text
stringlengths
10
2.72M
package com.tencent.mm.ui.contact; public abstract class m extends n { public a ujV; public abstract void a(String str, int[] iArr, boolean z); public abstract void acV(); public m(l lVar, boolean z, int i) { super(lVar, z, i); } public void a(a aVar) { this.ujV = aVar; } }
class CarTest{ public static void main(String [] args){ Car c=new Car(); System.out.println(c.getMileage()); c.goStraight(25); c.turnLeft(); c.goStraight(30); c.turnRight(); c.goStraight(15); c.turnLeft(); c.goStraight(20); System.out.printf("총 주행거리는 %d m입니다",c.getMileage()); } } class Car{ private int mileage; public void goStraight(int a){ System.out.println(a+"m만큼 직진"); mileage+=a; } public void turnLeft(){System.out.println("좌회전");} public void turnRight(){System.out.println("우회전");} public int getMileage(){ return mileage; } }
package com.tt.miniapp.titlemenu.item; import android.app.Activity; import android.content.Context; import android.text.TextUtils; import android.view.View; import com.tt.miniapp.AppbrandApplicationImpl; import com.tt.miniapp.shortcut.ShortcutEntity; import com.tt.miniapp.shortcut.ShortcutEventReporter; import com.tt.miniapp.shortcut.ShortcutService; import com.tt.miniapp.titlemenu.MenuDialog; import com.tt.miniapp.titlemenu.view.MenuItemView; import com.tt.miniapphost.AppBrandLogger; import com.tt.miniapphost.AppbrandContext; import com.tt.miniapphost.entity.AppInfoEntity; public class ShortcutMenuItem extends MenuItemAdapter { private MenuItemView mItemView; public ShortcutMenuItem(final Activity activity) { this.mItemView = new MenuItemView((Context)activity); this.mItemView.setIcon(activity.getDrawable(2097479742)); this.mItemView.setLabel(activity.getString(2097741850)); this.mItemView.setOnClickListener(new View.OnClickListener() { public void onClick(View param1View) { MenuDialog.inst(activity).dismiss(); ShortcutEventReporter.reportClick("user"); AppbrandApplicationImpl appbrandApplicationImpl = AppbrandApplicationImpl.getInst(); AppInfoEntity appInfoEntity = appbrandApplicationImpl.getAppInfo(); if (appInfoEntity == null) { AppBrandLogger.i("ShortcutMenuItem", new Object[] { "shortcut fail appinfo is null" }); ShortcutEventReporter.reportResult("no", "appInfo is null"); return; } ShortcutEntity shortcutEntity = (new ShortcutEntity.Builder()).setAppId(appInfoEntity.appId).setIcon(appInfoEntity.icon).setLabel(appInfoEntity.appName).setAppType(appInfoEntity.type).build(); ((ShortcutService)appbrandApplicationImpl.getService(ShortcutService.class)).tryToAddShortcut(activity, shortcutEntity); } }); if (!TextUtils.isEmpty(AppbrandContext.getInst().getInitParams().getShortcutClassName())) { this.mItemView.setVisibility(0); return; } this.mItemView.setVisibility(8); } public final String getId() { return "generate_shortcut"; } public MenuItemView getView() { return this.mItemView; } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\titlemenu\item\ShortcutMenuItem.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.example; import android.os.Handler; import android.text.TextUtils; /** * Created by shivam on 27/02/16. */ public class LoginInteractor { ILoginPresenter listener; public LoginInteractor(ILoginPresenter listener){ this.listener = listener; } public void checkLogin(final String email, final String password){ new Handler().postDelayed(new Runnable() { @Override public void run() { if ( !TextUtils.isEmpty(email) && email.contains("gmail")){ listener.success("Welcome"); }else{ listener.failed("email id is invalid"); } } }, 5000); } }
package oop1; public class Account { // 클래스 변수 - 대부분 상수 static final double RATE_OF_INTEREST = 0.021; // 상수는 모든 글자를 대문자로 적고, 여러 단어의 합성어인 경우 '_'를 사용하여 구분 // 인스턴스 변수 String owner; // 예금주 String no; // 계좌번호 String password; // 비밀번호 int balance; // 잔액 int period; // 가입기간 }
/* * Name: James Horton * Date: 12/11/2018 * Assignment: Final Project * File: Product.java */ package froggy.s.book.and.game.store; /** * * @author jh0375800 */ public class Product { private String itemCode; private String itemName; private String desc; private double price; public String getItemCode() { return itemCode; } public void setItemCode(String itemCode) { this.itemCode = itemCode; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Product(String itCd, String itN, String desc, double prc) { this.itemCode = itCd; this.itemName = itN; this.desc = desc; this.price = prc; } // end of full arg constructor public void displayItem() { System.out.println("\t" + itemCode + " " + itemName); } // end of display item } // end of class Product
package com.sparknetworks.exception; @SuppressWarnings("serial") public class QuestionException extends RuntimeException{ public QuestionException(String message){ super(message); } }
package cn.itsite.abase.demo; import android.app.Application; import android.util.Log; import androidx.annotation.NonNull; import cn.itsite.abase.mvvm.viewmodel.base.BaseViewModel; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; public class MainViewModel extends BaseViewModel<MainRepository> { public MainViewModel(@NonNull Application application) { super(application); Log.e(TAG, "MainViewModel: " ); } @Override public void onInitialize(Object... request) { Observable.create(emitter -> { Thread.sleep(4000); emitter.onComplete(); }).observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new BaseObserver<Object>() { @Override public void onSuccess(Object response) { Log.e(TAG, "开始: " + response); } }); } }
package hirondelle.web4j.ui.translate; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.Locale; import java.util.regex.*; import hirondelle.web4j.BuildImpl; import hirondelle.web4j.request.LocaleSource; import hirondelle.web4j.ui.tag.TagHelper; import hirondelle.web4j.util.EscapeChars; import hirondelle.web4j.util.Util; import hirondelle.web4j.util.Regex; /** Custom tag for translating regular text flow in large sections of a web page. <P><span class="highlight">This tag treats every piece of free flow text delimited by a tag as a unit of translatable base text</span>, and passes it to {@link Translator}. That is, all tags are treated as <em>delimiters</em> of units of translatable text. <P>This tag is suitable for translating most, but not all, of the regular text flow in a web page. <span class="highlight">It is suitable for translating markup that contains short, isolated snippets of text, that have no "structure", and no dynamic data</span>, such as the labels in a form, the column headers in a listing, and so on. (For many intranet applications, this makes up most of the free flow text appearing in the application.) Instead of using many separate <tt>&lt;w:txt&gt;</tt> {@link Text} tags to translate each item one by one, a single <tt>&lt;w:txtFlow&gt;</tt> tag can often be used to do the same thing in a single step. <P><span class="highlight">Using this class has two strong advantages</span> : <ul> <li>the effort needed to internationalize a page is greatly reduced <li>the markup will be significantly easier to read and maintain, since most of the free flow text remains unchanged from the single-language case </ul> <P> This tag is <em>not suitable</em> when the base text to be translated : <ul> <li>contains markup <li>has dynamic data of any sort <li>contains a <tt>TEXTAREA</tt> with a <em>non-empty</em> body. Such text will be seen as a translatable unit, which is usually undesired, since such text is usually not fixed, but dynamic (that is, from the database). (To avoid this, simply nest this tag <em>inside</em> the <tt>&lt;w:populate&gt;</tt> tag surrounding the form that contains the <tt>TEXTAREA</tt>. This ensures that the population is not affected by the action of this tag.) </ul> <P>For example, given this text containing markup : <PRE>The &lt;EM&gt;raison-d'etre&lt;/EM&gt; for this...</PRE> then this tag will split the text into three separate pieces, delimited by the <tt>EM</tt> tags. Then, each piece will be translated. For such items, this is almost always undesirable. Instead, one must use a <tt>&lt;w:txt&gt;</tt> {@link Text} tag, which can treat such items as a single unit of translatable text, without chopping it up into three pieces. <P><b>Example</b><br> Here, all of the <tt>LABEL</tt> tags in this form will have their content translated by the <tt>&lt;w:txtFlow&gt;</tt> tag : <PRE> &lt;w:populate style='edit' using="myUser"&gt; &lt;w:txtFlow&gt; &lt;form action='blah.do' method='post' class="user-input"&gt; &lt;table align="center"&gt; &lt;tr&gt; &lt;td&gt; &lt;label class="mandatory"&gt;Email&lt;/label&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="text" name="Email Address" size='30'&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;label&gt;Age&lt;/label&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="text" name="Age" size="30"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;label&gt;Desired Salary&lt;/label&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="text" name="Desired Salary" size="30"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;label&gt; Birth Date &lt;/label&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="text" name="Birth Date" size="30"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;input type='submit' value='UPDATE'&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;/w:txtFlow&gt; &lt;/w:populate&gt; </PRE> */ public final class TextFlow extends TagHelper { /** By default, this tag will escape any special characters appearing in the text flow, using {@link EscapeChars#forHTML(String)}. To change that default behaviour, set this value to <tt>false</tt>. <P><span class="highlight">Exercise care that text is not doubly escaped.</span> For instance, if the text already contains character entities, and <tt>setEscapeChars</tt> is true, then the text <tt>&amp;amp;</tt> will be emitted by this tag as <tt>&amp;amp;amp;</tt>, for example. */ public void setEscapeChars(boolean aValue){ fEscapeChars = aValue; } /** Translate each piece of free flow text appearing in <tt>aOriginalBody</tt>. <P>Each piece of text is delimited by one or more tags, and is translated using the configured {@link Translator}. Leading or trailing white space is preserved. */ @Override protected String getEmittedText(String aOriginalBody) { final StringBuffer result = new StringBuffer(); final StringBuffer snippet = new StringBuffer(); boolean isInsideTag = false; final StringCharacterIterator iterator = new StringCharacterIterator(aOriginalBody); char character = iterator.current(); while (character != CharacterIterator.DONE ){ if (character == '<') { doStartTag(result, snippet, character); isInsideTag = true; } else if (character == '>') { doEndTag(result, character); isInsideTag = false; } else { doRegularCharacter(result, snippet, isInsideTag, character); } character = iterator.next(); } if( Util.textHasContent(snippet.toString()) ) { appendTranslation(snippet, result); } return result.toString(); } // PRIVATE // static Pattern TRIMMED_TEXT = Pattern.compile("((?:\\S(?:.)*\\S)|(?:\\S))"); private boolean fEscapeChars = true; private LocaleSource fLocaleSource = BuildImpl.forLocaleSource(); private Translator fTranslator = BuildImpl.forTranslator(); private void doStartTag(StringBuffer aResult, StringBuffer aSnippet, char aCharacter) { if (Util.textHasContent(aSnippet.toString()) ){ appendTranslation(aSnippet, aResult); } else { //often contains just spaces and/or new lines, which are just appended aResult.append(aSnippet.toString()); } aSnippet.setLength(0); aResult.append(aCharacter); } private void doEndTag(StringBuffer aResult, char aCharacter) { aResult.append(aCharacter); } private void doRegularCharacter(StringBuffer aResult, StringBuffer aSnippet, boolean aIsInsideTag, char aCharacter) { if( aIsInsideTag ){ aResult.append(aCharacter); } else { aSnippet.append(aCharacter); } //fLogger.fine("Snippet : " + aSnippet); } /** The snippet may contain leading or trailing white space, or control chars (new lines), which must be preserved. */ private void appendTranslation(StringBuffer aSnippet, StringBuffer aResult){ if( Util.textHasContent(aSnippet.toString()) ) { StringBuffer translatedSnippet = new StringBuffer(); Matcher matcher = TRIMMED_TEXT.matcher(aSnippet.toString()); while ( matcher.find() ) { matcher.appendReplacement(translatedSnippet, getReplacement(matcher)); } matcher.appendTail(translatedSnippet); if( fEscapeChars ) { aResult.append(EscapeChars.forHTML(translatedSnippet.toString())); } else { aResult.append(translatedSnippet); } } else { aResult.append(aSnippet.toString()); } } private String getReplacement(Matcher aMatcher){ String result = null; String baseText = aMatcher.group(Regex.FIRST_GROUP); if (Util.textHasContent(baseText)){ Locale locale = fLocaleSource.get(getRequest()); result = fTranslator.get(baseText, locale); } else { result = baseText; } return EscapeChars.forReplacementString(result); } }
package a5; import java.beans.Beans; import java.io.NotSerializableException; import java.io.Serializable; import java.io.StreamCorruptedException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import util.annotations.Comp533Tags; import util.annotations.Tags; @Tags({Comp533Tags.DISPATCHING_SERIALIZER }) public class ADispatchingSerializer implements DispatchingSerializer{ @Override public void objectToBuffer(Object anOutputBuffer, Object anObject, List<Object> visitedObjects) throws NotSerializableException { if(!addToBuffer(anOutputBuffer, anObject, visitedObjects)){ if(anObject==null){ SerializerRegistry.getNullSerializer().objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject instanceof Integer){ SerializerRegistry.getValueSerializer(Integer.class).objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject instanceof Short){ SerializerRegistry.getValueSerializer(Short.class).objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject instanceof Long){ SerializerRegistry.getValueSerializer(Long.class).objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject instanceof Double){ SerializerRegistry.getValueSerializer(Double.class).objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject instanceof Float){ SerializerRegistry.getValueSerializer(Float.class).objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject instanceof Boolean){ SerializerRegistry.getValueSerializer(Boolean.class).objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject instanceof String){ SerializerRegistry.getValueSerializer(String.class).objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject instanceof ArrayList){ SerializerRegistry.getValueSerializer(ArrayList.class).objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject instanceof HashSet){ SerializerRegistry.getValueSerializer(HashSet.class).objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject instanceof Vector){ SerializerRegistry.getValueSerializer(Vector.class).objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject instanceof HashMap){ SerializerRegistry.getValueSerializer(HashMap.class).objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject instanceof Hashtable){ SerializerRegistry.getValueSerializer(Hashtable.class).objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject.getClass().isEnum()){ SerializerRegistry.getEnumSerializer().objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(util.misc.RemoteReflectionUtility.isList(anObject.getClass())){ SerializerRegistry.getListPatternSerializer().objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject.getClass().isArray()){ SerializerRegistry.getArraySerializer().objectToBuffer(anOutputBuffer, anObject, visitedObjects); }else if(anObject instanceof Serializable){ SerializerRegistry.getBeanSerializer().objectToBuffer(anOutputBuffer, anObject, visitedObjects); } } } @Override public Object objectFromBuffer(Object anInputBuffer, List<Object> retrievedObjects) throws StreamCorruptedException, NotSerializableException { String className = getClassName(anInputBuffer); if(className.equals(getNullClassName())){ return SerializerRegistry.getNullSerializer().objectFromBuffer(anInputBuffer, null, retrievedObjects); }else if(className.equals(getRefName())){ return getRetrievedObject(anInputBuffer, retrievedObjects); } Class<?> c = getClass(className); ValueSerializer serializer = SerializerRegistry.getValueSerializer(c); Class<?> altClass =SerializerRegistry.getDeserializingClass(c); if(altClass!=null){ return SerializerRegistry.getValueSerializer(altClass).objectFromBuffer(anInputBuffer, c, retrievedObjects); } if(serializer!=null){ return serializer.objectFromBuffer(anInputBuffer, c, retrievedObjects); }if(c.isEnum()){ return SerializerRegistry.getEnumSerializer().objectFromBuffer(anInputBuffer, c, retrievedObjects); }if(c.isArray()){ return SerializerRegistry.getArraySerializer().objectFromBuffer(anInputBuffer, c, retrievedObjects); }if(util.misc.RemoteReflectionUtility.isList(c)){ return SerializerRegistry.getListPatternSerializer().objectFromBuffer(anInputBuffer, c, retrievedObjects); } return SerializerRegistry.getBeanSerializer().objectFromBuffer(anInputBuffer, c, retrievedObjects); } public boolean addToBuffer(Object anOutputBuffer, Object anObject,List<Object> visitedObjects){ boolean reference=false; if(!visitedObjects.contains(anObject)){ visitedObjects.add(anObject); if(anOutputBuffer instanceof StringBuffer){ if(anObject==null){ ((StringBuffer)anOutputBuffer).append(getNullClassName()+":"); return false; } ((StringBuffer)anOutputBuffer).append(anObject.getClass().getName()+":"); }else if(anOutputBuffer instanceof ByteBuffer){ if(anObject==null){ ((ByteBuffer)anOutputBuffer).putInt(getNullClassName().length()); ((ByteBuffer)anOutputBuffer).put(getNullClassName().getBytes()); return false; } String name = anObject.getClass().getName(); ((ByteBuffer)anOutputBuffer).putInt(name.length()); ((ByteBuffer)anOutputBuffer).put(name.getBytes()); } }else{ reference=true; int ind =visitedObjects.indexOf(anObject); if(anOutputBuffer instanceof StringBuffer){ String index = new String(ind+""); ((StringBuffer)anOutputBuffer).append(getRefName()+":"+index.length()+":"+index); }else if(anOutputBuffer instanceof ByteBuffer){ ((ByteBuffer)anOutputBuffer).putInt(getRefName().length()); ((ByteBuffer)anOutputBuffer).put(getRefName().getBytes()); ((ByteBuffer)anOutputBuffer).putInt(ind); } } return reference; } public String getClassName(Object inputBuffer){ String className = ""; if(inputBuffer instanceof StringBuffer){ String[] parts =inputBuffer.toString().split(":", 2); ((StringBuffer) inputBuffer).delete(0, inputBuffer.toString().length()); ((StringBuffer) inputBuffer).append(parts[1]); className=parts[0]; }else if(inputBuffer instanceof ByteBuffer){ int length = ((ByteBuffer)inputBuffer).getInt(); byte[] chars = new byte[length]; ((ByteBuffer)inputBuffer).get(chars); className= new String(chars); } return className; } public Class<?> getClass(String className){ Class<?> c = null; try { c =Class.forName(className); } catch (ClassNotFoundException e) {e.printStackTrace();} return c; } public Object getRetrievedObject(Object anInputBuffer, List<Object> retrievedObjects) throws StreamCorruptedException, NotSerializableException{ int index = (Integer)SerializerRegistry.getValueSerializer(Integer.class).objectFromBuffer(anInputBuffer, Integer.class, retrievedObjects); retrievedObjects.remove(retrievedObjects.size()-1); return retrievedObjects.get(index); } public String getNullClassName(){ return "nullClass"; } public String getRefName(){ return ".ref"; } }
/* * 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 com.mycompany.gui.hiba; import com.codename1.components.ImageViewer; import com.codename1.components.SpanLabel; import com.codename1.ui.Button; import com.codename1.ui.Command; import com.codename1.ui.Container; import com.codename1.ui.Display; import com.codename1.ui.EncodedImage; import com.codename1.ui.Font; import com.codename1.ui.FontImage; import com.codename1.ui.Form; import com.codename1.ui.Image; import com.codename1.ui.Label; import com.codename1.ui.Slider; import com.codename1.ui.URLImage; import com.codename1.ui.events.ActionEvent; import com.codename1.ui.events.ActionListener; import com.codename1.ui.geom.Dimension; import com.codename1.ui.layouts.BoxLayout; import com.codename1.ui.layouts.FlowLayout; import com.codename1.ui.plaf.Border; import com.codename1.ui.plaf.Style; import com.mycompany.entities.hiba.Product; import com.mycompany.entities.hiba.Rating; import com.mycompany.services.hiba.ServiceProduct; import com.mycompany.services.hiba.ServiceRating; import java.io.IOException; import java.util.ArrayList; /** * * @author Hiba */ public class ShowListProduct { Form f; // Slider s= null; public ShowListProduct() { f=new Form("Shop",BoxLayout.y()); Menu m=new Menu(f); f.getToolbar().addMaterialCommandToOverflowMenu("cart",FontImage.MATERIAL_ADD_SHOPPING_CART,(e)->{ Cart c=new Cart(); c.getF().show(); }); //*******************Recuperer la liste de produit de la base*************************************************** ServiceProduct sp1=new ServiceProduct(); ServiceRating sr=new ServiceRating(); ArrayList<Product> list=sp1.showList(); //***************************Recherche******************************************************************* f.getToolbar().addSearchCommand(e->{ System.out.println(e.getSource()); Product psearch=sp1.searchByName((String)e.getSource()); System.out.println(psearch); if(psearch.getDescription()!=null) { Container c1 =getContainer(psearch); f.removeAll(); f.add(c1); f.revalidate(); } else { f.removeAll(); for(Product p : list) { Container c1=getContainer(p); f.add(c1); } f.revalidate(); } }); //********************************Parcourir la liste**************************************************************** for(Product p : list) { Container c1=getContainer(p); f.add(c1); } } public Container getContainer(Product p) { ServiceRating sr=new ServiceRating(); Container c1 =new Container(BoxLayout.x()); Container c3 =new Container(BoxLayout.y()); c1.getStyle().setBorder(Border.createLineBorder(2)); c1.getStyle().setMargin(1, 1, 1, 1); c1.getStyle().setPadding(20, 20, 0, 0); //****************************les elements du containers******************************************************** ImageViewer iv=new ImageViewer(); try { iv.setImage(Image.createImage("/"+ p.getImg()).scaled(100, 100)); } catch (IOException ex) { System.out.println("err"); } //Button b=new Button(image2.scaled(30,30)); Button b=new Button("add"); Slider s=createStarRankSlider(0); s.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { Rating r=new Rating(1,s.getProgress(),p.getId_product()); sr.addRate(r); } } ); Label l1=new Label("$"+Float.toString(p.getPrice())); // l1.getStyle().set(0xC40C0C); c1.add(iv); c1.add(c3); c3.add(new SpanLabel(p.getName())); c3.add(l1); c3.add(FlowLayout.encloseCenter(s)); c3.add(b); //*******************************Action sur le bouton add***************************************************** b.addActionListener(e->{ ShowProduct sp=new ShowProduct(p.getId_product()); sp.getF().show(); }); return c1; } private void initStarRankStyle(Style s, Image star) { s.setBackgroundType(Style.BACKGROUND_IMAGE_TILE_BOTH); s.setBorder(Border.createEmpty()); s.setBgImage(star); s.setBgTransparency(0); } private Slider createStarRankSlider(int i) { Slider starRank = new Slider(); starRank.setEditable(true); starRank.setMinValue(0); starRank.setMaxValue(5); Font fnt = Font.createTrueTypeFont("native:MainLight", "native:MainLight"). derive(Display.getInstance().convertToPixels(5, true), Font.STYLE_PLAIN); Style s = new Style(0xffff33, 0, fnt, (byte)0); Image fullStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage(); s.setOpacity(100); s.setFgColor(0); starRank.setProgress(i); Image emptyStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage(); initStarRankStyle(starRank.getSliderEmptySelectedStyle(), emptyStar); initStarRankStyle(starRank.getSliderEmptyUnselectedStyle(), emptyStar); initStarRankStyle(starRank.getSliderFullSelectedStyle(), fullStar); initStarRankStyle(starRank.getSliderFullUnselectedStyle(), fullStar); starRank.setPreferredSize(new Dimension(fullStar.getWidth() * 5, fullStar.getHeight())); return starRank; } public Form getF() { return f; } public void setF(Form f) { this.f = f; } }
package edu.softwarica.MeetingAttendence.View; import edu.softwarica.MeetingAttendence.Controller.Controllerregister; import edu.softwarica.MeetingAttendence.Model.Modelregister; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.regex.Pattern; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPasswordField; import javax.swing.JRadioButton; import javax.swing.JTextField; public class registration extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; public JFrame frame; private JTextField firstname; private JTextField lastname; private JTextField email; private JTextField address; private JTextField phone; private JPasswordField password; private JTextField availableTime; private JTextField unavailableTime; JRadioButton rdbtnFemale, rdbtnMale; String filepath; JButton btnAvDay; JButton btnUnavDay; JButton btnImage; JButton btnAvTime; JButton btnUnavTime; JButton btnRegister; JButton btnReset; JButton btnExit; JLabel label; Font font, font1, font2; int count = 0; private JLabel lblDay; private JLabel lblTim; public registration() { initialize(); } private void initialize() { frame = new JFrame(); frame.setTitle("Registration"); frame.setBounds(400, 100, 820, 400); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.getContentPane().setLayout(null); font = new Font("Times New Roman", Font.ITALIC, 20); font2 = new Font("Times New Roman", Font.ITALIC, 30); font1 = new Font("Times New Roman", Font.ITALIC, 15); frame.setResizable(false); JLabel lblRegister = new JLabel("Registration Form"); lblRegister.setForeground(Color.BLACK); lblRegister.setFont(font); lblRegister.setBounds(30, 40, 329, 30); frame.getContentPane().add(lblRegister); JLabel lblFname = new JLabel("First Name:"); lblFname.setBounds(30, 85, 100, 25); frame.getContentPane().add(lblFname); lblFname.setFont(font1); firstname = new JTextField(); firstname.setBounds(30, 110, 235, 25); frame.getContentPane().add(firstname); firstname.setFont(font1); firstname.setColumns(10); JLabel lblLname = new JLabel("Last Name:"); lblLname.setBounds(290, 85, 79, 25); frame.getContentPane().add(lblLname); lblLname.setFont(font1); lastname = new JTextField(); lastname.setBounds(290, 110, 235, 25); frame.getContentPane().add(lastname); lastname.setFont(font1); lastname.setColumns(10); JLabel lblEmail = new JLabel("Email Address:"); lblEmail.setBounds(550, 85, 120, 25); frame.getContentPane().add(lblEmail); lblEmail.setFont(font1); email = new JTextField(); email.setBounds(550, 110, 235, 25); frame.getContentPane().add(email); email.setFont(font1); email.setColumns(10); JLabel lblPassword = new JLabel("Password:"); lblPassword.setBounds(290, 140, 79, 25); frame.getContentPane().add(lblPassword); lblPassword.setFont(font1); password = new JPasswordField(); password.setBounds(290, 165, 235, 25); password.setFont(font1); frame.getContentPane().add(password); JLabel lblAddress = new JLabel("Location:"); lblAddress.setBounds(30, 140, 79, 25); frame.getContentPane().add(lblAddress); lblAddress.setFont(font1); address = new JTextField(); address.setBounds(30, 165, 235, 25); frame.getContentPane().add(address); address.setFont(font1); address.setColumns(10); JLabel lblGender = new JLabel("Gender:"); lblGender.setBounds(550, 140, 60, 25); frame.getContentPane().add(lblGender); lblGender.setFont(font1); rdbtnMale = new JRadioButton("Male"); rdbtnMale.setBackground(Color.white); rdbtnMale.setBounds(550, 165, 70, 25); rdbtnMale.setFont(font1); frame.getContentPane().add(rdbtnMale); rdbtnFemale = new JRadioButton("Female"); rdbtnFemale.setBounds(630, 165, 79, 25); rdbtnFemale.setFont(font1); rdbtnFemale.setBackground(Color.white); frame.getContentPane().add(rdbtnFemale); ButtonGroup bg = new ButtonGroup(); bg.add(rdbtnMale); bg.add(rdbtnFemale); JLabel lblPhone = new JLabel("Pay Grade:"); lblPhone.setBounds(30, 200, 80, 25); frame.getContentPane().add(lblPhone); lblPhone.setFont(font1); phone = new JTextField(); phone.setBounds(30, 230, 235, 25); frame.getContentPane().add(phone); phone.setFont(font1); phone.setColumns(10); JLabel lblImage = new JLabel("Image:"); lblImage.setBounds(290, 200, 56, 25); lblImage.setFont(font1); frame.getContentPane().add(lblImage); btnImage = new JButton("Image"); btnImage.setBounds(290, 230, 100, 25); btnImage.setBackground(Color.white); frame.getContentPane().add(btnImage); btnImage.setFont(font1); label = new JLabel(""); label.setBounds(344, 421, 190, 14); label.setFont(font1); frame.getContentPane().add(label); JLabel lblAvailableTimeSlots = new JLabel("Available time slots:"); lblAvailableTimeSlots.setBounds(30, 270, 151, 25); frame.getContentPane().add(lblAvailableTimeSlots); lblAvailableTimeSlots.setFont(font1); availableTime = new JTextField(); availableTime.setBounds(30, 300, 220, 25); availableTime.setFont(font1); frame.getContentPane().add(availableTime); availableTime.setColumns(10); JLabel lblUnavailableTimeSlots = new JLabel("Unavailable time slots:"); lblUnavailableTimeSlots.setBounds(430, 270, 200, 25); frame.getContentPane().add(lblUnavailableTimeSlots); lblUnavailableTimeSlots.setFont(font1); unavailableTime = new JTextField(); unavailableTime.setBounds(430, 300, 200, 25); frame.getContentPane().add(unavailableTime); unavailableTime.setColumns(10); // JMenuBar menuBar = new JMenuBar(); // menuBar.setBounds(0, 0, 546, 25); // frame.getContentPane().add(menuBar); // // JMenu mnMenu = new JMenu("Menu"); // menuBar.add(mnMenu); // // JMenuItem mntmExit = new JMenuItem("Exit"); // mnMenu.add(mntmExit); btnRegister = new JButton("Register"); btnRegister.setBounds(70, 340, 89, 25); btnRegister.setBackground(Color.white); frame.getContentPane().add(btnRegister); btnRegister.setFont(font1); btnReset = new JButton("Reset"); btnReset.setBounds(170, 340, 89, 25); btnReset.setBackground(Color.white); frame.getContentPane().add(btnReset); btnReset.setFont(font1); btnExit = new JButton("Exit"); btnExit.setBounds(270, 340, 89, 25); btnExit.setBackground(Color.white); frame.getContentPane().add(btnExit); btnExit.setFont(font1); /////Two button for accessing Jpanel btnAvDay = new JButton("Day"); btnAvDay.setBounds(270, 300, 60, 25); btnAvDay.setFont(new Font("Calibri", Font.BOLD, 12)); frame.getContentPane().add(btnAvDay); btnAvDay.setBackground(Color.white); btnAvDay.addActionListener(this); btnUnavDay = new JButton("Day"); btnUnavDay.setBounds(650, 300, 60, 25); btnUnavDay.setFont(new Font("Calibri", Font.BOLD, 12)); btnUnavDay.setBackground(Color.white); frame.getContentPane().add(btnUnavDay); btnAvTime = new JButton("Time"); btnAvTime.setBounds(350, 300, 65, 25); btnAvTime.setFont(new Font("Calibri", Font.BOLD, 12)); btnAvTime.setBackground(Color.white); frame.getContentPane().add(btnAvTime); btnUnavTime = new JButton("Time"); btnUnavTime.setBounds(730, 300, 65, 25); btnUnavTime.setFont(new Font("Calibri", Font.BOLD, 12)); btnUnavTime.setBackground(Color.white); frame.getContentPane().add(btnUnavTime); // lblDay = new JLabel("Day"); // lblDay.setBounds(420, 310, 46, 25); // lblDay.setFont(new Font("Calibri", Font.BOLD, 12)); // frame.getContentPane().add(lblDay); // // lblTim = new JLabel("Time"); // lblTim.setBounds(485, 310, 46, 25); // frame.getContentPane().add(lblTim); // lblTim.setFont(new Font("Calibri", Font.BOLD, 12)); btnImage.addActionListener(this); btnUnavDay.addActionListener(this); btnAvTime.addActionListener(this); btnUnavTime.addActionListener(this); btnRegister.addActionListener(this); btnReset.addActionListener(this); btnExit.addActionListener(this); btnRegister.setFont(new Font("Calibri", Font.BOLD, 12)); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnAvDay) { JFrame frame1 = new JFrame(); frame1.setBounds(700, 450, 111, 68); frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame1.getContentPane().setLayout(null); String time[] = new String[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thurusday", "Friday", "Saturday"}; JComboBox cb = new JComboBox(time); cb.setBounds(0, 0, 102, 33); frame1.getContentPane().add(cb); frame1.setVisible(true); String data = "Programming language Selected: " + cb.getItemAt(cb.getSelectedIndex()); ///String data1=null; if (data != null) { ///textField_2.setText(""); cb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String data1 = (String) cb.getItemAt(cb.getSelectedIndex()); if (e.getSource() == cb && count == 0) { ///count=count+1; availableTime.setText("" + availableTime.getText().concat(data1) + ":"); System.out.println("Count=" + count); } } }); } } else if (e.getSource() == btnUnavDay) { JFrame frame1 = new JFrame(); frame1.setBounds(700, 450, 111, 68); frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame1.getContentPane().setLayout(null); String time[] = new String[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thurusday", "Friday", "Saturday"}; JComboBox cb = new JComboBox(time); cb.setBounds(0, 0, 102, 33); frame1.getContentPane().add(cb); frame1.setVisible(true); String data = "Programming language Selected: " + cb.getItemAt(cb.getSelectedIndex()); ///String data1=null; if (data != null) { ///textField_2.setText(""); cb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String data1 = (String) cb.getItemAt(cb.getSelectedIndex()); if (e.getSource() == cb && count == 0) { ///count=count+1; unavailableTime.setText("" + unavailableTime.getText().concat(data1) + ":"); System.out.println("Count=" + count); } } }); } } else if (e.getSource() == btnAvTime) { JFrame frame1 = new JFrame(); frame1.setBounds(700, 450, 111, 68); frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame1.getContentPane().setLayout(null); String time[] = new String[]{"1:00pm", "1:30pm", "2:00pm", "2:30pm", "3:00pm", "3:30pm", "4:00pm", "4:30pm", "5:00pm", "5:30pm", "6:00pm", "6:30pm", "7:00pm", "7:30pm", "8:00pm", "8:30pm", "9:00pm", "9:30pm", "10:00pm", "10:30pm", "11:00pm", "11:30pm", "12:00pm", "-------"}; JComboBox cb = new JComboBox(time); cb.setBounds(0, 0, 102, 33); frame1.getContentPane().add(cb); frame1.setVisible(true); String data = "Programming language Selected: " + cb.getItemAt(cb.getSelectedIndex()); /////String data1=null; if (data != null) { ///textField_2.setText(""); cb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub String data1 = (String) cb.getItemAt(cb.getSelectedIndex()); if (e.getSource() == cb && count == 0) { count = count + 1; availableTime.setText(availableTime.getText().concat(data1)); System.out.println("Count=" + count); } else if (e.getSource() == cb && count != 0) { availableTime.setText(availableTime.getText().concat("---" + data1 + ";")); System.out.println("Count1=" + count); count = count - 1; } } }); } } else if (e.getSource() == btnUnavTime) { JFrame frame1 = new JFrame(); frame1.setBounds(700, 450, 111, 68); frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame1.getContentPane().setLayout(null); String time[] = new String[]{"1:00pm", "1:30pm", "2:00pm", "2:30pm", "3:00pm", "3:30pm", "4:00pm", "4:30pm", "5:00pm", "5:30pm", "6:00pm", "6:30pm", "7:00pm", "7:30pm", "8:00pm", "8:30pm", "9:00pm", "9:30pm", "10:00pm", "10:30pm", "11:00pm", "11:30pm", "12:00pm", "-------"}; JComboBox cb = new JComboBox(time); cb.setBounds(0, 0, 102, 33); frame1.getContentPane().add(cb); frame1.setVisible(true); String data = "Programming language Selected: " + cb.getItemAt(cb.getSelectedIndex()); if (data != null) { cb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String data1 = (String) cb.getItemAt(cb.getSelectedIndex()); if (e.getSource() == cb && count == 0) { count = count + 1; unavailableTime.setText(unavailableTime.getText().concat(data1)); System.out.println("Count=" + count); } else if (e.getSource() == cb && count != 0) { unavailableTime.setText(unavailableTime.getText().concat("---" + data1 + ";")); System.out.println("Count1=" + count); count = count - 1; } } }); } } else if (e.getSource() == btnImage) { JFileChooser fc = new JFileChooser(); int i = fc.showOpenDialog(this); if (i == JFileChooser.APPROVE_OPTION) { File f = fc.getSelectedFile(); filepath = f.getPath(); label.setText(filepath); } } else if (e.getSource() == btnRegister) { boolean b = Pattern.matches("^[A-Za-z0-9+_.-]+@(.+)$", email.getText()); boolean c = firstname.getText().equals("") && lastname.getText().equals("") && email.getText().equals("") && address.getText().equals("") && password.getText().equals("") && availableTime.getText().equals("") && unavailableTime.getText().equals(""); if (c == true) { JOptionPane.showMessageDialog(frame, "Empty field "); } if (b == false) { JOptionPane.showMessageDialog(frame, "Please enter valid email"); } if (b && c == false) { getDataCheck(); System.out.println("Hello"); } } else if (e.getSource() == btnReset) { firstname.setText(""); lastname.setText(""); email.setText(""); address.setText(""); phone.setText(""); password.setText(""); availableTime.setText(""); unavailableTime.setText(""); } else if (e.getSource() == btnExit) { frame.dispose(); } } public void getDataCheck() { String gender; if (rdbtnMale.isSelected()) { gender = "Male"; } else { gender = "Female"; } Modelregister ob = new Modelregister(); ob.setFname(firstname.getText()); ob.setLname(lastname.getText()); ob.setEmail(email.getText()); ob.setPass(password.getText()); ob.setAddress(address.getText()); ob.setGender(gender); ob.setPhone(phone.getText()); ob.setAvtime(availableTime.getText()); ob.setUnavtime(unavailableTime.getText()); ob.setImg(filepath); /// boolean status = Controllerregister.reisterUser(ob); if (status == true) { JOptionPane.showMessageDialog(frame, "Registration sucessfull"); frame.dispose(); } else { JOptionPane.showMessageDialog(frame, "Registration Unsucessfull"); } } }
package com.tencent.mm.plugin.ext.voicecontrol; import com.tencent.mm.ab.b; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.network.k; import com.tencent.mm.network.q; import com.tencent.mm.protocal.c.dk; import com.tencent.mm.protocal.c.dl; import com.tencent.mm.protocal.c.dm; import com.tencent.mm.protocal.c.dq; import com.tencent.mm.sdk.platformtools.x; public final class a extends l implements k { public String appId; public int bNI = 1; public int dHI; public int dHJ; b diG; private e diJ; public int iLq; public com.tencent.mm.bk.b iLr; public String iLs; public dq iLt; public dk iLu; int iLv = 5000; long iLw = 0; public int sH; public a(int i, String str, int i2, String str2, dq dqVar) { boolean z = true; this.appId = str; this.iLq = i; this.sH = 1; this.dHI = i2; this.iLt = dqVar; this.iLu = null; this.iLs = str2; String str3 = "MicroMsg.ext.NetSceneAppVoiceControl"; String str4 = "[voiceControl] new NetSceneAppVoiceControl, opCode=%s, appId=%s, voiceId=%s, totalLen=%s, controlType=%s, %s, %s"; Object[] objArr = new Object[7]; objArr[0] = Integer.valueOf(1); objArr[1] = str; objArr[2] = Integer.valueOf(i); objArr[3] = Integer.valueOf(i2); objArr[4] = Integer.valueOf(1); if (dqVar == null) { z = false; } objArr[5] = Boolean.valueOf(z); objArr[6] = Boolean.valueOf(false); x.i(str3, str4, objArr); } public a(int i, String str, dk dkVar, long j) { this.appId = str; this.iLq = i; this.sH = 1; this.iLt = null; this.iLu = dkVar; this.iLw = j; x.i("MicroMsg.ext.NetSceneAppVoiceControl", "[voiceControl] new NetSceneAppVoiceControl, opCode=%s, appId=%s, voiceId=%s, controlType=%s, %s, %s", new Object[]{Integer.valueOf(2), str, Integer.valueOf(i), Integer.valueOf(1), Boolean.valueOf(false), Boolean.valueOf(true)}); } public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) { if (i2 == 0 && i3 == 0 && qVar != null) { x.i("MicroMsg.ext.NetSceneAppVoiceControl", "[voiceControl] onGYNetEnd netId %d , errType %d, errCode %d, %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3), str}); } else { x.e("MicroMsg.ext.NetSceneAppVoiceControl", "[voiceControl] onGYNetEnd netId %d , errType %d, errCode %d, %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3), str}); } if (this.diJ != null) { this.diJ.a(i2, i3, str, this); } else { x.e("MicroMsg.ext.NetSceneAppVoiceControl", "[voiceControl] callback null"); } } public final int getType() { return 985; } public final int a(com.tencent.mm.network.e eVar, e eVar2) { this.diJ = eVar2; com.tencent.mm.ab.b.a aVar = new com.tencent.mm.ab.b.a(); aVar.dIF = 985; aVar.uri = "/cgi-bin/micromsg-bin/appvoicecontrol"; aVar.dIG = new dl(); aVar.dIH = new dm(); aVar.dII = 0; aVar.dIJ = 0; this.diG = aVar.KT(); dl dlVar = (dl) this.diG.dID.dIL; dlVar.qZc = this.bNI; dlVar.jQb = this.appId; dlVar.rdH = this.iLq; dlVar.rdI = this.sH; dlVar.rdJ = this.iLt; dlVar.rdK = this.iLu; return a(eVar, this.diG, this); } }
package com.lti.handson2; import java.util.Scanner; public class CountWords { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter the string:"); String s=sc.next(); System.out.println("There are" + count(s)+ "words in the string."); } static int count(String s) { int count=0; char c[]=new char[s.length()]; for(int i=0;i<s.length();i++) { c[i]=s.charAt(i); if( ((i>0)&&(c[i]!=' ')&&(c[i-1]==' ')) || ((c[0]!=' ')&&(i==0))) { count++; } } return count; } }
/** * Tanner Yost * ManageSystem.java * * Date: 12/16/2018 */ package tanneryost.flightreservation; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class ManageSystem extends AppCompatActivity { public static final String TAG = "ManageSystem"; EditText editAccountName; EditText editPassword; Button submitButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manage_system); editAccountName = (EditText) findViewById(R.id.editAccountName); editPassword = (EditText) findViewById(R.id.editPassword); submitButton = (Button) findViewById(R.id.submitButton); submitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(isEmpty(editAccountName) || isEmpty(editPassword)) { Log.i(TAG, "Error - fields must be set"); toastMaker("All fields must be set"); } else { if (checkField(editAccountName.getText().toString()) && checkField(editPassword.getText().toString())) { String name = editAccountName.getText().toString(); String passwd = editPassword.getText().toString(); if (name.equals("admin2") && passwd.equals("admin2")) { toastMaker("Success"); login(view); } } else { toastMaker("Incorrect account name and/or password."); } } } }); } public void login (View view) { Intent intent = new Intent(this, ManageSystemLoggedIn.class); startActivity(intent); } private boolean checkField(String field) { char[] word = field.toCharArray(); int character = 0; int digit = 0; for (char item : word) { if (Character.isLetter(item)) character++; else if (Character.isDigit(item)) digit++; } if (character >= 3 && digit >= 1) return true; return false; } private void toastMaker(String message) { Toast t = Toast.makeText(this.getApplicationContext(),message,Toast.LENGTH_LONG ); t.setGravity(Gravity.CENTER_VERTICAL,0,0); t.show(); } private boolean isEmpty(EditText textToCheck) { return textToCheck.getText().toString().trim().length() == 0; } }
package com.days.moment.qna.service; import com.days.moment.common.dto.PageRequestDTO; import com.days.moment.common.dto.PageResponseDTO; import com.days.moment.miniboard.domain.Mini; import com.days.moment.qna.domain.Qna; import com.days.moment.qna.dto.QnaDTO; import com.days.moment.qna.mapper.QnaMapper; import lombok.RequiredArgsConstructor; import lombok.extern.log4j.Log4j2; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Collectors; @Service @Log4j2 @RequiredArgsConstructor public class QnaServiceImpl implements QnaService{ private final QnaMapper qnaMapper; @Override public Long register(QnaDTO qnaDTO) { Qna qna = qnaDTO.getDomain(); qnaMapper.insert(qna); return qna.getQnaId(); } @Override public boolean originModify(QnaDTO qnaDTO) { Qna qna = qnaDTO.getDomain(); Long qnaId = qna.getQnaId(); return qnaMapper.originUpdate(qna) > 0; } @Override public boolean answerModify(QnaDTO qnaDTO) { Qna qna = qnaDTO.getDomain(); Long qnaId = qna.getQnaId(); return qnaMapper.answerUpdate(qna) > 0; } @Override public PageResponseDTO<QnaDTO> getDTOList(PageRequestDTO pageRequestDTO) { List<QnaDTO> dtoList = qnaMapper.getList(pageRequestDTO).stream().map(qna -> qna.getDTO()).collect(Collectors.toList()); int count = qnaMapper.getCount(pageRequestDTO); PageResponseDTO<QnaDTO> pageResponseDTO = PageResponseDTO.<QnaDTO>builder() .dtoList(dtoList) .count(count) .build(); return pageResponseDTO; } @Override public QnaDTO read(Long qnaId) { Qna qna = qnaMapper.select(qnaId); if(qna != null) { return qna.getDTO(); } return null; } @Override public boolean remove(Long qnaId) { return qnaMapper.delete(qnaId) > 0; } }
package 笔试题; import java.util.Collections; import java.util.LinkedList; import java.util.Scanner; public class 压缩字符 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String next = scanner.next(); scanner.close(); System.out.println(decode(next)); } public static String decode(String words){ while (words.contains("]")){ int right = words.indexOf("]"); int left = words.lastIndexOf("[", right); String repeatStr = words.substring(left+1, right); String[] split = repeatStr.split("\\|"); words = words.replace("["+repeatStr+"]", String.join("", Collections.nCopies(Integer.parseInt(split[0]), split[1]))); } return words; } // public static String decode(String str){ // LinkedList<String> strStack=new LinkedList<>(); // LinkedList<Integer> numStack=new LinkedList<>(); // StringBuilder sb=new StringBuilder(); // int count=0; // for (int i=0;i<str.length();i++){ // char c=str.charAt(i); // if (c>='0'&&c<='9'){ // count=10*count+(c-'0'); // }else if (c=='['){ // strStack.add(sb.toString()); // sb=new StringBuilder(); // }else if (c=='|'){ // numStack.add(count); // count=0; // }else if (c==']'){ // StringBuilder temp=new StringBuilder(); // count=numStack.removeLast(); // String now=sb.toString(); // while (count!=0){ // temp.append(now); // count--; // } // sb=new StringBuilder(); // sb.append(strStack.removeLast()); // sb.append(temp.toString()); // }else { // sb.append(c); // } // } // return sb.toString(); // } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gr.spinellis.ckjm; import gr.spinellis.ckjm.utils.FieldAccess; import gr.spinellis.ckjm.utils.LoggerHelper; import gr.spinellis.ckjm.utils.MethodCoupling; import gr.spinellis.ckjm.utils.MethodInvokation; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.*; import java.util.*; /** * @author marian */ public class IcAndCbmClassVisitor extends AbstractClassVisitor { private Method[] mMethods; private JavaClass mCurrentClass; private ConstantPoolGen mParentPool; private List<Method[]> mParentsMethods; private Set<MethodInvokation> mInvokationsFromParents; private Set<MethodInvokation> mInvoktionsFromCurrentClass; private Set<FieldAccess> mParentsReaders; private Set<FieldAccess> mCurrentClassSetters; private Set<MethodCoupling> mMethodCouplings; private JavaClass[] mParents; private JavaClass mParent; private String mParentClassName; /** * How many inheritet methods use a field, that is defined * in a new/redefined method. */ private int mCase1; /** * How many inherited methods call a redefined method * and use the return value of the redefined method. */ private int mCase2; /** * How many inherited methods are called by a redefined method * and use a parameter that is defined in the redefined method. */ private int mCase3; IcAndCbmClassVisitor(IClassMetricsContainer classMap) { super(classMap); } @Override protected void visitJavaClass_body(JavaClass jc) { mCase1 = mCase2 = mCase3 = 0; mCurrentClass = jc; try { mParents = jc.getSuperClasses(); mParentsMethods = new ArrayList<Method[]>(); mMethods = jc.getMethods(); mInvokationsFromParents = new TreeSet<MethodInvokation>(); mInvoktionsFromCurrentClass = new TreeSet<MethodInvokation>(); mParentsReaders = new TreeSet<FieldAccess>(); mCurrentClassSetters = new TreeSet<FieldAccess>(); mMethodCouplings = new TreeSet<MethodCoupling>(); for (JavaClass j : mParents) { mParentPool = new ConstantPoolGen(j.getConstantPool()); mParent = j; mParentsMethods.add(j.getMethods()); for (Method m : j.getMethods()) { m.accept(this); } } for (Method m : mMethods) { if (hasBeenDefinedInParentToo(m)) { investigateMethod(m); } investigateMethodAndLookForSetters(m); } countCase1(); countCase2(); //TODO: remove duplications countCase3(); saveResults(); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } } /** * It is used to visit methods of parents of investigated class. */ @Override public void visitMethod(final Method m) { MethodGen mg = new MethodGen(m, getParentClassName(), mParentPool); if (!mg.isAbstract() && !mg.isNative()) { for (InstructionHandle ih = mg.getInstructionList().getStart(); ih != null; ih = ih.getNext()) { Instruction i = ih.getInstruction(); if (!visitInstruction(i)) { i.accept(new org.apache.bcel.generic.EmptyVisitor() { @Override public void visitInvokeInstruction(InvokeInstruction ii) { String methodName = "", className = ""; Type[] args = ii.getArgumentTypes(mParentPool); methodName = ii.getMethodName(mParentPool); className = ii.getClassName(mParentPool); MethodInvokation mi = new MethodInvokation(className, methodName, args, getParentClassName(), m.getName(), m.getArgumentTypes()); mInvokationsFromParents.add(mi); } @Override public void visitFieldInstruction(FieldInstruction fi) { if (isGetInstruction(fi)) { FieldAccess fa = new FieldAccess(fi.getFieldName(mParentPool), m, mParent); mParentsReaders.add(fa); } } private boolean isGetInstruction(FieldInstruction fi) { String instr = fi.toString(mParentPool.getConstantPool()); return instr.startsWith("get"); } }); } } } } /** * Is mi a call of a redefined method? * * @param mi * @return Return true only when mi is an invokation of a method thas has been redefined in investigated class. */ private boolean callsRedefinedMethod(MethodInvokation mi) { for (Method m : mMethods) { if (isInvocationOfTheMethod(m, mi)) { mi.setDestClass(mClassName); return true; } } return false; } private boolean compareTypes(Type[] args, Type[] args2) { boolean areEquals = args.length == args2.length; if (areEquals == true) { for (int i = 0; i < args.length; i++) { String miArgSignature = args2[i].getSignature(); if (!args[i].getSignature().equals(miArgSignature)) { areEquals = false; break; } } } return areEquals; } private void countCase1() { for (FieldAccess fap : mParentsReaders) { if (!isFieldDefinedInCurrentClass(fap.getFieldName())) { for (FieldAccess fac : mCurrentClassSetters) { if (fap.getFieldName().equals(fac.getFieldName())) { MethodCoupling mc = new MethodCoupling(fap.getAccessorClass().getClassName(), fap.getAccessor().getName(), fac.getAccessorClass().getClassName(), fac.getAccessor().getName()); if (mMethodCouplings.add(mc)) { mCase1++; //System.out.println("!!Case1!" + mc.toString() ); break; } } } } } } private void countCase2() { for (MethodInvokation mi : mInvokationsFromParents) { if (isFromParents(mi)) { if (mi.isNotConstructorInvocation()) { if (callsRedefinedMethod(mi)) { MethodCoupling mc = new MethodCoupling(mi.getDestClass(), mi.getDestMethod(), mi.getSrcClass(), mi.getSrcMethod()); if (mMethodCouplings.add(mc)) { //System.out.println( "!!Case2!" + mc.toString() ); mCase2++; } } } } } } private void countCase3() { boolean isFromParents = false; for (MethodInvokation mi : mInvoktionsFromCurrentClass) { if (mi.isNotConstructorInvocation() && !isRedefinedInCurrentClass(mi)) { for (int i = 0; i < mParentsMethods.size(); i++) { for (Method m : mParentsMethods.get(i)) { //TODO: the while loop should be used isFromParents = isInvocationOfTheMethod(m, mi); if (isFromParents) { mi.setDestClass(mParents[i].getClassName()); MethodCoupling mc = new MethodCoupling(mi.getDestClass(), mi.getDestMethod(), mi.getSrcClass(), mi.getSrcMethod()); if (mMethodCouplings.add(mc)) { //System.out.println( "!!Case3!" + mc.toString() ); break; } } } if (isFromParents) { break; } } if (isFromParents) { mCase3++; } } } } /** * Two methods are equal when the have the same name and the same set of arguments. */ private boolean equalMethods(Method m, Method pm) { if (m.getName().equals(pm.getName())) { if (compareTypes(m.getArgumentTypes(), m.getArgumentTypes())) { return true; } } return false; } /** * Investigates method - a member of the currently investigated class. */ private void investigateMethod(final Method m) { MethodGen mg = new MethodGen(m, mClassName, mPoolGen); if (!mg.isAbstract() && !mg.isNative()) { for (InstructionHandle ih = mg.getInstructionList().getStart(); ih != null; ih = ih.getNext()) { Instruction i = ih.getInstruction(); if (!visitInstruction(i)) { i.accept(new org.apache.bcel.generic.EmptyVisitor() { @Override public void visitInvokeInstruction(InvokeInstruction ii) { String methodName = ""; String className = ""; Type[] args = ii.getArgumentTypes(mPoolGen); methodName = ii.getMethodName(mPoolGen); className = ii.getClassName(mPoolGen); if (args.length > 0) { MethodInvokation mi = new MethodInvokation(className, methodName, args, mClassName, m.getName(), m.getArgumentTypes()); mInvoktionsFromCurrentClass.add(mi); } } }); } } } } /** * Investigates method - a member of the currently investigated class. */ private void investigateMethodAndLookForSetters(final Method m) { MethodGen mg = new MethodGen(m, mClassName, mPoolGen); if (!mg.isAbstract() && !mg.isNative()) { for (InstructionHandle ih = mg.getInstructionList().getStart(); ih != null; ih = ih.getNext()) { Instruction i = ih.getInstruction(); if (!visitInstruction(i)) { i.accept(new org.apache.bcel.generic.EmptyVisitor() { @Override public void visitFieldInstruction(FieldInstruction fi) { if (isSetInstruction(fi)) { FieldAccess fa = new FieldAccess(fi.getFieldName(mPoolGen), m, mCurrentClass); mCurrentClassSetters.add(fa); } } private boolean isSetInstruction(FieldInstruction fi) { String instr = fi.toString(mCurrentClass.getConstantPool()); return instr.startsWith("put"); } }); } } } } private boolean isFieldDefinedInCurrentClass(String fieldName) { for (Field f : mCurrentClass.getFields()) { if (f.getName().equals(fieldName)) { return true; } } return false; } private boolean isFromParents(MethodInvokation mi) { for (JavaClass jc : mParents) { if (jc.getClassName().equals(mi.getDestClass())) { return true; } } return false; } /** * It compares the method's names and the lists of method's arguments. */ private boolean isInvocationOfTheMethod(Method m, MethodInvokation mi) { if (m.getName().equals(mi.getDestMethod())) { Type[] args = m.getArgumentTypes(); boolean areEquals = compareTypes(args, mi.getDestMethodArgs()); if (areEquals == true) { return true; } } return false; } private boolean hasBeenDefinedInParentToo(Method m) { String name = m.getName(); if (name.equals("<init>") || name.equals("<clinit>")) { return false; //constructors cannot be redefined } Iterator<Method[]> itr = mParentsMethods.iterator(); while (itr.hasNext()) { Method[] parentMethods = itr.next(); for (Method pm : parentMethods) { if (equalMethods(m, pm)) { return true; } } } return false; } private boolean isRedefinedInCurrentClass(MethodInvokation mi) { for (Method m : mMethods) { if (isInvocationOfTheMethod(m, mi)) { return true; } } return false; } private void saveResults() { int sum = mCase1 + mCase2 + mCase3; mClassMetrics.setCbm(sum); Set<String> coupledParents = new TreeSet<String>(); for (MethodCoupling mc : mMethodCouplings) { if (mc.getClassA().equals(mClassName)) { coupledParents.add(mc.getClassB()); if (mc.getClassB().equals(mClassName)) LoggerHelper.printError("Both of the involved in MethodCoupling classes are the investigated class!", new RuntimeException()); } else { coupledParents.add(mc.getClassA()); if (!mc.getClassB().equals(mClassName)) LoggerHelper.printError("None of the involved in MethodCoupling classes is the investigated class!", new RuntimeException()); } } mClassMetrics.setIc(coupledParents.size()); } /** * Visit a single instruction. */ private boolean visitInstruction(Instruction i) { short opcode = i.getOpcode(); return ((InstructionConstants.INSTRUCTIONS[opcode] != null) /*&& !(i instanceof ConstantPushInstruction) && !(i instanceof ReturnInstruction)*/); } /** * @return the Parent Class Name */ private String getParentClassName() { return mParent.getClassName(); } }
import processing.core.PApplet; import processing.core.PImage; public class MySketch extends PApplet{ int MAX_TAPPERS = 500; int WIDTH = 1200; int HEIGHT = 750; float SCALE_FACTOR = 10f; float DEFAULT_SIZE = 2f; float MIN_SIZE = 0.8f; String BGpath = "img/img4.png"; Tapper[] tappers = new Tapper[MAX_TAPPERS]; LedGrid[] gridArray = new LedGrid[100]; int nextIndex = 0; int frame = 0; int frameDelay = 0; PImage BGimg; public void settings(){ size(WIDTH, HEIGHT); BGimg = loadImage(BGpath); } public void draw(){ image(BGimg, 0, 0); for (int j=0; j<nextIndex; j++) { tappers[j].update(frame); tappers[j].render(); } frame ++; delay(frameDelay); } public void mousePressed(){ tappers[nextIndex] = new Tapper(this, mouseX, mouseY, frame, DEFAULT_SIZE); nextIndex ++; } public void mousePressedPersp(){ float size = MIN_SIZE + (abs((WIDTH/2)-mouseX)/((WIDTH/2)/SCALE_FACTOR)); tappers[nextIndex] = new Tapper(this, mouseX, mouseY, frame, size); nextIndex ++; } public void keyPressed() { boolean allOn = true; if (key == CODED) { if (keyCode == RIGHT) allOn = true; if (keyCode == LEFT) allOn = false; if (keyCode == UP) tappers[nextIndex-1].myGrid.sizeUp(); if (keyCode == DOWN) tappers[nextIndex-1].myGrid.sizeDown(); if (keyCode == SHIFT) frameDelay += 10; if (keyCode == ALT) if (frameDelay != 0) frameDelay -= 10; if (keyCode == RIGHT || keyCode == LEFT) { for (Tapper tapper : tappers) { if (tapper != null) { for (LED led : tapper.myLEDs) { if (led != null) if (allOn) led.setAlpha(255); else led.setAlpha(0); } } } } } } public static void main(String[] args){ String[] processingArgs = {"MySketch"}; MySketch mySketch = new MySketch(); PApplet.runSketch(processingArgs, mySketch); } }
package it.geek.annunci.form; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; public class LoginForm extends ActionForm{ private int id; private String username; private String password; private String nome; private String cognome; private String method; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCognome() { return cognome; } public void setCognome(String cognome) { this.cognome = cognome; } /*public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); if (username==null || "".equals(username)) { errors.add("username", new ActionMessage("errors.login.username.blank")); } if (username!=null && !"".equals(username) && username.length()<3) { errors.add("username", new ActionMessage("errors.login.lunghezza_insufficiente")); } if (username!=null && !"".equals(username) && (username.contains("'")||username.contains("\"")||username.contains("/")||username.contains("\\")||username.contains("?"))){ errors.add("username", new ActionMessage("errors.login.caratteri_non_consentiti")); } if (password==null ||"".equals(password)) { errors.add("password", new ActionMessage("errors.login.password.blank")); } if (password!=null && !"".equals(password) && password.length()<3) { errors.add("password", new ActionMessage("errors.login.lunghezza_insufficiente")); } if (password!=null && !"".equals(password) && (password.contains("'")||password.contains("\"")||password.contains("/")||password.contains("\\")||password.contains("?"))){ errors.add("password", new ActionMessage("errors.login.caratteri_non_consentiti")); } return errors; }*/ }
package game.core.screen.bottomPanel.subPanels; import game.core.HexTileActions; import game.core.screen.Panel; import game.core.screen.bottomPanel.BottomPanel; import render2d.Color; import render2d.elements.Point; public class SkillPanel extends Panel { public final static int LAYER = BottomPanel.LAYER + 1; public final static int BASE_MARGIN = BottomPanel.BASE_MARGIN; public final static Color BASE_COLOR = BottomPanel.BASE_COLOR; private SkillSlot movement; private SkillSlot weapon1; private SkillSlot weapon2; private int slotScale; public SkillPanel(Point basePos, int scale) { super(basePos, scale, scale); this.slotScale = scale; initSkillSlots(); } @Override public void toRender() { updateSkillSlots(); movement.toRender(); weapon1.toRender(); weapon2.toRender(); } private void updateSkillSlots() { movement.setTexName(getSelectedUnitSkillTex(0)); weapon1.setTexName(getSelectedUnitSkillTex(1)); weapon2.setTexName(getSelectedUnitSkillTex(2)); } private String getSelectedUnitSkillTex(int slot) { String texName = ""; if(HexTileActions.getSelectedUnit() != null) texName = HexTileActions.getSelectedUnit() .getSkill(slot) .getTexName(); return texName; } private void initSkillSlots() { this.movement = new SkillSlot( basePos.getNew(), slotScale ); this.weapon1 = new SkillSlot( basePos.getNew(BASE_MARGIN + slotScale, 0), slotScale ); this.weapon2 = new SkillSlot( basePos.getNew(BASE_MARGIN * 2 + slotScale * 2, 0), slotScale ); } }
package banking.model; import java.util.HashSet; import java.util.Set; public class User { @Override public String toString() { return "User [userID=" + userID + ", firstName=" + firstName + ", lastName=" + lastName + ", username=" + username + ", phoneNumber=" + phoneNumber + ", password=" + password + ", accounts=" + accounts + ", cards=" + cards + "]"; } //List of accounts private Integer userID; private String firstName; private String lastName; private String username; private String phoneNumber; private String password; private Set<Account> accounts; private Set<ChargeCard> cards; private static Account accessedAccount; //---CONSTRUCTORS---// //--NEW USER--// /*** * @author Leon Wilson */ public User(Integer userID, String firstName, String lastName, String username, String phoneNumber, String password) { this.userID = userID; this.firstName = firstName; this.lastName = lastName; this.username = username; this.setPhoneNumber(phoneNumber); this.password = password; this.accounts = new HashSet<Account>(); this.accounts.add(new Account()); //default account //no card } /*** * @author Leon Wilson */ public User(Integer userID, String firstName, String lastName, String username, String phoneNumber, String password, Account newAccount) { this.userID = userID; this.firstName = firstName; this.lastName = lastName; this.username = username; this.setPhoneNumber(phoneNumber); this.password = password; this.accounts = new HashSet<Account>(); this.accounts.add(newAccount); this.setCards(new HashSet<ChargeCard>()); //no card } /*** * @author Leon Wilson */ public User(Integer userID, String firstName, String lastName, String username, String phoneNumber, String password, ChargeCard card) { this.userID = userID; this.firstName = firstName; this.lastName = lastName; this.username = username; this.setPhoneNumber(phoneNumber); this.password = password; this.accounts = new HashSet<Account>(); this.accounts.add(new Account()); //default account this.setCards(new HashSet<ChargeCard>()); this.getCards().add(card); } /*** * @author Leon Wilson */ public User(Integer userID, String firstName, String lastName, String username, String phoneNumber, String password, Account newAccount, ChargeCard card) { this.userID = userID; this.firstName = firstName; this.lastName = lastName; this.username = username; this.setPhoneNumber(phoneNumber); this.password = password; this.accounts = new HashSet<Account>(); this.accounts.add(newAccount); this.setCards(new HashSet<ChargeCard>()); this.getCards().add(card); } //--EXISTING USER--// /*** * @author Leon Wilson */ public User(Integer userID, String firstName, String lastName, String username, String phoneNumber, String password, Set<Account> accounts, Set<ChargeCard> cards) { this.userID = userID; this.firstName = firstName; this.lastName = lastName; this.username = username; this.setPhoneNumber(phoneNumber); this.password = password; this.setAccounts(accounts); this.setCards(cards); } //---FUNCTIONS---// //--DISPLAY--// /*** * @author Leon Wilson */ public void displayAccounts() { } /*** * @author Leon Wilson */ public void displayUserSummary() { } public void displayCards() { } //--FUNCTIONALITY--// /*** * @author Leon Wilson */ public void addAccount(String name, AccountTypes type) { } /*** * @author Leon Wilson */ public void addAccount(Account a) { this.accounts.add(a); } /*** * @author Leon Wilson */ public void deleteAccount(Account a1) { } /*** * @author Leon Wilson */ public void transferBetweenAccounts(Account a1, Account a2, Double amount) { } //--GETTERS/SETTERS--// public Integer getUserID() { return userID; } public void setUserID(Integer userID) { this.userID = userID; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Set<Account> getAccounts() { return accounts; } public void setAccounts(Set<Account> accounts) { this.accounts = accounts; } public Set<ChargeCard> getCards() { return cards; } public void setCards(Set<ChargeCard> cards) { this.cards = cards; } public static Account getAccessedAccount() { return accessedAccount; } public static void setAccessedAccount(Account accessedAccount) { User.accessedAccount = accessedAccount; } }
package org.goshop.email.service; import org.goshop.email.i.EMailService; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.goshop.base.service.SpringBaseTest; /** * Created by Administrator on 2016/6/21. */ public class EMailServiceImplTest extends SpringBaseTest { @Autowired EMailService eMailService; @Test public void testSend() throws Exception { eMailService.send("pzh_gugu@126.com","找回密码","你来吧!"); } }
package org.xgame.commons.generator; /** * @Company: 深圳市烈焰时代科技有限公司 * @Product: flame-gxnjy * @File: com.flame.game.core.aacommon.generate.ILongIDReset.java * @Description: 重设接口 * @Create: DerekWu 2017年8月8日 上午11:09:31 * @version: V1.0 */ public interface ILongIDReset { void startReset(); }
package com.yinghai.a24divine_user.bean; /** * @author Created by:fanson * Created Time: 2017/11/19 15:36 * Describe:本地选择星座的Bean */ public class ConstellationBean { private String constellation; public String getConstellation() { return constellation; } public void setConstellation(String constellation) { this.constellation = constellation; } }
package com.tencent.mm.plugin.webview.ui.tools; import android.net.Uri; import com.tencent.mm.plugin.webview.model.ah; import com.tencent.mm.plugin.webview.ui.tools.jsapi.d; import com.tencent.mm.plugin.webview.ui.tools.jsapi.f.a; import com.tencent.mm.plugin.webview.ui.tools.jsapi.i$a; import com.tencent.mm.protocal.GeneralControlWrapper; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.util.HashMap; class WebViewUI$27 implements a { final /* synthetic */ WebViewUI pZJ; WebViewUI$27(WebViewUI webViewUI) { this.pZJ = webViewUI; } public final void bWG() { int I; int i = 2; boolean z = false; try { if (this.pZJ.gcO.aSn()) { if (this.pZJ.bWr() || this.pZJ.bWs()) { I = WebViewUI.I(this.pZJ); if (I > 0 && I <= 4) { i = I; } WebViewUI.d(this.pZJ, i); this.pZJ.M(true, true); if (this.pZJ.mhH != null && this.pZJ.gcP != null && this.pZJ.pNV != null) { String url = this.pZJ.mhH.getUrl(); if (!bi.oW(url) && WebViewUI.J(this.pZJ).add(url)) { GeneralControlWrapper bVS = this.pZJ.gcP.bVS(); boolean z2 = (bVS.qVZ & 512) > 0; x.d("MicroMsg.GeneralControlWrapper", "allowUploadHosts, ret = " + z2); if (z2) { d dVar = this.pZJ.pNV; x.i("MicroMsg.JsApiHandler", "getAllHostsInPage, ready(%s).", new Object[]{Boolean.valueOf(dVar.qhq)}); if (dVar.qhk != null && dVar.qhq) { dVar.qhk.evaluateJavascript("javascript:WeixinJSBridge._handleMessageFromWeixin(" + i$a.a("sys:get_all_hosts", new HashMap(), dVar.qhs, dVar.qht) + ")", null); } } if ((bVS.qVZ & 1024) > 0) { z2 = true; } else { z2 = false; } x.d("MicroMsg.GeneralControlWrapper", "allowUploadHTML, ret = " + z2); if (z2) { this.pZJ.pNV.kl(false); return; } ah m = WebViewUI.m(this.pZJ); if (!bi.oW(url)) { url = Uri.parse(url).getHost(); if (!bi.oW(url)) { z = m.pRV.remove(url); } } if (z) { this.pZJ.pNV.kl(true); return; } return; } return; } return; } if (bi.oW(this.pZJ.cbP) || !com.tencent.mm.plugin.webview.a.pNp.matcher(this.pZJ.cbP).matches()) { I = this.pZJ.gcO.ej(16384, 2); } else { I = this.pZJ.gcO.ej(16388, 2); } i = I; WebViewUI.d(this.pZJ, i); this.pZJ.M(true, true); if (this.pZJ.mhH != null) { } } } catch (Exception e) { x.e("MicroMsg.WebViewUI", "onLoadJsApiFinished, ex = " + e.getMessage()); } I = 2; i = I; WebViewUI.d(this.pZJ, i); this.pZJ.M(true, true); if (this.pZJ.mhH != null) { } } }
package org.company; import org.testng.annotations.Test; public class CompanyInfo { @Test(priority=1) private void companyName() { System.out.println("company name is HCL"); } @Test(priority=0) private void companyId() { System.out.println("company id is 51638"); } @Test(priority=2) private void companyAddress() { System.out.println("company address is sholinganallur"); } /*public static void main(String[] args) { CompanyInfo c=new CompanyInfo(); c.companyName(); c.companyId(); c.companyAddress(); }*/ }
import java.awt.event.KeyEvent; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import javax.swing.JOptionPane; /* * 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. */ /** * * @author Ali */ public class checkData extends javax.swing.JFrame { /** * Creates new form checkData */ public checkData() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel7 = new javax.swing.JLabel(); jTextField6 = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); tf = new javax.swing.JTextField(); jButton2 = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); id = new javax.swing.JTextField(); gender = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); age = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); designation = new javax.swing.JTextField(); name = new javax.swing.JTextField(); sallary = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); jLabel7.setText("ID:"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel6.setForeground(new java.awt.Color(51, 51, 51)); jLabel6.setText("Employee management System"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Data Search", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(204, 204, 204))); // NOI18N jLabel1.setText("Employe ID"); jButton1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton1.setText("Search"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); tf.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { tfKeyTyped(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tf, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(tf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jButton2.setText("Back"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jLabel5.setText("DESIGNATION:"); jLabel4.setText("GENDER:"); jLabel2.setText("ID:"); jLabel8.setText("Name:"); jLabel3.setText("AGE:"); jLabel9.setText("Sallary:"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(40, 40, 40) .addComponent(age, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(54, 54, 54) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(id, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(name, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(40, 40, 40) .addComponent(gender, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(40, 40, 40) .addComponent(designation, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(40, 40, 40) .addComponent(sallary, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(age, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(gender, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(designation, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(sallary, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(68, 68, 68) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(layout.createSequentialGroup() .addGap(153, 153, 153) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(57, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton2) .addContainerGap(20, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void tfKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfKeyTyped // TODO add your handling code here: char c = evt.getKeyChar(); if(!(Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE) || (c==KeyEvent.VK_BACK_SLASH) || (c==KeyEvent.VK_DELETE) )){ getToolkit().beep(); evt.consume(); } }//GEN-LAST:event_tfKeyTyped private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: dispose(); MainWindow mw = new MainWindow(); mw.setVisible(true); }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: try{ int c = Integer.parseInt(tf.getText()); GetStack stk = new GetStack(); if(!stk.getIDStack(c)){ JOptionPane.showMessageDialog(checkData.this, "User Id Does not Exists"); return; } else{ Connection con = CP.createC(); String query ="Select * from employe where id ="+ c; Statement stmt = con.createStatement(); ResultSet set = stmt.executeQuery(query); String av[] = {"id","name","age","gender","designation","sallary"}; String ars[] = new String[3]; int ari[] = new int[3]; set.next(); ars[0] = set.getString("Name"); ars[1] = set.getString("Gender"); ars[2] = set.getString("Designation"); ari[0] =c; ari[1]= set.getInt("Age"); ari[2] = set.getInt("Sallary"); name.setText(ars[0]); gender.setText(ars[1]); designation.setText(ars[2]); id.setText(Integer.toString(ari[0])); age.setText(Integer.toString(ari[1])); sallary.setText(Integer.toString(ari[2])); return; } } catch(Exception e){ } }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(checkData.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(checkData.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(checkData.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(checkData.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new checkData().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField age; private javax.swing.JTextField designation; private javax.swing.JTextField gender; private javax.swing.JTextField id; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField jTextField6; private javax.swing.JTextField name; private javax.swing.JTextField sallary; private javax.swing.JTextField tf; // End of variables declaration//GEN-END:variables }
package com.example.pedro.pethost; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; public class AnfitriaoAdapter extends BaseAdapter { private List<UserAnfitriao> lista; private Context context; public AnfitriaoAdapter(List<UserAnfitriao> anfitriaos , Context context) { Log.i("BD","ChegouNoAdapter"); this.lista = anfitriaos; this.context = context; } @Override public int getCount() { return this.lista.size(); } @Override public Object getItem(int position) { return this.lista.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; UserAnfitriao anfitriao = this.lista.get(position); if (convertView == null) { LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = li.inflate(R.layout.activity_anfitriao_layout, null); }else view = convertView; TextView tv = (TextView) view.findViewById(R.id.tvNomeAnfitriaoLayout); tv.setText(anfitriao.getNome()); return view; } }
package twoLayerNN; import java.util.Arrays; public class NeuronLayer { int num_neurons; int num_inputs; double[][] weights; Neuron[] neurons; public NeuronLayer (int num_neurons, double[] weights_arr, double bias) { this.num_neurons = num_neurons; this.num_inputs = weights_arr.length/this.num_neurons; this.weights = new double[this.num_neurons][]; // converting weights array into a 2d array using indices w^l_jk format for (int i = 0; i < this.weights.length; i++) { this.weights[i] = Arrays.copyOfRange(weights_arr, i*num_inputs, (i+1)*num_inputs); } this.neurons = new Neuron[num_neurons]; for (int i = 0; i < this.num_neurons; i++) { this.neurons[i] = new Neuron(bias); } } public double[] feedforward (double[] inputs) { double[] outputs = new double[num_neurons]; for (int i = 0; i < num_neurons; i++) { outputs[i] = this.neurons[i].calculate_output(inputs, this.weights[i]); } return outputs; } // we take the product of weight matrix and deltas public double[] get_layer_deltas (double[] deltas, double[] outputs) { double[] products = new double[this.num_inputs]; for (int i = 0; i < products.length; i++) { products[i] = 0; for (int j = 0; j < deltas.length; j++) { products[i] += this.weights[j][i] * deltas[j]; } products[i] *= NeuralNetwork.activate_derivative(outputs[i]); } return products; } public double[][] get_gradients_w (double[] activations, double[] deltas) { double[][] gradients = new double[this.num_neurons][this.num_inputs]; for (int j = 0; j < gradients.length; j++) { for (int k = 0; k < gradients[0].length; k++) { gradients[j][k] = activations[k]*deltas[j]; } } return gradients; } public double[] get_gradients_b (double[] deltas) { return deltas; } public void update_network_layer (double[][] gradients_w, double[] gradients_b, double LEARNING_RATE) { for (int i = 0; i < gradients_w.length; i++) for (int j = 0; j < gradients_w[0].length; j++) { weights[i][j] -= LEARNING_RATE * gradients_w[i][j]; } for (int i = 0; i < this.num_neurons; i++) { neurons[i].update_bias(gradients_b[i]); } } public void inspect() { System.out.println("\tLAYER"); for (int i = 0; i < num_neurons; i++) { this.neurons[i].inspect(this.weights[i]); } } }
package com.tt.miniapp.monitor; import android.app.ActivityManager; import android.content.Context; import android.os.Debug; import android.os.Process; import com.tt.miniapp.AppbrandApplicationImpl; import com.tt.miniapphost.AppbrandContext; import com.tt.miniapphost.MiniappHostBase; public class MemoryMonitorTask extends BaseMonitorTask { private static long sMaxMemory; public MemoryMonitorTask() { super(10000L); } public MemoryMonitorTask(long paramLong) { super(paramLong); } public static long getAvailMemory(Context paramContext) { ActivityManager activityManager = (ActivityManager)paramContext.getSystemService("activity"); ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo(); activityManager.getMemoryInfo(memoryInfo); double d = memoryInfo.totalMem; Double.isNaN(d); return (long)(d * 0.12D); } public static long getMaxMemory() { return sMaxMemory; } private void monitorMemoryInfo() { MiniappHostBase miniappHostBase = AppbrandContext.getInst().getCurrentActivity(); if (miniappHostBase != null) { ActivityManager activityManager = (ActivityManager)miniappHostBase.getSystemService("activity"); if (activityManager == null) return; Debug.MemoryInfo[] arrayOfMemoryInfo = activityManager.getProcessMemoryInfo(new int[] { Process.myPid() }); if (arrayOfMemoryInfo != null) { if (arrayOfMemoryInfo.length <= 0) return; Debug.MemoryInfo memoryInfo = arrayOfMemoryInfo[0]; if (sMaxMemory == 0L) sMaxMemory = activityManager.getMemoryClass() * 1024L; MonitorInfoPackTask.addMemoryInfo(AppbrandApplicationImpl.getInst().getForeBackgroundManager().isBackground(), memoryInfo); } } } protected void executeActual() { monitorMemoryInfo(); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\monitor\MemoryMonitorTask.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
/************************************************************************** * <pre> * * Copyright (c) Unterrainer Informatik OG. * This source is subject to the Microsoft Public License. * * See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. * All other rights reserved. * * (In other words you may copy, use, change and redistribute it without * any restrictions except for not suing me because it broke something.) * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR * PURPOSE. * * </pre> ***************************************************************************/ package info.unterrainer.java.tools.csvtools; import java.io.Closeable; import lombok.Getter; /** * The Class CsvBase. * <p> * This is the base-class for both the reader and the writer. It's mainly used to share default-values. */ public abstract class CsvBase implements Closeable { /** * The default value for the column separator. */ protected final static Character DEFAULT_COLUMN_SEPARATOR = ';'; /** * The default value for the row separator. */ protected final static String DEFAULT_ROW_SEPARATOR = "\r\n"; /** * The default value for the field delimiter. */ protected final static String DEFAULT_FIELD_DELIMITER = "\""; /** * This is the lock-object for this class. */ protected Object lockObject = new Object(); /** * The value of the column separator that is used by the program. */ @Getter protected Character columnSeparator = DEFAULT_COLUMN_SEPARATOR; /** * The value of the field delimiter that is used by the program. */ @Getter protected String fieldDelimiter = DEFAULT_FIELD_DELIMITER; /** * The value of the row separator that is used by the program. */ @Getter protected String rowSeparator = DEFAULT_ROW_SEPARATOR; }
package ru.mindbroker.lesson01; import ru.mindbroker.common.Task; import java.util.List; public class LuckyTicketTask implements Task { private Integer n; private Integer qty; public String run(List<String> data) { if (data == null || data.get(0) == null) { return null; } qty = 0; n = Integer.valueOf(data.get(0)); countLuckyTickets(0, 0, 0); return qty.toString(); } private void countLuckyTickets(Integer nr, Integer sum1, Integer sum2) { if (nr == 2 * n) { if (sum1.equals(sum2)) { qty++; } return; } for (int i = 0; i <= 9; i ++) { if (nr < n) { countLuckyTickets(nr + 1, sum1 + i, sum2); } else { countLuckyTickets(nr + 1, sum1, sum2 + i); } } } }
package com.ace.easyteacher.Adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.ace.easyteacher.DataBase.TeacherInfo; import com.ace.easyteacher.R; import java.util.List; public class DeleteTeacherAdapter extends RecyclerView.Adapter<DeleteTeacherAdapter.BaseViewHolder> { private List<TeacherInfo> mList; public OnItemClickListener mItemClickListener; private Context mContext; public DeleteTeacherAdapter(Context context, List<TeacherInfo> list) { this.mList = list; this.mContext = context; } @Override public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new BaseViewHolder(LayoutInflater.from(mContext).inflate(R.layout.common_list_item, null)); } @Override public void onBindViewHolder(BaseViewHolder holder, int position) { holder.bindView(mList.get(position)); } @Override public int getItemCount() { return mList.size(); } public class BaseViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private TextView tv_name; private TextView tv_jobnumber; public BaseViewHolder(View itemView) { super(itemView); tv_jobnumber = (TextView) itemView.findViewById(R.id.item_tv_job_number); tv_name = (TextView) itemView.findViewById(R.id.item_tv_name); itemView.setOnClickListener(this); } public void bindView(TeacherInfo bean) { tv_name.setText(bean.getName()); tv_jobnumber.setText(bean.getJob_number()); } @Override public void onClick(View v) { if (mItemClickListener != null) { mItemClickListener.onItemClick(v, getPosition()); } } } public interface OnItemClickListener { void onItemClick(View view, int position); } public void setOnItemClickListener(final OnItemClickListener mItemClickListener) { this.mItemClickListener = mItemClickListener; } }
package layouts; import controller.eventHandler; import factories.buttonFactory; import factories.imageFactory; import javafx.scene.Scene; public abstract class layout { protected double windowHeight; protected double windowWidth; protected Scene scene; protected buttonFactory factory; protected imageFactory imgFactory; public eventHandler handler = eventHandler.getInstance(); public layout(double height, double width) { windowHeight = height; windowWidth = width; factory = buttonFactory.getButtonFactory(); imgFactory = imageFactory.getImageFactory(); } public Scene getScene() { return scene; } }
package com.vilio.ppms.dao.common; import com.vilio.ppms.pojo.common.RouteBankDayTotal; public interface RouteBankDayTotalMapper { int deleteByPrimaryKey(Long id); int insert(RouteBankDayTotal record); int insertSelective(RouteBankDayTotal record); RouteBankDayTotal selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(RouteBankDayTotal record); int updateByPrimaryKey(RouteBankDayTotal record); }
package hearthstone; import java.util.Scanner; public class HearthstoneBoard { Card deck[]; Card enemyDeck[]; Card hand[] = new Card[10]; Card enemyHand[] = new Card[10]; Card fieldCards[] = new Card[7]; Card enemyFieldCards[] = new Card[7]; int startMana; int currentMana; Hero allyHero; Hero enemyHero; int cardsPlayed; public HearthstoneBoard() { } public void printGame() { String line = "________________________________________________________________________________________"; String line2 = "><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><"; String line3 = "****************************************************************************************"; System.out.println(line3); System.out.print("Enemy Minions||");//15 chars for (int i = 0; i < 7; i++) {//print enemy card names if (this.enemyFieldCards[i].name.equals("")) {//print empty card System.out.print("\t|"); } else if (this.enemyFieldCards[i].name.length() > 6) {//print card name limit to 6 chars System.out.print(" " + this.enemyFieldCards[i].name.substring(0, 6) + " |"); } else {//print card name System.out.print(" " + this.enemyFieldCards[i].name + "\t|"); } } System.out.println(""); System.out.print(" ||");//15 chars for (int i = 0; i < 7; i++) {//print enemy attack, hp if (this.enemyFieldCards[i].name.equals("")) {//print empty card System.out.print("\t|"); } else {//print enemy attack, hp System.out.print(" " + this.enemyFieldCards[i].attack + "ATK " + this.enemyFieldCards[i].hp + "HP\t|"); } } System.out.println(""); System.out.print(" ||");//15 chars for (int i = 0; i < 7; i++) {//print enemy conditions if (this.enemyFieldCards[i].name.equals("")) {//print empty card System.out.print("\t|"); } else {//print enemy conditions String arrConditions[] = this.enemyFieldCards[i].condition.split(","); for (int j = 0; j < arrConditions.length; j++) {//prints out every condition that the minion contains System.out.print(arrConditions[j].charAt(0) + "/"); } System.out.print("\t|"); } } System.out.println(""); System.out.println(""); System.out.println(line2);//divider between enemy and ally minions System.out.println(""); System.out.print("Your Minions ||");//15 chars for (int i = 0; i < 7; i++) {//print ally card names if (this.fieldCards[i].name.equals("")) {//print empty card System.out.print("\t|"); } else if (this.fieldCards[i].name.length() > 6) {//print card name limit to 6 chars System.out.print(" " + this.fieldCards[i].name.substring(0, 6) + " |"); } else {//print card name System.out.print(" " + this.fieldCards[i].name + "\t|"); } } System.out.println(""); System.out.print(" ||");//15 chars for (int i = 0; i < 7; i++) {//print ally attack, hp if (this.fieldCards[i].name.equals("")) {//print empty card System.out.print("\t|"); } else {//print enemy attack, hp System.out.print(" " + this.fieldCards[i].attack + "ATK " + this.fieldCards[i].hp + "HP\t|"); } } System.out.println(""); System.out.print(" ||");//15 chars for (int i = 0; i < 7; i++) {//print ally conditions if (this.fieldCards[i].name.equals("")) {//print empty card System.out.print("\t|"); } else {//print enemy conditions String arrConditions[] = this.fieldCards[i].condition.split(","); for (int j = 0; j < arrConditions.length; j++) {//prints out every condition that the minion contains System.out.print(arrConditions[j].charAt(0) + "/"); } System.out.print("\t|"); } } System.out.println("\n" + line3); System.out.print("Your Hand ||");//15 chars for (int i = 0; i < 10; i++) {//print ally card names if (this.hand[i].name.equals("")) {//print empty card System.out.print("\t|"); } else if (this.hand[i].name.length() > 6) {//print card name limit to 6 chars System.out.print(" " + this.hand[i].name.substring(0, 6) + " |"); } else {//print card name System.out.print(" " + this.hand[i].name + "\t|"); } } System.out.println(""); System.out.print(" ||");//15 chars for (int i = 0; i < 10; i++) {//print cost of the card if (this.hand[i].name.equals("")) {//print empty card System.out.print("\t|"); } else {//print cost System.out.print(" " + this.hand[i].cost + " MANA\t|"); } } System.out.println(""); System.out.print(" ||");//15 chars for (int i = 0; i < 10; i++) {//print card attack, hp if (this.hand[i].name.equals("") || this.hand[i].condition.contains("Spell")) {//print empty card System.out.print("\t|"); } else {//print card attack, hp System.out.print(" " + this.hand[i].attack + "ATK " + this.hand[i].hp + "HP\t|"); } } System.out.println(""); System.out.print(" ||");//15 chars for (int i = 0; i < 10; i++) {//print card conditions if (this.hand[i].name.equals("") || this.hand[i].condition.contains("Spell")) {//print empty card System.out.print("\t|"); } else {//print enemy conditions String arrConditions[] = this.hand[i].condition.split(","); for (int j = 0; j < arrConditions.length; j++) {//prints out every condition that the minion contains System.out.print(arrConditions[j].charAt(0) + "/"); } System.out.print("\t|"); } } System.out.println(line); System.out.println("Choose your action: \"A\" - Attack | \"P\" - Play Card | \"R\" - Restart | \"E\" - Exit"); System.out.println(line); } public void attackAction() { Scanner scInt = new Scanner(System.in); for (int i = 0; i < 7; i++) {//prints each avaliable minion that can attack if (!this.fieldCards[i].name.equals("")) { if (!this.fieldCards[i].isFirstTurn()) { System.out.println("[" + i + "] - " + this.fieldCards[i].name); } } } System.out.println("Choose a minion to attack with"); int choice1 = scInt.nextInt();//selects the minion to attack with System.out.println(""); for (int i = 0; i < 7; i++) {//prints each avaliable enemy minion if (!this.fieldCards[i].name.equals("")) { System.out.println("[" + i + "] - " + this.enemyFieldCards[i].name); } } System.out.println("Choose the minion to attack"); int choice2 = scInt.nextInt();//selects the minion to be attacked System.out.println(""); this.fieldCards[choice1].attack(this.enemyFieldCards[choice2]);//issue for dylan to deal with } public void cardAction() { Scanner scInt = new Scanner(System.in); for (int i = 0; i < 10; i++) {//prints each avaliable card that can be played if (!this.hand[i].name.equals("")) { if (this.hand[i].cost <= this.currentMana) { System.out.println("[" + i + "] - " + this.hand[i].name + "(" + this.hand[i].cost + " mana)"); } } } System.out.println("Choose the card to be played"); int choice1 = scInt.nextInt();//selects the card System.out.println(""); if (!this.hand[choice1].condition.contains("Spell")) {//if the card is a minion card boolean check = false; for (int i = 0; i < 7; i++) {//checks if there is room on the field to play a minion if (this.fieldCards[i].name.equals("")) { check = true; } } if (check) { System.out.println("Choose where to play the minion (1-7)"); int choice2 = scInt.nextInt();//selects the position to place the minion System.out.println(""); //////////////////place down minion method } } else {//if th card is a spell card //////////////////play spell card method } } }
package com.espendwise.manta.web.forms; import java.util.List; import com.espendwise.manta.model.view.TradingPartnerListView; import com.espendwise.manta.spi.Initializable; import com.espendwise.manta.util.Pair; import com.espendwise.manta.util.validation.Validation; import com.espendwise.manta.web.validator.DistributorFormValidator; @Validation(DistributorFormValidator.class) public class DistributorForm extends WebForm implements Initializable { //base attributes private Long distributorId; private String distributorName; private String distributorStatus; private String distributorLocale; //properties private String distributorDisplayName; private String distributorType; private String distributorCallCenterHours; private String distributorCompanyCode; private String distributorCustomerReferenceCode; //contact private ContactInputForm contact; //associated trading partners private List<TradingPartnerListView> tradingPartners; //reference data private List<Pair<String, String>> localeChoices; private boolean initialize; public DistributorForm() { } public Long getDistributorId() { return distributorId; } public void setDistributorId(Long distributorId) { this.distributorId = distributorId; } public String getDistributorName() { return distributorName; } public void setDistributorName(String distributorName) { this.distributorName = distributorName; } public String getDistributorStatus() { return distributorStatus; } public void setDistributorStatus(String distributorStatus) { this.distributorStatus = distributorStatus; } public String getDistributorLocale() { return distributorLocale; } public void setDistributorLocale(String distributorLocale) { this.distributorLocale = distributorLocale; } public String getDistributorDisplayName() { return distributorDisplayName; } public void setDistributorDisplayName(String distributorDisplayName) { this.distributorDisplayName = distributorDisplayName; } public String getDistributorType() { return distributorType; } public void setDistributorType(String distributorType) { this.distributorType = distributorType; } public String getDistributorCallCenterHours() { return distributorCallCenterHours; } public void setDistributorCallCenterHours(String distributorCallCenterHours) { this.distributorCallCenterHours = distributorCallCenterHours; } public String getDistributorCompanyCode() { return distributorCompanyCode; } public void setDistributorCompanyCode(String distributorCompanyCode) { this.distributorCompanyCode = distributorCompanyCode; } public String getDistributorCustomerReferenceCode() { return distributorCustomerReferenceCode; } public void setDistributorCustomerReferenceCode( String distributorCustomerReferenceCode) { this.distributorCustomerReferenceCode = distributorCustomerReferenceCode; } public ContactInputForm getContact() { return contact; } public void setContact(ContactInputForm contact) { this.contact = contact; } public List<TradingPartnerListView> getTradingPartners() { return tradingPartners; } public void setTradingPartners(List<TradingPartnerListView> tradingPartners) { this.tradingPartners = tradingPartners; } public List<Pair<String, String>> getLocaleChoices() { return localeChoices; } public void setLocaleChoices(List<Pair<String, String>> localeChoices) { this.localeChoices = localeChoices; } @Override public void initialize() { initialize = true; } @Override public boolean isInitialized() { return initialize; } public boolean getIsNew() { return isNew(); } public boolean isNew() { return isInitialized() && (distributorId == null || distributorId == 0); } @Override public String toString() { return "DistributorForm{" + "initialize=" + initialize + ", distributorId=" + distributorId + ", distributorName='" + distributorName + '\'' + ", distributorStatus='" + distributorStatus + '\'' + ", distributorDisplayName='" + distributorDisplayName + '\'' + ", distributorType='" + distributorType + '\'' + ", distributorCallCenterHours='" + distributorCallCenterHours + '\'' + ", distributorCompanyCode='" + distributorCompanyCode + '\'' + ", distributorCustomerReferenceCode='" + distributorCustomerReferenceCode + '\'' + ", contact=" + contact + '}'; } }
/** * */ package com.cnk.travelogix.common.facades.product.impl; import java.util.ArrayList; import java.util.List; import org.fest.util.Collections; import com.cnk.travelogix.common.facades.product.CnkProductSearchFacade; import com.cnk.travelogix.common.facades.product.data.BasePageableSearchData; import com.cnk.travelogix.common.facades.product.data.BaseProductData; import com.cnk.travelogix.common.facades.product.data.CnkProductSearchPageData; import com.cnk.travelogix.common.facades.product.data.CnkProductSortConditionData; import com.cnk.travelogix.common.facades.product.data.CnkSortedDataList; import com.cnk.travelogix.common.facades.product.sort.CnkProductSortHelper; import com.cnk.travelogix.common.facades.product.sort.impl.SortedToModelEntry; import com.cnk.travelogix.common.facades.product.sort.impl.SortedToModelMapper; /** * @author i313879 * */ public abstract class SortedCnkProductSearchFacade<RESULT extends BaseProductData> implements CnkProductSearchFacade { //The class to be decorated private CnkProductSearchFacade<RESULT> cnkProductSearchFacade; private SortedToModelMapper sortedToModelMapper; private CnkProductSortHelper cnkProductSortHelper; protected List<CnkProductSortConditionData> buildSortedSkeleton() { final List<SortedToModelEntry> sortedEntries = sortedToModelMapper.getSortedToModelEntries(); final List<CnkProductSortConditionData> sortedConditionList = new ArrayList(); for (final SortedToModelEntry sortedEntry : sortedEntries) { sortedConditionList.add(createNormalSort(sortedEntry)); } return sortedConditionList; } private CnkProductSortConditionData createNormalSort(final SortedToModelEntry sortedEntry) { final CnkProductSortConditionData facetData = new CnkProductSortConditionData(); facetData.setCode(sortedEntry.getCode()); facetData.setName(sortedEntry.getName()); facetData.setDesc(sortedEntry.isDesc()); if (sortedEntry.getCode().equalsIgnoreCase("Price")) { facetData.setSelected(true); } //facetData.setType(FacetType.);; return facetData; } /* * (non-Javadoc) * * @see * com.cnk.travelogix.common.facades.product.CnkProductSearchFacade#searchProduct(com.cnk.travelogix.common.facades * .product.data.BasePageableSearchData) */ @Override public CnkProductSearchPageData searchProduct(final BasePageableSearchData searchParameters) { //TODO: facet process final CnkProductSearchPageData result = cnkProductSearchFacade.searchProduct(searchParameters); final List<CnkSortedDataList> sortConditionList = getSortedDataList(searchParameters); sort(result, sortConditionList); result.setSortConditionList(sortConditionList); return result; } protected List<CnkSortedDataList> getSortedDataList(final BasePageableSearchData searchParameters) { List<CnkSortedDataList> sortedList = searchParameters.getSortConditionList(); if (Collections.isEmpty(sortedList)) { sortedList = new ArrayList(); final CnkSortedDataList theSortedConditions = new CnkSortedDataList(); final List<CnkProductSortConditionData> conditions = buildSortedSkeleton(); theSortedConditions.setConditions(conditions); sortedList.add(theSortedConditions); } return sortedList; } protected abstract void sort(final CnkProductSearchPageData result, final List<CnkSortedDataList> sortedList); /* * (non-Javadoc) * * @see * com.cnk.travelogix.common.facades.product.CnkProductSearchFacade#searchProductDetail(com.cnk.travelogix.common * .facades.product.data.BasePageableSearchData) */ @Override public BaseProductData searchProductDetail(final BasePageableSearchData searchParameters) { // YTODO Auto-generated method stub return cnkProductSearchFacade.searchProductDetail(searchParameters); } /* * (non-Javadoc) * * @see com.cnk.travelogix.common.facades.product.CnkProductSearchFacade#searchProductDetail(java.lang.String) */ @Override public BaseProductData searchProductDetail(final String productId) { // YTODO Auto-generated method stub return cnkProductSearchFacade.searchProductDetail(productId); } /** * @return the cnkProductSearchFacade */ public CnkProductSearchFacade<RESULT> getCnkProductSearchFacade() { return cnkProductSearchFacade; } /** * @param cnkProductSearchFacade * the cnkProductSearchFacade to set */ public void setCnkProductSearchFacade(final CnkProductSearchFacade<RESULT> cnkProductSearchFacade) { this.cnkProductSearchFacade = cnkProductSearchFacade; } /** * @return the cnkProductSortHelper */ public CnkProductSortHelper getCnkProductSortHelper() { return cnkProductSortHelper; } /** * @param cnkProductSortHelper * the cnkProductSortHelper to set */ public void setCnkProductSortHelper(final CnkProductSortHelper cnkProductSortHelper) { this.cnkProductSortHelper = cnkProductSortHelper; } /** * @return the sortedToModelMapper */ public SortedToModelMapper getSortedToModelMapper() { return sortedToModelMapper; } /** * @param sortedToModelMapper * the sortedToModelMapper to set */ public void setSortedToModelMapper(final SortedToModelMapper sortedToModelMapper) { this.sortedToModelMapper = sortedToModelMapper; } }
package com.gorniak.spring.spring_boot_2h.dao; import com.gorniak.spring.spring_boot_2h.model.Person; import java.util.List; import java.util.Optional; import java.util.UUID; public interface PersonDao { int insertPerson(UUID id, Person person); default int insertPerson(Person person){ UUID id = UUID.randomUUID(); return insertPerson(id,person); } List<Person> selectAllPeople(); Optional<Person> sellectedPersonById(UUID id); int deletePerson(UUID id); int updatePersonById(UUID id, Person person); }
package com.piistech.gratecrm.Utils.Service; import android.app.IntentService; import android.content.Intent; import android.content.Context; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.RetryPolicy; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.piistech.gratecrm.Utils.LocalDatabase; import org.json.JSONObject; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import static com.piistech.gratecrm.Utils.Constant.API_NAME_TOKEN; import static com.piistech.gratecrm.Utils.Constant.API_STATUS; import static com.piistech.gratecrm.Utils.Constant.API_TOKEN; import static com.piistech.gratecrm.Utils.Constant.API_URL; import static com.piistech.gratecrm.Utils.Constant.BROADCAST_ID_FOR_LOGIN; import static com.piistech.gratecrm.Utils.Constant.EXPIRE_TIME; import static com.piistech.gratecrm.Utils.Constant.IS_AUTHENTICATED_USER; import static com.piistech.gratecrm.Utils.Constant.SOCKET_TIMEOUT; import static com.piistech.gratecrm.Utils.Constant.valueOf; import static com.piistech.gratecrm.Utils.Constant.valueOfInt; import static com.piistech.gratecrm.Utils.Constant.valueOfString; public class LoginService extends IntentService { private Context context; public LoginService() { super("LoginService"); } @Override protected void onHandleIntent(Intent intent) { if (intent != null) { context = this; requestNetwork(intent.getStringExtra("username"), intent.getStringExtra("password")); } } private void requestNetwork(String user_name, String password) { RequestQueue mRequestQueue = Volley.newRequestQueue(this); mRequestQueue.getCache().clear(); Intent resultIntent = new Intent(BROADCAST_ID_FOR_LOGIN); StringRequest postRequest = new StringRequest(Request.Method.POST, API_URL + API_NAME_TOKEN, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject json = new JSONObject(response); if (!json.has("access_token")) resultIntent.putExtra(API_STATUS,false); else { resultIntent.putExtra(API_STATUS,true); LocalDatabase.setLongValue(context, EXPIRE_TIME, (Calendar.getInstance().getTimeInMillis()/1000)+valueOfInt(json, "expires_in")); LocalDatabase.setStringValue(context, API_TOKEN, valueOfString(json,"token_type") + " " + valueOfString(json,"access_token")); } } catch (Exception e) { resultIntent.putExtra(API_STATUS,false); } LocalBroadcastManager.getInstance(LoginService.this).sendBroadcast(resultIntent); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { resultIntent.putExtra(API_STATUS,false); LocalBroadcastManager.getInstance(LoginService.this).sendBroadcast(resultIntent); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("username", user_name); params.put("password", password); params.put("grant_type", "password"); return params; } }; RetryPolicy policy = new DefaultRetryPolicy(SOCKET_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); postRequest.setRetryPolicy(policy); mRequestQueue.add(postRequest); } }
package JsonParser; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import model.Itune; /** * Created by anh khoa on 11/6/2017. */ public class ItuneParser { public static Itune getItune(String url,int i) throws JSONException{ Itune itune=new Itune(); JSONObject ItuneObject=new JSONObject(url); JSONArray resultJsonArray=ItuneObject.getJSONArray("results"); JSONObject artistObject=resultJsonArray.getJSONObject(i); itune.setArtistName(getString("artistName",artistObject)); itune.setTrackName(getString("trackName",artistObject)); itune.setArtworkUrl100(getString("artworkUrl100",artistObject)); return itune; } public static Itune getSearchItune(String url,int j,String TrackName) throws JSONException{ Itune itune=new Itune(); JSONObject ItuneObject=new JSONObject(url); JSONArray resultJsonArray=ItuneObject.getJSONArray("results"); for(int i=0;i<resultJsonArray.length();i++){ JSONObject artistObject= resultJsonArray.getJSONObject(j); if(TrackName.equalsIgnoreCase(artistObject.getString("trackName"))){ itune.setArtistName(getString("artistName",artistObject)); itune.setTrackName(getString("trackName",artistObject)); itune.setArtworkUrl100(getString("artworkUrl100",artistObject)); return itune; } // if(TrackName.equalsIgnoreCase(getString("trackName",artistObject))){ // } } return itune; } public JSONObject SearchObject(String newtext) throws JSONException { String trackname; JSONObject ItuneObject = null; JSONArray resultJsonArray=new JSONArray("results"); for(int i=0;i<resultJsonArray.length();i++){ JSONObject currentob=resultJsonArray.getJSONObject(i); trackname=currentob.getString("trackName"); if(trackname.equalsIgnoreCase(newtext)){ ItuneObject=currentob; } } return ItuneObject; } public static JSONObject jsonObject(String tagName,JSONObject jsonObject)throws JSONException{ return jsonObject.getJSONObject(tagName); } private static String getString(String tagName, JSONObject jsonObject) throws JSONException{ return jsonObject.getString(tagName); } }
package com.mideas.rpg.v2.game.classes; import com.mideas.rpg.v2.game.Joueur; import com.mideas.rpg.v2.game.item.stuff.Stuff; import com.mideas.rpg.v2.game.shortcut.SpellShortcut; import com.mideas.rpg.v2.game.spell.Spell; import com.mideas.rpg.v2.game.spell.SpellManager; import com.mideas.rpg.v2.game.spell.list.Ambush; import com.mideas.rpg.v2.game.spell.list.Eviscerate; import com.mideas.rpg.v2.game.spell.list.SinisterStrike; public class Rogue extends Joueur { public static final int MAX_HEALTH = 6000; public static final int MAX_MANA = 4000; public Rogue() { super(6000, 700, 120, 120, 120, 20, 4000, new SpellShortcut[49], new Spell[49], new Stuff[21], "Rogue", 9, 6000, 4000, 0, 1500, 1050, 0); //setSpells(0, new Ambush()); //setSpells(1, new Eviscerate()); //setSpells(2, new SinisterStrike()); setSpells(0, SpellManager.getShortcutSpell(701)); setSpells(1, SpellManager.getShortcutSpell(702)); setSpells(2, SpellManager.getShortcutSpell(703)); setSpellUnlocked(0, new Ambush()); setSpellUnlocked(1, new Eviscerate()); setSpellUnlocked(2, new SinisterStrike()); } }
/* package com.bingo.code.example.filecode; */ /** * Created by ZhangGe on 2017/10/26. *//* public class ChangeCode { private String source; private String destination; public ChangeCode(String source, String destination) { this.source = source; this.destination = destination; } public byte[] changeCode(byte[] bytes) { } } */
package demoGui; import javax.swing.JList; import javax.swing.JTree; import javax.swing.SwingWorker; import javax.swing.tree.DefaultMutableTreeNode; /***************************************************************************************************************************************** * This class represents a parallel thread to run alongside the main MultipathUI GUI, to perform a long-running task in the background * to eliminate noticeable lag and freezing. * * If the user has selected a GRI in the GUI, the GRI is queries and results are displayed in the console. However, it's possible that * those query results are not up to date. For example, when the user cancels a request, the output might have status "INCANCEL". * This class allows for repeated querying to give the user the most up-to-date information about the GRI every 7 seconds. * * @author Jeremy /*****************************************************************************************************************************************/ public class DemoRefreshThread extends SwingWorker<Void, Integer> { DemoUI callingMPGui; // The actual GUI object /** * Constructor * * @param theGui, The actual GUI object **/ public DemoRefreshThread(DemoUI theGui) { callingMPGui = theGui; } /** * Thread's runner method. When the calling object invokes execute(), this is the method that runs. **/ protected Void doInBackground() { boolean refreshMultipathQuery = false; // Is the refreshed GRI Multipath or Unicast? JTree griTree = callingMPGui.griTree; DemoQueryThread refreshingQuery; // Querying thread to run in parallel // Refresh query results every 7 seconds // while(true) { Object selectedGri = griTree.getLastSelectedPathComponent(); if(selectedGri == null){ continue; } // Don't perform query unless it is necessary // if(callingMPGui.outputConsole.getText().equals("Welcome to the Multipath Client User Interface!")) continue; if(callingMPGui.outputConsole.getText().equals("Creating reservation...")) continue; if(callingMPGui.outputConsole.getText().equals("Querying reservation...")) continue; if(callingMPGui.outputConsole.getText().equals("Cancelling reservation...")) continue; if(callingMPGui.outputConsole.getText().equals("")) continue; // Prepare to refresh MP-GRI query results // if(selectedGri != null) { System.out.println("HERE IN REFRESH!"); selectedGri = selectedGri.toString(); refreshMultipathQuery = true; } // Prepare to refresh subrequest/Unicast GRI query results // if(selectedGri != null && !selectedGri.toString().contains("MP")) { System.out.println("HERE IN REFRESH!"); selectedGri = selectedGri.toString(); refreshMultipathQuery = false; } if(refreshMultipathQuery) refreshingQuery = new DemoQueryThread(selectedGri.toString(), callingMPGui); // Refresh group else refreshingQuery = new DemoQueryThread(selectedGri.toString(), callingMPGui); // Refresh subrequest // Perform the actual refreshing query // refreshingQuery.execute(); callingMPGui.handleGriTree(); callingMPGui.selectARequest(selectedGri.toString()); System.out.println("REFRESHING ..."); // Wait 7 seconds before refreshing -- Arbitrarily chosen time-interval// try { Thread.sleep(7000); } catch(Exception e){} } } }
package com.tencent.mm.ui.chatting; import android.view.View; import com.tencent.mm.ui.base.MMPullDownView.c; class y$3 implements c { final /* synthetic */ y tMm; y$3(y yVar) { this.tMm = yVar; } public final boolean aCi() { View childAt = y.a(this.tMm).getChildAt(y.a(this.tMm).getChildCount() - 1); if (childAt == null) { return true; } if (childAt.getBottom() > y.a(this.tMm).getHeight() || y.a(this.tMm).getLastVisiblePosition() != y.a(this.tMm).getAdapter().getCount() - 1) { return false; } return true; } }
package nodes.base; import flow.Wire; import flow.Bit; import exceptions.LogicException; import java.util.List; import java.util.ArrayList; public abstract class AbstractGate extends AbstractNode implements Gate{ private List<Wire> inputs; private List<Wire> outputs; public AbstractGate(int inputCount, int outputCount) { if (inputCount <= 0 || outputCount <= 0) { throw new LogicException(); } else { inputs = new ArrayList<>(inputCount); outputs = new ArrayList<>(outputCount); for (int i = 0; i < inputCount; ++i) { inputs.add(null); } for (int i = 0; i < outputCount; ++i) { outputs.add(new Wire()); } } } @Override public void setInput(int index, Wire wire) { if (index >= inputs.size() || index < 0) { throw new LogicException(); } else { inputs.set(index, wire); } } @Override public Wire getOutput(int index) { if (index >= outputs.size() || index < 0) { throw new LogicException(); } return outputs.get(index); } @Override public boolean isOperable() { for (int i = 0; i < inputs.size(); ++i) { if (inputs.get(i) == null) { return false; } } return true; } protected abstract Bit calculateResult(Bit[] bits); @Override public void update() { if (this.isOperable() != false) { Bit[] bits = new Bit[inputs.size()]; int i = 0; for (Wire wire: inputs) { Bit bit = wire.getValue(); bits[i] = bit; i += 1; } Bit bit = calculateResult(bits); for (Wire wire: outputs) { wire.setValue(bit); } } } }
package pl.edu.amu.datasupplier.exception; import lombok.Getter; import java.util.HashSet; @Getter public class TestDataRepleteException extends RuntimeException { private final HashSet<String> testDataErrors; public TestDataRepleteException(HashSet<String> testDataErrors) { this.testDataErrors = testDataErrors; } public TestDataRepleteException(String s, HashSet<String> testDataErrors) { super(s); this.testDataErrors = testDataErrors; } public TestDataRepleteException(String s, Throwable throwable, HashSet<String> testDataErrors) { super(s, throwable); this.testDataErrors = testDataErrors; } }
package com.sage.rpg; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class Saving { public static String SAVE_0 = System.getProperty("user.home") + "\\save0.properties"; public static String SAVE_1 = System.getProperty("user.home") + "\\save1.properties"; public static String SAVE_2 = System.getProperty("user.home") + "\\save2.properties"; public static String currentSave; public static void saveKey(String saveFile, String key, String value) { Properties props = new Properties(); try { props.load(new FileInputStream(saveFile)); props.setProperty(key, value); File file = new File(saveFile); FileOutputStream output = new FileOutputStream(file); props.store(output, null); output.close(); } catch (IOException e) { e.printStackTrace(); } } public static String loadKey(String saveFile, String key) { Properties props = new Properties(); try { FileInputStream saveFileLocation = new FileInputStream(saveFile); props.load(saveFileLocation); } catch (IOException e) { e.printStackTrace(); } return props.getProperty(key); } public static boolean available(String saveFile) { Properties props = new Properties(); try { File file = new File(saveFile); if (!file.isFile()) { file.createNewFile(); } FileInputStream saveFileLocation = new FileInputStream(saveFile); props.load(saveFileLocation); } catch (IOException e) { e.printStackTrace(); } if (props.size() > 0) return false; else return true; } public static void deleteSave(String saveFile) { Properties props = new Properties(); try { FileInputStream saveFileLocation = new FileInputStream(saveFile); props.load(saveFileLocation); props.clear(); File file = new File(saveFile); FileOutputStream output = new FileOutputStream(file); props.store(output, null); output.close(); } catch (IOException e) { e.printStackTrace(); } } }
package com.sunyd.common.response; import lombok.Getter; import java.io.Serializable; /** * 统一 Response 设计指南 * NOTE: https://mawen.work/java/2020/07/03/unify-response/ */ @Getter public final class BaseResponse<T> implements Serializable { private static final long serialVersionUID = 3886133510113334083L; private ResponseStatus code; private String message; private T data; // 无参构造方法中将响应码置为DefaultStatus中的SUCCESS public BaseResponse() { this.setCode(ResponseStatus.SUCCESS); this.message = ResponseStatus.SUCCESS.message(); } public BaseResponse(T data) { this(); this.data = data; } public BaseResponse<T> setCode(ResponseStatus code) { this.code = code; this.message = code.message(); return this; } public BaseResponse<T> setMessage(String message) { this.message = message; return this; } public BaseResponse<T> setData(T data) { this.data = data; return this; } public static <T> BaseResponse<T> with(ResponseStatus code, String message) { BaseResponse<T> response = new BaseResponse<>(); response.code = code; response.message = message != null && !message.isEmpty() ? message : code.message(); return response; } public static <T> BaseResponse<T> with(ResponseStatus code, String message, T data) { BaseResponse<T> response = new BaseResponse<>(); response.code = code; response.message = message; response.data = data; return response; } @Override public String toString() { return "BaseResponse{" + "code=" + code.code() + ", message='" + message + '\'' + ", data=" + data + '}'; } }
package com.smxknife.java2.classloader.hotswap; /** * @author smxknife * 2019/10/31 */ public class _Doc { /** 使用ClassLoader实现热部署 * 原理:比较class文件修改时间,如果被修改过,就重新加载 */ }
package org.sankozi.rogueland.generator; import com.google.common.base.Function; import org.sankozi.rogueland.model.Item; import java.util.Collections; /** * Generates loot * @author sankozi */ public interface ItemGenerator { ItemGenerator NULL = new ItemGenerator() { @Override public Iterable<Item> generate(float value) { return Collections.emptyList(); } }; // ItemGenerator NULL = (float value) -> Collections.emptyList(); /** * Creates new batch of items * @param value value of items to be created * @return new batch of items (ItemGenerator cannot return Item that already exists) */ public Iterable<Item> generate(float value); }
/** * ************************************************************************ * Copyright (C) 2010 Atlas of Living Australia All Rights Reserved. * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * ************************************************************************* */ package au.org.ala.spatial.analysis.service; import au.org.ala.spatial.util.AlaspatialProperties; import au.org.ala.spatial.util.Layers; import java.util.List; /** * Settings for the ALOC process. Sets up the basic/default settings allow for * more settings to be added as needed * * @author ajayr */ public class AlocSettings { private String alocPath; private int numberOfGroups; private String envVarToggler; private String envPath; private String envPrefix; private String envSuffix; private List envList; private String outputPath; private String defaultCmdVars; public AlocSettings() { alocPath = AlaspatialProperties.getAnalysisAlocCmd(); envVarToggler = ""; envPrefix = ""; envSuffix = ""; defaultCmdVars = ""; } public String getDefaultCmdVars() { return defaultCmdVars; } public void setDefaultCmdVars(String defaultCmdVars) { this.defaultCmdVars = defaultCmdVars; } public String getEnvPath() { return envPath; } public void setEnvPath(String envPath) { this.envPath = envPath; } public String getEnvPrefix() { return envPrefix; } public void setEnvPrefix(String envPrefix) { this.envPrefix = envPrefix; } public String getEnvSuffix() { return envSuffix; } public void setEnvSuffix(String envSuffix) { this.envSuffix = envSuffix; } public String getOutputPath() { return outputPath; } public void setOutputPath(String outputPath) { this.outputPath = outputPath; } public int getNumberOfGroups() { return numberOfGroups; } public void setNumberOfGroups(int numberOfGroups) { this.numberOfGroups = numberOfGroups; } public String getEnvVarToggler() { return envVarToggler; } public void setEnvVarToggler(String envVarToggler) { this.envVarToggler = envVarToggler; } public String getAlocPath() { return alocPath; } public void setAlocPath(String alocPath) { this.alocPath = alocPath; } public List<String> getEnvList() { return envList; } public void setEnvList(List<String> envList) { for (int i = 0; i < envList.size(); i++) { envList.set(i, Layers.getFieldId(envList.get(i))); } this.envList = envList; } @Override public String toString() { String cmd; cmd = ""; // add the maxent path cmd += alocPath; // add the env.vars path cmd += " " + getEnvPath(); // set group count cmd += " " + numberOfGroups; // set thread count cmd += " " + AlaspatialProperties.getAnalysisThreadCount(); // finally add the output path cmd += " " + outputPath; return cmd; } }
package gov.samhsa.c2s.pcm.config; import lombok.Data; import org.hibernate.validator.constraints.NotBlank; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import javax.validation.constraints.NotNull; @Configuration @ConfigurationProperties(prefix = "c2s.pcm.fhir") @Data @Validated public class FhirProperties { @NotNull @Valid private Ssn ssn; @NotNull @Valid private Npi npi; @NotNull @Valid private Pou pou; @NotNull @Valid private Mrn mrn; @NotNull private boolean patientReference; @Data public static class Identifier { @NotBlank private String system; @NotBlank private String oid; @NotBlank private String label; } @Data public static class Mrn extends Identifier { } @Data public static class Ssn extends Identifier { } @Data public static class Npi extends Identifier { } @Data public static class Pou extends Identifier { } }
package model.dao; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import model.vo.movie.CountryVO; import model.vo.movie.GenreVO; import model.vo.movie.MovieGradeInfo; import model.vo.movie.MovieVO; import model.vo.movie.StaticsVO; import model.vo.reservation.ScreeningMovieVO; import model.vo.theater.LocalInfoVO; import model.vo.theater.PlayRoomTypeVO; import model.vo.theater.PlayRoomVO; import model.vo.theater.TheaterVO; import com.ibatis.sqlmap.client.SqlMapClient; public class AdminDao { public AdminDao() { super(); // TODO Auto-generated constructor stub } private SqlMapClient sqlMapClient; public void setSqlMapClient(SqlMapClient sqlMapClient) { this.sqlMapClient = sqlMapClient; } public ArrayList<GenreVO> getGenreInfo() throws SQLException { return (ArrayList<GenreVO>) sqlMapClient.queryForList("admin.getGnereInfo"); } public ArrayList<CountryVO> getCountryInfo() throws SQLException { return (ArrayList<CountryVO>)sqlMapClient.queryForList("admin.getCountryInfo"); } public ArrayList<LocalInfoVO> getLocalInfo() throws SQLException { return (ArrayList<LocalInfoVO>)sqlMapClient.queryForList("admin.getLocalInfo"); } public ArrayList<MovieGradeInfo> getGradeInfo() throws SQLException { return (ArrayList<MovieGradeInfo>)sqlMapClient.queryForList("admin.getGradeInfo"); } public int registerMovie(MovieVO movieVO) throws SQLException { return (Integer)sqlMapClient.insert("admin.registerMovie",movieVO); } public ArrayList<TheaterVO> getTheaterInfo() throws SQLException { return (ArrayList<TheaterVO>) sqlMapClient.queryForList("admin.getTheaterInfo"); } public ArrayList<MovieVO> getMovieInfo() throws SQLException { return (ArrayList<MovieVO>)sqlMapClient.queryForList("admin.getMovieInfo"); } public void registerScreeningMovie(ScreeningMovieVO movieVO) throws SQLException { sqlMapClient.insert("admin.registerScreeningMovie",movieVO); } public ArrayList<HashMap> getScreeningMovieList() throws SQLException { return (ArrayList<HashMap>)sqlMapClient.queryForList("admin.getScreeningMovieList"); } public ArrayList<HashMap> getPublicDayByMovieNo(int movie_no) throws SQLException { return (ArrayList<HashMap>) sqlMapClient.queryForList("admin.getPublicDayByMovieNo",movie_no); } public void regScreeningMovie(ScreeningMovieVO movieVO) throws SQLException { sqlMapClient.insert("admin.regScreeningMovie",movieVO); } /** * 상영표에 등록 가능한 영화 목록들을 가져온다. */ public ArrayList<Map> getRegisterPossibleMovie() throws SQLException { return (ArrayList<Map>) sqlMapClient.queryForList("admin.getRegisterPossibleMovie"); } /** * 상영표에 등록 가능한 지역 목록들을 가져온다. */ public ArrayList<Map> getRegisterPossibleLocal() throws SQLException { return (ArrayList<Map>) sqlMapClient.queryForList("admin.getRegisterPossibleLocal"); } /** * 상영표에 등록 가능한 영화관 목록들을 가져온다. */ public ArrayList<Map> getRegisterPossibleTheater() throws SQLException { return (ArrayList<Map>) sqlMapClient.queryForList("admin.getRegisterPossibleTheater"); } /** * 상영표 등록시 영화선택에 따른 지역 정보를 가져온다. */ public ArrayList<Map> getLocalAsMovieNo(String movie_no) throws SQLException { return (ArrayList<Map>) sqlMapClient.queryForList("admin.getLocalAsMovieNo",movie_no); } /** * 상영표 등록시 영화,지역 선택에 따른 영화관 정보를 가져온다. */ public ArrayList<Map> getTheaterAsLocalNoAndMovleNo(Map map) throws SQLException { return (ArrayList<Map>) sqlMapClient.queryForList("admin.getTheaterAsLocalNoAndMovleNo",map); } /** * 상영표 등록시 영화관 선택에 따른 상영관 정보를 가져온다. */ public ArrayList<Map> getPlayRoomAsTheaterNo(String theater_no) throws SQLException { return (ArrayList<Map>) sqlMapClient.queryForList("admin.getPlayRoomAsTheaterNo",theater_no); } /** * 상영표 등록시 해당 영화의 상영기간을 가져온다. */ public HashMap getPossibleDateAsMovieNo(Map map) throws SQLException { return (HashMap) sqlMapClient.queryForObject("admin.getPossibleDateAsMovieNo",map); } /** * 상영표 등록시 해당 영화의 러닝타임을 가져온다. */ public int getRunninTimeAsMovieNo(String movie_no) throws SQLException { return (int) sqlMapClient.queryForObject("admin.getRunninTimeAsMovieNo",movie_no); } //영화관 등록 메서드 :신일 public void registerTheater(TheaterVO theaterVO) throws SQLException { int id=(Integer)sqlMapClient.insert("admin.registerTheater",theaterVO); theaterVO.setTheater_no(id); } //상영관 등록 메서드 :신일 public void registerPlayRoom(PlayRoomVO playRoomVO) throws SQLException { int id=(Integer)sqlMapClient.insert("admin.registerPlayRoom",playRoomVO); playRoomVO.setPlay_room_uniq_no(id); } //인자값 TheaterVO 로 TheaterVO 를 로딩하는 메서드 :신일 public TheaterVO getTheaterVObyTNo(TheaterVO theaterVO) throws SQLException { return (TheaterVO) sqlMapClient.queryForObject("admin.getTheaterVObyTNo",theaterVO); } //인자값 TheaterVO 로 영화관 정보를 수정 :신일 public void modifyTheaterVObyTheaterVO(TheaterVO theaterVO) throws SQLException { sqlMapClient.update("admin.modifyTheaterVObyTheaterVO",theaterVO); } //인자값 theater_no 로 해당되는 상영관 리스트를 로딩 :신일 public ArrayList<PlayRoomVO> getPlayRoomVObyTNO(int tno) throws SQLException{ return (ArrayList<PlayRoomVO>) sqlMapClient.queryForList("admin.getPlayRoomVObyTNO",tno); } //인자값 int playRoomNo 상영관 삭제 : 참조키가 물려있는 경우 sql exception 발생 :신일 public void delPlayRoom(int playRoomNo) throws SQLException { sqlMapClient.delete("admin.delPlayRoom",playRoomNo); } //playRoomNo 로딩 : 상영관 삭제후 결과 값 (상영관 번호) 를 반환 :신일 public int getPlayRoomNoByPlayRoomUniqNo(int playRoomNo) throws SQLException{ return (Integer) sqlMapClient.queryForObject("admin.getPlayRoomNoByPlayRoomUniqNo",playRoomNo); } //playRoomTypeVo 를 리스트로 로딩 : 상영관 등록 및 수정 시 입력 가능한 상영관 타입을 로딩 :신일 public ArrayList<PlayRoomTypeVO> getPlayRoomTypeVO() throws SQLException{ return (ArrayList<PlayRoomTypeVO>) sqlMapClient.queryForList("admin.getPlayRoomTypeVO"); } /** * 상영표 등록시 영화관, 상영관 번호로 상영관의uniqNo를 가져온다. */ public String getPlayRoomUniqNoAsTheaterNoAndPlayRoomNo(Map map) throws SQLException { return (String) sqlMapClient.queryForObject("admin.getPlayRoomUniqNoAsTheaterNoAndPlayRoomNo",map); } /** * 상영표 등록 */ public void timeTableRegister(HashMap map) throws SQLException { sqlMapClient.insert("admin.timeTableRegister",map); } /** * 상영표 등록시 현재 등록되어 있는 목록을 가져옴 (paging) */ public ArrayList<Map> getTimeTable(String pageNo) throws SQLException { return (ArrayList<Map>) sqlMapClient.queryForList("admin.getTimeTable",pageNo); } /** * 상영표 목록 페이징을 위해서 총 갯수를 가져옴 */ public int getTotalTimeTable() throws SQLException { return (Integer)sqlMapClient.queryForObject("admin.getTotalTimeTable"); } /** * 상영표 등록시 영화 선택에 따라서 해당 영화의 상영표 등록현황을 가져옴 */ public ArrayList<HashMap> getTimeTableAsMovieNo(String movie_no) throws SQLException { return (ArrayList<HashMap>) sqlMapClient.queryForList("admin.getTimeTableAsMovieNo",movie_no); } /** * 상영표 등록시 영화,지역 선택에 따라서 해당 영화의 상영표 등록현황을 가져옴 */ public ArrayList<HashMap> getTimeTableAsMovieNoAndLocalNo(Map map) throws SQLException { return (ArrayList<HashMap>) sqlMapClient.queryForList("admin.getTimeTableAsMovieNoAndLocalNo",map); } /** * 상영표 등록시 영화,지역,영화관 선택에 따라서 해당 영화의 상영표 등록현황을 가져옴 */ public ArrayList<HashMap> getTimeTableAsMovieNoAndLocalNoAndTheaterNo(HashMap queryMap) throws SQLException { return (ArrayList<HashMap>) sqlMapClient.queryForList("admin.getTimeTableAsMovieNoAndLocalNoAndTheaterNo",queryMap); } /** * 상영표 등록시 영화,지역,영화관,상영관 선택에 따라서 해당 영화의 상영표 등록현황을 가져옴 */ public ArrayList<HashMap> getTimeTableAsAllNo(HashMap map) throws SQLException { return (ArrayList<HashMap>) sqlMapClient.queryForList("admin.getTimeTableAsAllNo",map); } /** * 상영표 삭제시 time_table_no 로 해당 게시물 삭제 */ public void delTimeTable(String str) throws SQLException { sqlMapClient.delete("admin.delTimeTable",str); } /** * 상영표 삭제시 등록되어 있는 모든 time_table_no 를 가져옴 */ public ArrayList<String> getAllTimeTableNo() throws SQLException { return (ArrayList<String>) sqlMapClient.queryForList("admin.getAllTimeTableNo"); } /** * 5/8 아영추가사항 * @param movie_no * @throws SQLException */ public void regMovieToStatics(MovieVO vo) throws SQLException { sqlMapClient.insert("admin.regMovieToStatics", vo); sqlMapClient.insert("admin.regMovieToStaticsWoman",vo); } /** * 영화정보 수정 * @throws SQLException */ public void modifyMovie(MovieVO movieVO) throws SQLException { sqlMapClient.update("admin.modifyMovie",movieVO); } /** * 박스 오피스 업데이트 5/9 아영 */ public void updateBoxOffice(StaticsVO statics) throws SQLException { sqlMapClient.update("admin.updateBoxOffice",statics); } /** * 철희 * 통계에서 박스오피스 업데이트시 최근1주일 제외하고 reservation 모두삭제 */ public void deleteReservationWeek() throws SQLException{ sqlMapClient.delete("admin.deleteReservationWeek"); } /** * 철희 * 통계에서 박스오피스 업데이트시 최근1주일 제외하고 time_table 모두삭제 */ public void deleteTimeTableWeek() throws SQLException{ sqlMapClient.delete("admin.deleteTimeTableWeek"); } /** * 누적관객수 불러오기 * @throws SQLException */ public int getBoxOfficeCount(StaticsVO statics) throws SQLException { return (int) sqlMapClient.queryForObject("admin.getBoxOfficeCount",statics); } public void screeningMovieDel(Map map) throws SQLException { sqlMapClient.delete("admin.screeningMovieDel",map); } public String todayCheck() throws SQLException { return (String) sqlMapClient.queryForObject("admin.todayCheck"); } }
/* * This file is part of PixelCam Mod, licensed under the Apache License, Version 2.0. * * Copyright (c) 2016 CrushedPixel <http://crushedpixel.eu> * Copyright (c) contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.replaymod.pixelcam; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.replaymod.pixelcam.path.CameraPath; import com.replaymod.pixelcam.path.Position; import net.minecraft.client.Minecraft; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.lang.reflect.Type; import java.util.List; /** * Created by misson20000 on 7/20/16. */ public class PathSaveHandler { private File saveDir; private Gson gson; private Type listType = new TypeToken<List<Position>>() {}.getType(); public PathSaveHandler() { saveDir = new File(Minecraft.getMinecraft().mcDataDir, "paths"); if(!saveDir.exists()) { saveDir.mkdir(); } // might be a good idea to do a bit more sanity checking here, but I don't care enough to code that gson = new Gson(); } public String[] listSaveNames() { String[] src = saveDir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".path"); } }); // strip .path extension String[] dst = new String[src.length]; for(int i = 0; i < src.length; i++) { dst[i] = src[i].substring(0, src[i].length()-5); } return dst; } public void loadPath(CameraPath cameraPath, String name) throws FileNotFoundException { File f = new File(saveDir, name + ".path"); cameraPath.setPoints(gson.<List<Position>>fromJson(new FileReader(f), listType)); } public void savePath(CameraPath path, String name) throws IOException { File f = new File(saveDir, name + ".path"); FileWriter writer = new FileWriter(f); gson.toJson(path.getPoints(), listType, writer); writer.close(); } }
package ca.csf.dfc.poo.Singleton; public class ObjetSeul { private static ObjetSeul instance = new ObjetSeul(); //espace memoire deja reserve private ObjetSeul() {};//constructeur private comme sa personne peut creer la classe public static ObjetSeul getInstance(){ return instance; } public void showMessage(){ System.out.println("Hello World!"); } }
package ru.aahzbrut.reciperestapi.dto.responses.recipe; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import ru.aahzbrut.reciperestapi.domain.Difficulty; import ru.aahzbrut.reciperestapi.dto.responses.category.CategoryResponse; import ru.aahzbrut.reciperestapi.dto.responses.note.NoteResponse; import ru.aahzbrut.reciperestapi.dto.responses.step.StepResponse; import java.time.LocalDateTime; import java.util.LinkedList; import java.util.List; import static ru.aahzbrut.reciperestapi.utils.Constants.ISO_DATE_TIME_PATTERN; @Getter @Setter @NoArgsConstructor public class RecipeResponse { private Long id; private String name; private String description; private Difficulty difficulty; private Integer numServings; private String source; private String url; private byte[] image; private List<CategoryResponse> categories = new LinkedList<>(); private List<NoteResponse> notes = new LinkedList<>(); private List<StepResponse> steps = new LinkedList<>(); @JsonFormat(pattern = ISO_DATE_TIME_PATTERN) private LocalDateTime createdDateTime; @JsonFormat(pattern = ISO_DATE_TIME_PATTERN) private LocalDateTime updatedDateTime; }
package br.com.pcmaker.spring.config; import javax.sql.DataSource; import org.apache.commons.configuration2.DatabaseConfiguration; import org.apache.commons.configuration2.FileBasedConfiguration; import org.apache.commons.configuration2.PropertiesConfiguration; import org.apache.commons.configuration2.builder.BasicConfigurationBuilder; import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder; import org.apache.commons.configuration2.builder.fluent.DatabaseBuilderParameters; import org.apache.commons.configuration2.builder.fluent.Parameters; import org.apache.commons.configuration2.ex.ConfigurationException; import org.apache.commons.configuration2.io.ClasspathLocationStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ConfigInit { private static final Logger LOGGER = LoggerFactory.getLogger(ConfigInit.class); private static final String PROPERTIES_FILE_NAME = "configuracao.properties"; private static final String PROPERTIES_LOCAL_FILE_NAME = "localhost.properties"; @Autowired DataSource dataSource; @Bean public FileBasedConfiguration configuracaoGlobal() throws Exception { Parameters params = new Parameters(); FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class) .configure(params.properties() .setLocationStrategy(new ClasspathLocationStrategy()) .setFileName(PROPERTIES_FILE_NAME)); return builder.getConfiguration(); } @Bean public FileBasedConfiguration configuracaoLocal() throws Exception { Parameters params = new Parameters(); FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class) .configure(params.properties() .setLocationStrategy(new ClasspathLocationStrategy()) .setFileName(PROPERTIES_LOCAL_FILE_NAME)); try{ return builder.getConfiguration(); }catch(ConfigurationException e){ LOGGER.warn("Nao encontrou arquivo local " + PROPERTIES_LOCAL_FILE_NAME); } return null; } @Bean public DatabaseConfiguration configuracaoDS() throws Exception { BasicConfigurationBuilder<DatabaseConfiguration> builder = new BasicConfigurationBuilder<DatabaseConfiguration>(DatabaseConfiguration.class); DatabaseBuilderParameters databaseBuilderParameters = new Parameters().database(); databaseBuilderParameters .setDataSource(dataSource) .setTable("configuracao") .setKeyColumn("chave") .setValueColumn("valor"); builder.configure(databaseBuilderParameters); return builder.getConfiguration(); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.eclipse; import java.io.File; import java.io.FilenameFilter; import java.lang.reflect.InvocationTargetException; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.hadoop.eclipse.preferences.MapReducePreferencePage; import org.apache.hadoop.eclipse.preferences.PreferenceConstants; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExecutableExtension; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jdt.ui.wizards.NewJavaProjectWizardPage; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.preference.PreferenceDialog; import org.eclipse.jface.preference.PreferenceManager; import org.eclipse.jface.preference.PreferenceNode; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.Wizard; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchWizard; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.WizardNewProjectCreationPage; import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard; /** * Wizard for creating a new MapReduce Project * */ public class NewMapReduceProjectWizard extends Wizard implements IWorkbenchWizard, IExecutableExtension { static Logger log = Logger.getLogger(NewMapReduceProjectWizard.class.getName()); private HadoopFirstPage firstPage; private NewJavaProjectWizardPage javaPage; public NewDriverWizardPage newDriverPage; private IConfigurationElement config; public NewMapReduceProjectWizard() { setWindowTitle("New MapReduce Project Wizard"); } public void init(IWorkbench workbench, IStructuredSelection selection) { } @Override public boolean canFinish() { return firstPage.isPageComplete() && javaPage.isPageComplete() // && ((!firstPage.generateDriver.getSelection()) // || newDriverPage.isPageComplete() ; } @Override public IWizardPage getNextPage(IWizardPage page) { // if (page == firstPage // && firstPage.generateDriver.getSelection() // ) // { // return newDriverPage; // if "generate mapper" checked, second page is // new driver page // } // else // { IWizardPage answer = super.getNextPage(page); if (answer == newDriverPage) { return null; // dont flip to new driver page unless "generate // driver" is checked } else if (answer == javaPage) { return answer; } else { return answer; } // } } @Override public IWizardPage getPreviousPage(IWizardPage page) { if (page == newDriverPage) { return firstPage; // newDriverPage, if it appears, is the second // page } else { return super.getPreviousPage(page); } } static class HadoopFirstPage extends WizardNewProjectCreationPage implements SelectionListener { public HadoopFirstPage() { super("New Hadoop Project"); setImageDescriptor(ImageLibrary.get("wizard.mapreduce.project.new")); } private Link openPreferences; private Button workspaceHadoop; private Button projectHadoop; private Text location; private Button browse; private String path; public String currentPath; // private Button generateDriver; @Override public void createControl(Composite parent) { super.createControl(parent); setTitle("MapReduce Project"); setDescription("Create a MapReduce project."); Group group = new Group((Composite) getControl(), SWT.NONE); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText("Hadoop MapReduce Library Installation Path"); GridLayout layout = new GridLayout(3, true); layout.marginLeft = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.marginRight = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN); layout.marginTop = convertHorizontalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.marginBottom = convertHorizontalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); group.setLayout(layout); workspaceHadoop = new Button(group, SWT.RADIO); GridData d = new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false); d.horizontalSpan = 2; workspaceHadoop.setLayoutData(d); // workspaceHadoop.setText("Use default workbench Hadoop library // location"); workspaceHadoop.setSelection(true); updateHadoopDirLabelFromPreferences(); openPreferences = new Link(group, SWT.NONE); openPreferences .setText("<a>Configure Hadoop install directory...</a>"); openPreferences.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false)); openPreferences.addSelectionListener(this); projectHadoop = new Button(group, SWT.RADIO); projectHadoop.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false)); projectHadoop.setText("Specify Hadoop library location"); location = new Text(group, SWT.SINGLE | SWT.BORDER); location.setText(""); d = new GridData(GridData.END, GridData.CENTER, true, false); d.horizontalSpan = 1; d.widthHint = 250; d.grabExcessHorizontalSpace = true; location.setLayoutData(d); location.setEnabled(false); browse = new Button(group, SWT.NONE); browse.setText("Browse..."); browse.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false)); browse.setEnabled(false); browse.addSelectionListener(this); projectHadoop.addSelectionListener(this); workspaceHadoop.addSelectionListener(this); // generateDriver = new Button((Composite) getControl(), SWT.CHECK); // generateDriver.setText("Generate a MapReduce driver"); // generateDriver.addListener(SWT.Selection, new Listener() // { // public void handleEvent(Event event) { // getContainer().updateButtons(); } // }); } @Override public boolean isPageComplete() { boolean validHadoop = validateHadoopLocation(); if (!validHadoop && isCurrentPage()) { setErrorMessage("Invalid Hadoop Runtime specified; please click 'Configure Hadoop install directory' or fill in library location input field"); } else { setErrorMessage(null); } return super.isPageComplete() && validHadoop; } private boolean validateHadoopLocation() { FilenameFilter gotHadoopJar = new FilenameFilter() { public boolean accept(File dir, String name) { return (name.startsWith("hadoop") && name.endsWith(".jar") && (name.indexOf("test") == -1) && (name.indexOf("examples") == -1)); } }; if (workspaceHadoop.getSelection()) { this.currentPath = path; return new Path(path).toFile().exists() && (new Path(path).toFile().list(gotHadoopJar).length > 0); } else { this.currentPath = location.getText(); File file = new Path(location.getText()).toFile(); return file.exists() && (new Path(location.getText()).toFile().list(gotHadoopJar).length > 0); } } private void updateHadoopDirLabelFromPreferences() { path = Activator.getDefault().getPreferenceStore().getString( PreferenceConstants.P_PATH); if ((path != null) && (path.length() > 0)) { workspaceHadoop.setText("Use default Hadoop"); } else { workspaceHadoop.setText("Use default Hadoop (currently not set)"); } } public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { if (e.getSource() == openPreferences) { PreferenceManager manager = new PreferenceManager(); manager.addToRoot(new PreferenceNode( "Hadoop Installation Directory", new MapReducePreferencePage())); PreferenceDialog dialog = new PreferenceDialog(this.getShell(), manager); dialog.create(); dialog.setMessage("Select Hadoop Installation Directory"); dialog.setBlockOnOpen(true); dialog.open(); updateHadoopDirLabelFromPreferences(); } else if (e.getSource() == browse) { DirectoryDialog dialog = new DirectoryDialog(this.getShell()); dialog .setMessage("Select a hadoop installation, containing hadoop-X-core.jar"); dialog.setText("Select Hadoop Installation Directory"); String directory = dialog.open(); if (directory != null) { location.setText(directory); if (!validateHadoopLocation()) { setErrorMessage("No Hadoop jar found in specified directory"); } else { setErrorMessage(null); } } } else if (projectHadoop.getSelection()) { location.setEnabled(true); browse.setEnabled(true); } else { location.setEnabled(false); browse.setEnabled(false); } getContainer().updateButtons(); } } @Override public void addPages() { /* * firstPage = new HadoopFirstPage(); addPage(firstPage ); addPage( new * JavaProjectWizardSecondPage(firstPage) ); */ firstPage = new HadoopFirstPage(); javaPage = new NewJavaProjectWizardPage(ResourcesPlugin.getWorkspace() .getRoot(), firstPage); // newDriverPage = new NewDriverWizardPage(false); // newDriverPage.setPageComplete(false); // ensure finish button // initially disabled addPage(firstPage); addPage(javaPage); // addPage(newDriverPage); } @Override public boolean performFinish() { try { PlatformUI.getWorkbench().getProgressService().runInUI( this.getContainer(), new IRunnableWithProgress() { public void run(IProgressMonitor monitor) { try { monitor.beginTask("Create Hadoop Project", 300); javaPage.getRunnable().run( new SubProgressMonitor(monitor, 100)); // if( firstPage.generateDriver.getSelection()) // { // newDriverPage.setPackageFragmentRoot(javaPage.getNewJavaProject().getAllPackageFragmentRoots()[0], // false); // newDriverPage.getRunnable().run(new // SubProgressMonitor(monitor,100)); // } IProject project = javaPage.getNewJavaProject().getResource().getProject(); IProjectDescription description = project.getDescription(); String[] existingNatures = description.getNatureIds(); String[] natures = new String[existingNatures.length + 1]; for (int i = 0; i < existingNatures.length; i++) { natures[i + 1] = existingNatures[i]; } natures[0] = MapReduceNature.ID; description.setNatureIds(natures); project.setPersistentProperty(new QualifiedName( Activator.PLUGIN_ID, "hadoop.runtime.path"), firstPage.currentPath); project.setDescription(description, new NullProgressMonitor()); String[] natureIds = project.getDescription().getNatureIds(); for (int i = 0; i < natureIds.length; i++) { log.fine("Nature id # " + i + " > " + natureIds[i]); } monitor.worked(100); monitor.done(); BasicNewProjectResourceWizard.updatePerspective(config); } catch (CoreException e) { // TODO Auto-generated catch block log.log(Level.SEVERE, "CoreException thrown.", e); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }, null); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return true; } public void setInitializationData(IConfigurationElement config, String propertyName, Object data) throws CoreException { this.config = config; } }
package org.hov.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.List; import org.hov.config.AppConfig; import org.hov.model.User; import org.hov.service.UserService; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringJUnitConfig(classes=AppConfig.class) public class UserTestCases { @Autowired UserService userService; /* CREATION TEST CASES */ @Test @Ignore public void addUserValid1() //Valid Record { User user = new User(); user.setFirstName("Tester123"); user.setLastName("123"); user.setUserEmail("testing@foodieff.com"); user.setUserPassword("Test@123"); user.setTeamId(0); user.setAuthority("BUYER"); user.setBlocked(false); assertEquals(true , userService.addUser(user)); } /* * @Test * * @Ignore public void addUserInvalid1() //Invalid Record { User user = new * User(); user.setFirstName("Tester123"); user.setLastName("123"); * user.setUserEmail("testing@foodieff.com"); user.setUserPassword("Test@123"); * user.setTeamId(0); user.setAuthority("BUYER"); user.setBlocked(false); * * assertEquals(true , userService.addUser(user)); } */ /* RETRIEVE TEST CASES */ @Test //@Ignore public void displayAllUserListValid() { List<User> userlist = userService.getAllUsers(); for(User u:userlist) { System.out.println("--------------------------"); System.out.println(u.getUserId()); System.out.println(u.getFirstName()); System.out.println(u.getLastName()); System.out.println(u.getUserEmail()); System.out.println(u.getUserPassword()); System.out.println(u.getAuthority()); System.out.println(u.getVerificationCode()); System.out.println(u.isVerified()); System.out.println(u.isBlocked()); System.out.println(u.isSuspended()); System.out.println(""); } assertNotNull(userlist); } @Test @Ignore public void displayUserbyIdValid1() //User 5 { User u = userService.getUserById(5); System.out.println("--------------------------"); System.out.println(u.getUserId()); System.out.println(u.getFirstName()); System.out.println(u.getLastName()); System.out.println(u.getUserEmail()); System.out.println(u.getUserPassword()); System.out.println(u.getAuthority()); System.out.println(u.getVerificationCode()); System.out.println(u.isVerified()); System.out.println(u.isBlocked()); System.out.println(u.isSuspended()); System.out.println(""); assertNotNull(u); } @Test @Ignore public void displayUserbyIdInvalid1() //User -999 { assertNull(userService.getUserById(-1)); } @Test @Ignore public void displayUserbyEmailValid1() //Valid Email { User u = userService.getUserByEmail("user123@foodie.com"); System.out.println("--------------------------"); System.out.println(u.getUserId()); System.out.println(u.getFirstName()); System.out.println(u.getLastName()); System.out.println(u.getUserEmail()); System.out.println(u.getUserPassword()); System.out.println(u.getAuthority()); System.out.println(u.getVerificationCode()); System.out.println(u.isVerified()); System.out.println(u.isBlocked()); System.out.println(u.isSuspended()); System.out.println(""); assertNotNull(u); } @Test @Ignore public void displayUserbyEmailInvalid1() //Invalid Email { assertNull(userService.getUserByEmail("x323535xxy3434y5454yzzz@foodie.com")); } /* UPDATION TEST CASES */ @Test @Ignore public void updateUserValid1() // Update User Id 11 { User u = userService.getUserById(11); u.setFirstName("Updated UserName1"); assertEquals(true, userService.updateUser(u)); } /* SUB-UPDATION TEST CASES */ @Test @Ignore public void blockUserValid() // Id = 5 { assertEquals(true, userService.blockUserById(5)); } @Test @Ignore public void unblockUserValid() // Id = 5 { assertEquals(true, userService.unblockUserById(5)); } @Test @Ignore public void suspendUserValid() // Id = 5 { assertEquals(true, userService.suspendUserById(5)); } }
package com.giga.annotation; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.Arrays; import java.util.List; public class CityValidator implements ConstraintValidator<City, String> { List<String> cities = Arrays.asList("Sai Gon", "Ha Noi", "Da Nang", "Hue", "Quang Nam"); @Override public boolean isValid(String value, ConstraintValidatorContext context) { return cities.contains(value); } }
//This class is responsible for creating and removing the blades when the mouse is dragged based on a set duration import java.awt.Image; public class Blade { private int xPosition; private int yPosition; private Image picture; private int counter; private final int BLADE_DURATION=7; public Blade (int x, int y, Image pic) { setxPosition(x); setyPosition(y); setPicture(pic); setCounter(0); } public void setxPosition(int xPosition) { this.xPosition = xPosition; } public int getxPosition() { return xPosition; } public void setyPosition(int yPosition) { this.yPosition = yPosition; } public int getyPosition() { return yPosition; } public void setPicture(Image picture) { this.picture = picture; } public Image getPicture() { return picture; } public void setCounter(int counter) { this.counter = counter; } public int getCounter() { return counter; } public int getBLADE_DURATION() { return BLADE_DURATION; } }
package com.translator.domain.model.validation; import com.translator.domain.model.numeral.RomanNumeral; import java.util.Collections; import java.util.HashMap; import java.util.List; import static com.translator.domain.model.numeral.RomanNumeral.*; import static com.translator.domain.model.numeral.RomanNumeral.C; import static com.translator.domain.model.numeral.RomanNumeral.M; import static java.util.Arrays.asList; public class SubtractionPairsNotRepeated implements Validator { private static final HashMap<List<RomanNumeral>, Integer> SUBTRACTION_NUMERAL_VALUES = new HashMap<List<RomanNumeral>, Integer>(){{ put(asList(I,V), 4); put(asList(I,X), 9); put(asList(X,L), 40); put(asList(X,C), 90); put(asList(C,D), 400); put(asList(C,M), 900); }}; public boolean validate(List<RomanNumeral> romanNumerals) { return subtractionPairsNotRepeated(romanNumerals); } private boolean subtractionPairsNotRepeated(List<RomanNumeral> numerals) { for (List<RomanNumeral> invalidSequence : SUBTRACTION_NUMERAL_VALUES.keySet()) { int first = Collections.indexOfSubList(numerals, invalidSequence); int second = Collections.lastIndexOfSubList(numerals, invalidSequence); if (first != second) { return false; } } return true; } }
package model.vo.mycinema; import model.vo.mycinema.MemberLevelInfoVO; public class MemberVO { private int member_no; private String ssn; private String id; private String password; private String name; private String member_addr; private String email; private String join_day; private String member_tel; private MemberLevelInfoVO memberlevelinfoVO ; public MemberVO() { super(); // TODO Auto-generated constructor stub } public MemberVO(int member_no, String ssn, String id, String password, String name, String member_addr, String email, String join_day, String member_tel, MemberLevelInfoVO memberlevelinfoVO) { super(); this.member_no = member_no; this.ssn = ssn; this.id = id; this.password = password; this.name = name; this.member_addr = member_addr; this.email = email; this.join_day = join_day; this.member_tel = member_tel; this.memberlevelinfoVO = memberlevelinfoVO; } public int getMember_no() { return member_no; } public void setMember_no(int member_no) { this.member_no = member_no; } public String getSsn() { return ssn; } public void setSsn(String ssn) { this.ssn = ssn; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMember_addr() { return member_addr; } public void setMember_addr(String member_addr) { this.member_addr = member_addr; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getJoin_day() { return join_day; } public void setJoin_day(String join_day) { this.join_day = join_day; } public String getMember_tel() { return member_tel; } public void setMember_tel(String member_tel) { this.member_tel = member_tel; } public MemberLevelInfoVO getMemberlevelinfoVO() { return memberlevelinfoVO; } public void setMemberlevelinfoVO(MemberLevelInfoVO memberlevelinfoVO) { this.memberlevelinfoVO = memberlevelinfoVO; } @Override public String toString() { return "MemberVO [member_no=" + member_no + ", ssn=" + ssn + ", id=" + id + ", password=" + password + ", name=" + name + ", member_addr=" + member_addr + ", email=" + email + ", join_day=" + join_day + ", member_tel=" + member_tel + ", memberlevelinfoVO=" + memberlevelinfoVO + "]"; } }
package com.sharpower.service.impl; import com.sharpower.entity.User; import com.sharpower.service.UserService; public class UserServiceImpl extends BaseServiceImpl<User> implements UserService { }
package com.xindq.yilan.dialog.item; import android.app.Dialog; import android.content.Context; import android.graphics.Point; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.TextView; import com.xindq.yilan.R; import com.xindq.yilan.domain.Item; public class ItemDialog extends Dialog implements View.OnClickListener { private TextView mTvTitle, mTvCancle, mTvConfilm; private TextView mTvItemId, mTvItemName, mTvItemType, mTvItemNotes, mTvItemGroup; private TextView mTvItemUnit, mTvItemMin, mTvItemMax, mTvItemNormal; private Item item; private DialogListener listener; public ItemDialog(@NonNull Context context) { super(context); } public ItemDialog(@NonNull Context context, int themeResId) { super(context, themeResId); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog_item); setWidth(); init(); } private void setWidth() { WindowManager manager = getWindow().getWindowManager(); Display display = manager.getDefaultDisplay(); WindowManager.LayoutParams params = getWindow().getAttributes(); Point size = new Point(); display.getSize(size); params.width = (int) (size.x * 0.8); getWindow().setAttributes(params); } private void init() { mTvTitle = findViewById(R.id.dialog_title); mTvCancle = findViewById(R.id.dialog_cancle); mTvConfilm = findViewById(R.id.dialog_confirm); mTvCancle.setOnClickListener(this); mTvConfilm.setOnClickListener(this); mTvItemId = findViewById(R.id.dialog_item_id); mTvItemName = findViewById(R.id.dialog_item_name); mTvItemType = findViewById(R.id.dialog_item_type); mTvItemNotes = findViewById(R.id.dialog_item_notes); mTvItemGroup = findViewById(R.id.dialog_item_group); mTvItemUnit = findViewById(R.id.dialog_item_unit); mTvItemMin = findViewById(R.id.dialog_item_min); mTvItemMax = findViewById(R.id.dialog_item_max); mTvItemNormal = findViewById(R.id.dialog_item_normal); mTvItemId.setText(item.getId() + ""); mTvItemName.setText(item.getItemName()); mTvItemType.setText(item.getType()); mTvItemNotes.setText(item.getNotes()); mTvItemGroup.setText(item.getGroup()); mTvItemUnit.setText(item.getUnit()); mTvItemMax.setText(item.getMax() + ""); mTvItemMin.setText(item.getMin() + ""); mTvItemNormal.setText(item.getNormal() + ""); } public ItemDialog setItem(Item item) { this.item = item; return this; } public Item getItem() { return item; } public ItemDialog setOnClickBtnListener(DialogListener listener) { this.listener = listener; return this; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.dialog_cancle: dismiss(); if (listener != null) { listener.onCancle(); } break; case R.id.dialog_confirm: if (listener != null) { listener.onConfirm(); } break; } } interface DialogListener { void onConfirm(); void onCancle(); } }
package discreteStochaticSim; import java.util.Comparator; /************************************************************** * Comparador entre Eventos * * @author Grupo 11 * <p> Classe que e usada somente para comparar Eventos baseando * nos seus tempos. Quando usado com o metodo list.sort (Comparador), * ele classificara uma lista de eventos pelo menor tempo primeiro. * Ele implementa a interface do Comparador substituindo o metodo * de comparacao. *************************************************************/ public class EventComparator implements Comparator<Event> { /******************************************************** * Metodo que substitui o metodo comparador. Ele recebe dois * argumentos e retorna um inteiro baseado na comparacao do * campo de tempo dos argumentos. * @param event1 e o primeiro evento que queremos comparar. * @param event2 e o segundo evento que queremos comparar. * * @return e -1 se o primeiro tiver menor tempo, +1 se for * o contrario e 0 se for o mesmo. * ********************************************************/ public int compare (Event event1, Event event2) { double time1 = event1.getTime(); double time2 = event2.getTime(); return time1 < time2 ? -1 : time1 > time2 ? +1 : 0; } }
package com.jim.multipos.ui.admin_main_page.fragments.product.adapter; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.jim.mpviews.MpRoundedImageView; import com.jim.multipos.R; import com.jim.multipos.core.BaseAdapter; import com.jim.multipos.core.BaseViewHolder; import com.jim.multipos.ui.admin_main_page.fragments.product.model.Product; import com.jim.multipos.utils.OnItemClickListener; import java.util.List; import butterknife.BindView; public class ProductAdapter extends BaseAdapter<Product, ProductAdapter.ViewHolder>{ OnItemClickListener<Product> listener; public ProductAdapter(List<Product> items, OnItemClickListener<Product> listener) { super(items); this.listener = listener; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.admin_product_list_item, parent, false)); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Product product = items.get(position); holder.tvProductName.setText(product.getName()); holder.tvBarcode.setText(product.getBarcode()); holder.tvSku.setText(product.getSku()); holder.tvPriceUnit1.setText(product.getPriceUnit_1()); holder.tvPriceUnit2.setText(product.getPriceUnit_2()); holder.itemView.setOnClickListener(v -> listener.onItemClicked(product)); } class ViewHolder extends BaseViewHolder{ @BindView(R.id.ivProductImage) MpRoundedImageView ivProductImage; @BindView(R.id.tvProductName) TextView tvProductName; @BindView(R.id.tvBarcode) TextView tvBarcode; @BindView(R.id.tvSku) TextView tvSku; @BindView(R.id.tvPriceUnit1) TextView tvPriceUnit1; @BindView(R.id.tvPriceUnit2) TextView tvPriceUnit2; public ViewHolder(View itemView) { super(itemView); } } }
package lastoccurance; public class Solutiontest { public static void main (String []args){ Solution s = new Solution (); int array[] = {1,2,2,2,3}; System.out.println(s.lastOccur(array, 2)); } }
package com.lalit.hibernate.mapping.onetoone.bidirectional; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class DeleteDemo { public static void main(String... s) { SessionFactory factory = new Configuration().configure("hibernate.cfg-mapping.xml").addAnnotatedClass(Instructor.class).addAnnotatedClass(InstructorDetails.class).buildSessionFactory(); Session session = factory.getCurrentSession(); try { session.beginTransaction(); InstructorDetails instructorDetails = session.get(InstructorDetails.class, 13); System.out.println(instructorDetails.getInstructor()); instructorDetails.getInstructor().setInstructorDetails(null); session.delete(instructorDetails); session.getTransaction().commit(); } finally { session.close(); factory.close(); } } }
package com.tencent.mm.plugin.hp.b; import com.tencent.mm.g.a.d; import com.tencent.mm.model.au; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.x; import com.tinkerboots.sdk.a; public final class f extends c<d> { private static long bvB = 0; public f() { this.sFo = d.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { if (!(((d) bVar).bGd.bGe || au.HM())) { long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis - bvB >= 21600000 && a.cJC() != null) { a.cJC().na(false); x.i("MicroMsg.Tinker.TinkerBootsActivateListener", "callback post task and fetchPatchUpdate false"); bvB = currentTimeMillis; } } return false; } public static void dM(long j) { bvB = j; } }
package onlinerealestateproject.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import onlinerealestateproject.domain.Apartment; import onlinerealestateproject.dto.ApartmentDTO; import onlinerealestateproject.lock.impl.ExclusiveWriteLockManager; import onlinerealestateproject.service.ApartmentService; import onlinerealestateproject.service.ApartmentServiceBean; import onlinerealestateproject.service.imp.ApartmentServiceBeanImp; import onlinerealestateproject.service.imp.ApartmentServiceImp; import onlinerealestateproject.util.UnitofWorkApartment; /** * Servlet implementation class NewApartmentFormController */ @WebServlet("/NewApartmentFormController") public class NewApartmentFormController extends ActionServlet { private static final long serialVersionUID = 1L; private static ApartmentService apartmentService = new ApartmentServiceImp(); private static ApartmentServiceBean apartmentServiceBean = new ApartmentServiceBeanImp(); /** * @see HttpServlet#HttpServlet() */ public NewApartmentFormController() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //doGet(request, response); HttpSession httpSession = request.getSession(); SessionManager.getInstance().setHttpSession(httpSession); int id = Integer.parseInt(request.getParameter("id")); if(request.getParameter("back") != null) { httpSession.setAttribute("userId", id); SessionManager.getInstance().setHttpSession(httpSession); response.sendRedirect("./RealEstate/RealEstatePage.jsp?id="+id); } else if(request.getParameter("create") != null) { String startRentTime = request.getParameter("startRentTime"); String endRentTime = request.getParameter("endRentTime"); String availability = request.getParameter("availability"); int price = Integer.parseInt(request.getParameter("price")); int acreage = Integer.parseInt(request.getParameter("acreage")); String location = request.getParameter("location"); String apartmentName = request.getParameter("apartmentName"); // UnitofWorkApartment.newCurrent(); // Apartment apartment = new Apartment(0, startRentTime, endRentTime, // availability, price, acreage, location, apartmentName); // if(apartmentService.addApartment(apartment)) { // httpSession.setAttribute("userId", id); // response.sendRedirect("./RealEstate/RealEstatePage.jsp?id="+id); // } UnitofWorkApartment.newCurrent(); ApartmentDTO apartmentDTO = new ApartmentDTO(0, startRentTime, endRentTime, availability, price, acreage, location, apartmentName); apartmentServiceBean.createApartmentByByte(ApartmentDTO.object2Byte(apartmentDTO)); httpSession.setAttribute("userId", id); SessionManager.getInstance().setHttpSession(httpSession); response.sendRedirect("./RealEstate/RealEstatePage.jsp?id="+id); } } }
package jc.sugar.JiaHui.jmeter.preprocessor; import jc.sugar.JiaHui.jmeter.*; import org.apache.jmeter.protocol.http.modifier.AnchorModifier; import java.util.HashMap; import java.util.Map; @JMeterElementMapperFor(value = JMeterElementType.AnchorModifier, testGuiClass = JMeterElement.AnchorModifier) public class AnchorModifierMapper extends AbstractJMeterElementMapper<AnchorModifier> { private AnchorModifierMapper(AnchorModifier element, Map<String, Object> attributes) { super(element, attributes); } public AnchorModifierMapper(Map<String, Object> attributes){ this(new AnchorModifier(), attributes); } public AnchorModifierMapper(AnchorModifier element){ this(element, new HashMap<>()); } @Override public AnchorModifier fromAttributes() { return element; } @Override public Map<String, Object> toAttributes() { attributes.put(WEB_CATEGORY, JMeterElementCategory.Preprocessor); attributes.put(WEB_TYPE, JMeterElementType.AnchorModifier); return attributes; } }
package com.tencent.mm.plugin.sns.ui; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.messenger.a.b; import com.tencent.mm.plugin.sns.i; import com.tencent.mm.plugin.sns.i.c; import com.tencent.mm.plugin.sns.i.f; import com.tencent.mm.plugin.sns.i.j; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ab; import com.tencent.mm.ui.widget.listview.AnimatedExpandableListView.a; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public final class aq extends a { public static int[] nXP = new int[]{j.sns_label_public_hint, j.sns_label_private_hint, j.sns_label_include_hint, j.sns_label_exclude_hint}; public static int[] nXt = new int[]{j.sns_label_public, j.sns_label_private, j.sns_label_include, j.sns_label_exclude}; private LayoutInflater Bc; private Context mContext; ArrayList<String> nXQ; public int nXR = 0; public boolean nXS = false; public ArrayList<String> nXT = new ArrayList(); public ArrayList<String> nXU = new ArrayList(); public ArrayList<String> nXV = new ArrayList(); public ArrayList<String> nXW = new ArrayList(); public int style; public aq(Context context) { this.mContext = context; this.Bc = (LayoutInflater) context.getSystemService("layout_inflater"); } public final Object getChild(int i, int i2) { return this.nXQ.get(i2); } public final long getChildId(int i, int i2) { return 0; } public final void O(ArrayList<String> arrayList) { List<String> bDD = bDD(); Object arrayList2 = new ArrayList(); if (!(bDD == null || arrayList == null)) { for (String str : bDD) { if (i(arrayList, str)) { arrayList.remove(str); arrayList2.add(str); } } arrayList.addAll(0, arrayList2); String str2 = bi.c(arrayList2, ","); g.Ek(); g.Ei().DT().set(335875, str2); } this.nXQ = arrayList; } private static List<String> bDD() { g.Ek(); String str = (String) g.Ei().DT().get(335875, null); x.d("MicroMsg.Sns.AnimatedExpandableListAdapter", "dz:getTopFive : %s", new Object[]{str}); if (bi.oW(str)) { return null; } return bi.F(str.split(",")); } public static void NW(String str) { x.d("MicroMsg.Sns.AnimatedExpandableListAdapter", "recordTopFive : %s", new Object[]{str}); if (bDD() != null) { List arrayList = new ArrayList(bDD()); if (!i(arrayList, str)) { if (arrayList.size() == 5) { arrayList.remove(4); } arrayList.add(0, str); String c = bi.c(arrayList, ","); g.Ek(); g.Ei().DT().set(335875, c); return; } return; } g.Ek(); g.Ei().DT().set(335875, str); } private CharSequence NX(String str) { List<String> FD = com.tencent.mm.plugin.label.a.a.aYK().FD(com.tencent.mm.plugin.label.a.a.aYK().FA(str)); if (FD == null || FD.size() == 0) { return ""; } List arrayList = new ArrayList(FD.size()); for (String gT : FD) { arrayList.add(((b) g.l(b.class)).gT(gT)); } return com.tencent.mm.pluginsdk.ui.d.j.a(this.mContext, bi.c(arrayList, ",")); } private static boolean i(List<String> list, String str) { for (String equals : list) { if (equals.equals(str)) { return true; } } return false; } private boolean aH(int i, String str) { if (i == 1) { return i(this.nXT, str); } return i(this.nXU, str); } public final Object getGroup(int i) { return null; } public final int getGroupCount() { return 4; } public final long getGroupId(int i) { return 0; } public final View getGroupView(int i, boolean z, View view, ViewGroup viewGroup) { a aVar; if (view == null || !(view.getTag() instanceof a)) { View inflate; if (this.style == 1) { inflate = this.Bc.inflate(i.g.sns_label_expand_item_black, null); } else { inflate = this.Bc.inflate(i.g.sns_label_expand_item, null); } a aVar2 = new a(this, (byte) 0); aVar2.titleView = (TextView) inflate.findViewById(f.sns_label_title); aVar2.kYT = (ImageView) inflate.findViewById(f.sns_label_right_img); aVar2.kJq = (TextView) inflate.findViewById(f.sns_label_sub_title); inflate.setTag(aVar2); view = inflate; aVar = aVar2; } else { aVar = (a) view.getTag(); } aVar.titleView.setText(nXt[i]); aVar.kJq.setText(nXP[i]); switch (i) { case 0: case 1: if (this.nXR == i) { aVar.kYT.setImageResource(i.i.radio_on); aVar.kYT.setContentDescription(this.mContext.getString(j.selected_Imgbtn)); break; } aVar.kYT.setImageResource(i.i.radio_off); break; case 2: if (this.nXR == i) { aVar.kYT.setImageResource(i.i.radio_on); aVar.kYT.setContentDescription(this.mContext.getString(j.selected_Imgbtn)); break; } aVar.kYT.setImageResource(i.i.radio_off); break; case 3: if (this.style != 1) { if (this.nXR == i) { aVar.kYT.setImageResource(i.i.radio_on_red); aVar.kYT.setContentDescription(this.mContext.getString(j.selected_Imgbtn)); break; } aVar.kYT.setImageResource(i.i.radio_off); break; } else if (this.nXR == i) { aVar.kYT.setImageResource(i.i.round_selector_checked_orange); aVar.kYT.setContentDescription(this.mContext.getString(j.selected_Imgbtn)); break; } else { aVar.kYT.setImageResource(i.i.radio_off); break; } } if (!this.nXS || i != 1) { return view; } view = new View(this.mContext); view.setVisibility(8); return view; } public final boolean hasStableIds() { return false; } public final boolean isChildSelectable(int i, int i2) { return true; } private static List<String> aE(List<String> list) { List<String> linkedList = new LinkedList(); g.Ek(); if (!g.Eg().Dx()) { return linkedList; } if (list == null) { return linkedList; } for (Object obj : list) { Object obj2; g.Ek(); ab Yg = ((com.tencent.mm.plugin.messenger.foundation.a.i) g.l(com.tencent.mm.plugin.messenger.foundation.a.i.class)).FR().Yg(obj2); if (!(Yg == null || ((int) Yg.dhP) == 0)) { obj2 = Yg.BL(); } linkedList.add(obj2); } return linkedList; } public final View d(int i, int i2, View view) { View inflate; a aVar; if (view == null) { if (this.style == 1) { inflate = this.Bc.inflate(i.g.sns_label_child_item_black, null); } else { inflate = this.Bc.inflate(i.g.sns_label_child_item, null); } aVar = new a(this, (byte) 0); aVar.titleView = (TextView) inflate.findViewById(f.sns_label_title); aVar.kJq = (TextView) inflate.findViewById(f.sns_label_sub_title); aVar.nXX = (TextView) inflate.findViewById(f.sns_label_single_line); aVar.nXY = (TextView) inflate.findViewById(f.sns_label_selected_other_users); aVar.kYT = (ImageView) inflate.findViewById(f.sns_label_right_img); inflate.setTag(aVar); } else { aVar = (a) view.getTag(); inflate = view; } if (i2 == this.nXQ.size()) { aVar.titleView.setVisibility(8); aVar.kJq.setVisibility(8); aVar.kYT.setVisibility(8); aVar.nXX.setVisibility(0); aVar.nXY.setVisibility(0); if (i == 3) { if (this.nXW.size() > 0) { aVar.nXY.setText("√" + bi.c(aE(this.nXW), ",")); aVar.nXY.setVisibility(0); aVar.nXY.setTextColor(this.mContext.getResources().getColor(c.sns_selected_other_user_name_color_black)); } else { aVar.nXY.setText(""); aVar.nXY.setVisibility(8); } } else if (i == 2) { if (this.nXV.size() > 0) { aVar.nXY.setText("√" + bi.c(aE(this.nXV), ",")); aVar.nXY.setVisibility(0); aVar.nXY.setTextColor(this.mContext.getResources().getColor(c.sns_selected_other_user_name_color)); } else { aVar.nXY.setText(""); aVar.nXY.setVisibility(8); } } } else { aVar.titleView.setVisibility(0); aVar.kJq.setVisibility(0); aVar.kYT.setVisibility(0); aVar.nXX.setVisibility(8); aVar.nXY.setVisibility(8); String str = (String) this.nXQ.get(i2); aVar.titleView.setText(com.tencent.mm.pluginsdk.ui.d.j.a(this.mContext, str)); aVar.kJq.setText(NX(str)); aVar.kYT.setVisibility(0); if (this.style == 1) { if (i == 2) { if (aH(1, str)) { aVar.kYT.setImageResource(i.i.sight_list_checkbox_selected); } else { aVar.kYT.setImageResource(i.i.sight_list_checkbox_unselected); } } else if (i == 3) { if (this.nXR != i) { aVar.kYT.setImageResource(i.i.sight_list_checkbox_unselected_red); } else { aVar.kYT.setImageResource(i.i.sight_list_checkbox_selected_red); } if (aH(2, str)) { aVar.kYT.setImageResource(i.i.sight_list_checkbox_selected_red); } else { aVar.kYT.setImageResource(i.i.sight_list_checkbox_unselected_red); } } } else if (i == 2) { if (aH(1, str)) { aVar.kYT.setImageResource(i.i.checkbox_selected); } else { aVar.kYT.setImageResource(i.i.checkbox_unselected); } } else if (i == 3) { if (aH(2, str)) { aVar.kYT.setImageResource(i.i.checkbox_selected_red); } else { aVar.kYT.setImageResource(i.i.checkbox_unselected); } } } return inflate; } public final int xv(int i) { if (i <= 1 || this.nXQ == null) { return 0; } return this.nXQ.size() + 1; } }
/* * 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 optimization; /** * * @author hp */ import java.awt.BorderLayout; import java.awt.Color; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; public class OptimizationUI extends javax.swing.JFrame { public OptimizationUI() { initComponents(); setLocationRelativeTo(null); jPanel3.setVisible(false); jPanel5.setVisible(false); jTabbedPane1.removeTabAt(1); jTabbedPane1.removeTabAt(1); // System.out.println((int)'0'); return; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel2 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); rst1 = new javax.swing.JTextArea(); jPanel5 = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Traditional Arabic", 1, 22)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Optimization Solution Using Simplex Method"); jButton2.setFont(new java.awt.Font("Traditional Arabic", 1, 14)); // NOI18N jButton2.setText("Click to Test Simplex"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); rst1.setEditable(false); rst1.setBackground(new java.awt.Color(0, 0, 51)); rst1.setColumns(20); rst1.setForeground(new java.awt.Color(255, 255, 255)); rst1.setRows(5); jScrollPane2.setViewportView(rst1); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 761, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Solution Progress", jPanel2); jPanel6.setBackground(new java.awt.Color(204, 204, 255)); jPanel6.setLayout(new java.awt.BorderLayout()); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 761, Short.MAX_VALUE) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap())) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 394, Short.MAX_VALUE) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE) .addContainerGap())) ); jTabbedPane1.addTab("Graph Evaluator", jPanel5); jPanel4.setBackground(new java.awt.Color(204, 204, 255)); jPanel4.setLayout(new java.awt.BorderLayout()); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 761, Short.MAX_VALUE) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap())) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 394, Short.MAX_VALUE) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE) .addContainerGap())) ); jTabbedPane1.addTab("Result Chart Evaluator", jPanel3); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 341, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(215, 215, 215)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 734, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jTabbedPane1) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTabbedPane1) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents Double[][] assSlack(Integer eqn){ Double sla[][]=new Double[eqn][eqn]; String hi=""; for (int i = 0; i < sla.length; i++) { String jay=""; if (hi.contains(i+"")){ continue;} for (int j = 0; j < sla[0].length; j++) { if (hi.contains(j+"")){ sla[i][j]=0.0;continue;} if (jay.contains(j+"")||hi.contains(i+"")){ break;} sla[i][j]=1.0; jay+=j+""; hi+=i+""; // System.out.println(i+"$"+j+" "+sla[i][j]); } } for (int i = 0; i < sla.length; i++) { for (int j = 0; j < sla[0].length; j++) { if (sla[i][j]==null) { sla[i][j]=0.0; } } } return sla; } Integer getMax(String []simp,Integer max){ for (int i = 0; i < simp.length; i++) { String ops[]=new String[2]; if(i==0){ ops[0]=simp[i].split("=")[1].replace("+", "%"); ops[1]="0"; String op[]=ops[0].split("%"); max=maxi(max, op.length); continue; } if (simp[i].contains("<=")) { ops[0]=simp[i].split("<=")[0].replace("+", "%"); ops[1]=simp[i].split("<=")[1]; String op[]=ops[0].split("%"); max=maxi(max, op.length); continue; }if (simp[i].contains("<")) { ops[0]=simp[i].split("<")[0].replace("+", "%"); ops[1]=simp[i].split("<")[1]; String op[]=ops[0].split("%"); max=maxi(max, op.length); continue; } } return max; } String[] getParams(String [] simp){ for (int i = 0; i < simp.length; i++) { if(i==0){ simp[i]=input("Enter Equation for Problem Objective:", "Request", qm); rst1.append("\tObjective: "+simp[i]+"\t\n\tConstraints:"); continue; } simp[i]=input("Enter Equation for Problem Constraint "+i+":", "Request", qm).trim(); rst1.append("\n\t\t"+simp[i]+"\n"); } return simp; } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed System.out.println(""); Integer eqn=Integer.parseInt(input("Enter Number Of Constraints:", "Request", qm)); String simp[]=new String[eqn+1]; Double[][]Vrow=new Double[eqn+1][];Double slaks[][]=assSlack(eqn),sq[]=new Double[eqn],rt[]=new Double[eqn+1],obsl[]=new Double[eqn]; for (int i = 0; i < obsl.length; i++) { obsl[i]=0.0; }rst1.setText("\t\t-----------------\tOptimization Solution\t----------------\n"); Integer c=0; simp=getParams(simp); /////////////////////////////////////////// Integer max=0; max=getMax(simp,max); Vrow=new Double[eqn+1][max+1]; // System.out.println("Max="+max+" "+simp[0]); for (int i = 0; i < simp.length; i++) { String ops[]=new String[2]; if(i==0){ ops[0]=simp[i].split("=")[1].replace("+", "%"); ops[1]="0"; String op[]=ops[0].split("%"); if (Vrow[0].length>op.length+1) { for (int j = 0; j < op.length; j++) { String mm=""; for (int k = 0; k < op[j].length(); k++) { mm+=((((int)op[j].charAt(k))>=48)&&(((int)op[j].charAt(k))<=57)||(op[j].charAt(k)=='-'))?op[j].charAt(k)+"":""; } Vrow[i][j] = Double.parseDouble(mm)*-1.0; } for (int j = op.length; j < Vrow[0].length-1; j++) { Vrow[i][j] = 0.0; } }else{ for (int j = 0; j < op.length; j++) { String mm=""; for (int k = 0; k < op[j].length(); k++) { mm+=((((int)op[j].charAt(k))>=48)&&(((int)op[j].charAt(k))<=57)||(op[j].charAt(k)=='-'))?op[j].charAt(k)+"":""; } Vrow[i][j] = Double.parseDouble(mm)*-1.0; } } Vrow[i][Vrow[0].length-1]=0.0; continue; } if (simp[i].contains("<=")) { ops[0]=simp[i].split("<=")[0].replace("+", "%"); ops[1]=simp[i].split("<=")[1]; String op[]=ops[0].split("%"); if (Vrow[0].length>op.length+1) { for (int j = 0; j < op.length; j++) { String mm=""; for (int k = 0; k < op[j].length(); k++) { mm+=((((int)op[j].charAt(k))>=48)&&(((int)op[j].charAt(k))<=57)||(op[j].charAt(k)=='-'))?op[j].charAt(k)+"":""; } Vrow[i][j] = Double.parseDouble(mm); } for (int j = op.length; j < Vrow[0].length-1; j++) { Vrow[i][j] = 0.0; } }else{ for (int j = 0; j < op.length; j++) { String mm=""; for (int k = 0; k < op[j].length(); k++) { mm+=((((int)op[j].charAt(k))>=48)&&(((int)op[j].charAt(k))<=57)||(op[j].charAt(k)=='-'))?op[j].charAt(k)+"":""; } Vrow[i][j] = Double.parseDouble(mm); } } Vrow[i][Vrow[0].length-1]=Double.parseDouble(ops[1]); continue; }if (simp[i].contains("<")) { ops[0]=simp[i].split("<")[0].replace("+", "%"); ops[1]=simp[i].split("<")[1]; String op[]=ops[0].split("%"); if (Vrow[0].length>op.length+1) { for (int j = 0; j < op.length; j++) { String mm=""; for (int k = 0; k < op[j].length(); k++) { mm+=((((int)op[j].charAt(k))>=48)&&(((int)op[j].charAt(k))<=57)||(op[j].charAt(k)=='-'))?op[j].charAt(k)+"":""; } Vrow[i][j] = Double.parseDouble(mm); } for (int j = op.length; j < Vrow[0].length-1; j++) { Vrow[i][j] = 0.0; } }else{ for (int j = 0; j < op.length; j++) { String mm=""; for (int k = 0; k < op[j].length(); k++) { mm+=((((int)op[j].charAt(k))>=48)&&(((int)op[j].charAt(k))<=57)||(op[j].charAt(k)=='-'))?op[j].charAt(k)+"":""; } Vrow[i][j] = Double.parseDouble(mm); } } Vrow[i][Vrow[0].length-1]=Double.parseDouble(ops[1]); } }rst1.append("\n"); //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// Integer tblc=1;Double newVrow[][]=Vrow;String myopt;westr=""; ///////////////////////////////////////////////////////////////////////////////// Integer pc,pr;Double pe,pch=0.0; pc=getPivotC(newVrow); ///////////////////////////////////////////////////////////////////////////////// generateRatios(rt,newVrow,pc); pr=getPivotR(rt); if (pr==0) { rst1.append("This Problem is Slready an Optimized Problem\n"); return; } westr+=(""+pc+"%"+pr+"-"); pe=newVrow[pr][pc]; ///////////////////////////////////////////////////////////////////////////////// displayTable( newVrow,obsl,slaks,rt); ///////////////////////////////////////////////////////////////////////////////// showPivots(pr,pc,pe,newVrow); myopt=checkOptimalty(newVrow); // int mm=1; // if (mm==1) { // return; // } ///////////////////////////////////////////////////////////////////////////////// XYSeriesCollection dataset= new XYSeriesCollection(); XYSeries series1[]; rst1.append("\n"); while (myopt.equalsIgnoreCase("not optimal")) { // System.out.println("------------------------------"); // for (int i = 0; i < rt.length; i++) { // System.out.println(" Please We Need PrVal= "+rt[i]); // // } // System.out.println("------------------------------"); tblc++; rst1.append("\n\t-----Solution is not Optimal----- \n\t New Tableaux "+tblc+"\n"); Double pivCon[]=new Double[newVrow.length]; for (int i = 0; i < newVrow.length; i++) { if (i==pr) { newVrow[i][pc]=pivCon[i]=newVrow[i][pc]/pe; continue; } pivCon[i]=newVrow[i][pc]; newVrow[i][pc]=pivCon[i]-newVrow[i][pc]; } // System.out.println("slacks time "+slaks.length); for (int k = 0; k < slaks.length; k++) { slaks[k][pr-1]=slaks[k][pr-1]/pe; // System.out.println(slaks[k][pr-1]+" jj "); } for (int i = 0; i < newVrow.length; i++) { for (int j = 0; j < newVrow[0].length; j++) { if (j==pc) { continue; } if (i==pr) { newVrow[i][j]=newVrow[i][j]/pe; } } } for (int k = -1; k < slaks.length; k++) { for (int i = 0; i < slaks[0].length; i++) { if (k==-1) { obsl[i]=obsl[i]-(pivCon[k+1]*slaks[pr-1][i]); continue; } if (k+1==(pr)) { continue; } slaks[k][i]=slaks[k][i]-(pivCon[k+1]*slaks[pr-1][i]); // System.out.println("\n\t"+slaks[k][i]+" pp "+slaks[pr-1][i]); } } for (int i = 0; i < newVrow.length; i++) { for (int j = 0; j < newVrow[0].length; j++) { if (j==pc) { continue; } if (i==pr) { continue; } // System.out.println(pivCon[i]+" zzz "+newVrow[pr][j]+" fff "+newVrow[i][j]+" bbb "+j+" vvv "+i); newVrow[i][j]=newVrow[i][j]-(pivCon[i]*newVrow[pr][j]); } } pch=0.0; pc=getPivotC(newVrow); ////////////////////////////////////////////////////////////////////////////////////////// generateRatios(rt,newVrow,pc); pr=getPivotR(rt); if (pr==0) { break; } pe=newVrow[pr][pc]; ///////////////////////////////////////////////////////////////////////////// displayTable( newVrow,obsl,slaks,rt); ///////////////////////////////////////////////////////////////////////////////// myopt=checkOptimalty(newVrow); if (myopt.equalsIgnoreCase("optimal")) { break; } showPivots(pr,pc,pe,newVrow); ///////////////////////////////////////////////////////////////////////////////// rst1.append("\n"); // if (tblc>4) { // break; // } westr+=(""+pc+"%"+pr+"-"); } rst1.append("\n\t-----Solution is Optimal At-----\n"); String ops1=simp[0].split("=")[1].replace("+", "%"); String op1[]=ops1.split("%"); String weatra[]=westr.split("-"),wea=""; for (int i = 0; i < (op1.length); i++) { wea+=op1[i].charAt(op1[i].length()-1); } for (int i = -1; i < (op1.length); i++) { if (i==-1) { rst1.append("\n\t\tP Max="+newVrow[0][newVrow[0].length-1]+"\n "); continue; } int w=Integer.parseInt(weatra[i].split("%")[0]),v=Integer.parseInt(weatra[i].split("%")[1]); rst1.append("\t\t"+wea.charAt(w)+"="+newVrow[v][newVrow.length-1]+"\n "); } String chartTitle = "Optimisation Graph"; String xAxisLabel = "X"; String yAxisLabel = "Y"; JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, xAxisLabel, yAxisLabel, dataset); ChartPanel chp = new ChartPanel(chart); jPanel6.removeAll(); jPanel6.add(chp, BorderLayout.CENTER); jPanel6.validate(); }//GEN-LAST:event_jButton2ActionPerformed String westr; Integer maxi(Integer m1,Integer m2){ return (m1>m2)?m1:m2; } Double mini(Double m1,Double m2){ return (m1<m2)?m1:m2; } Integer getPivotC(Double[][] Vrow){ Integer pc=0;Double pch=0.0; for (int i = 0; i < Vrow[0].length-1; i++) { if (i==0) { pch=Vrow[0][i];pc=i; } if (pch<=Vrow[0][i]) { pch=pch+0.0; }else{ pch=Vrow[0][i];pc=i; } } return pc; } Integer getPivotR(Double[] Vrow){ Integer pr=0;Double pch=-0.0; for (int i = 1; i < Vrow.length; i++) { System.out.println(" Please We Need PrVal= "+Vrow[i]); if(Vrow[i]<0.0){ pr=pr+0; pch=pch*1.0; continue; } if (i==1) { pch=Vrow[i];pr=i; } if (pch<=Vrow[i]) { if (pch==-0.0) { pch=Vrow[Vrow.length-1]; pr=Vrow.length-1; continue; } pch=pch+0.0; }else{ pch=Vrow[i];pr=i; } } return pr; } void generateRatios(Double rt[],Double Vrow[][],Integer pc){ for (int i = 0; i < Vrow.length; i++) { if (Vrow[i][pc]==0.0) { rt[i]= Vrow[i][Vrow[0].length-1]; continue; } rt[i]=Vrow[i][Vrow[0].length-1]/Vrow[i][pc]; } } void displayTable(Double Vrow[][],Double obsl[],Double slaks[][],Double rt[]){ for (int i = -1; i < Vrow.length; i++) { for (int j = -1; j < Vrow[0].length; j++) { if (j==-1&&i==-1) { rst1.append("\t"); continue; } if (j==-1) { rst1.append("\tL"+(i+1)); continue; } if (i==-1) { if(j==Vrow[0].length-1){ rst1.append("\tSQ\tRatio"); continue; }else{ rst1.append("\tX"+(j+1)); } if (j==Vrow[0].length-2) { int s=1; for (int k = 0; k < obsl.length; k++) { rst1.append("\t S"+s); s++; } continue; } continue; } if(j==Vrow[0].length-1){ rst1.append("\t"+Vrow[i][j]+"\t"+String.format("%.2f",rt[i])); }else{ rst1.append("\t"+String.format("%.2f",Vrow[i][j])); } if (j==Vrow[0].length-2&&i==0) { for (int k = 0; k < obsl.length; k++) { rst1.append("\t"+String.format("%.2f",obsl[k])); } continue; } if (j==Vrow[0].length-2&&i>0) { for (int k = 0; k < slaks[0].length; k++) { rst1.append("\t"+String.format("%.2f",slaks[i-1][k])); } } } rst1.append("\n"); } } void showPivots(Integer pr, Integer pc,Double pe, Double Vrow[][]){ rst1.append("\n\tPivot Col:"+pc); rst1.append("\n\tPivot Row:"+pr); rst1.append("\n\tPivot Element:"+String.format("%.2f",pe)); } Boolean f = false, t = true; javax.swing.JOptionPane jp = new javax.swing.JOptionPane(); Integer yes = jp.YES_OPTION, no = jp.NO_OPTION, im = jp.INFORMATION_MESSAGE, wm = jp.WARNING_MESSAGE, qm = jp.QUESTION_MESSAGE, dec = jp.YES_NO_OPTION, okC = jp.OK_CANCEL_OPTION, em = jp.ERROR_MESSAGE; private String checkOptimalty(Double[][] Vrow){ String optimal="optimal"; for (int i = 0; i < Vrow[0].length-1; i++) { if (Vrow[0][i]<0.0) { System.out.println("\n Solution is not optimal"); optimal="not optimal"; } } return optimal; } private Integer confirm(String message, String title, Integer ic) { return jp.showConfirmDialog(null, message, title, dec, ic); } private void message(String message, String title, Integer ic) { jp.showMessageDialog(null, message, title, ic); } private String input(String message, String title, Integer ic) { return jp.showInputDialog(null, message, title, ic); } public void empty(javax.swing.JTextField obj) { obj.setText(null); } public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(OptimizationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(OptimizationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(OptimizationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(OptimizationUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new OptimizationUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTextArea rst1; // End of variables declaration//GEN-END:variables }
package angel.v.devil; import static android.opengl.GLES10.*; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLSurfaceView; import android.opengl.GLU; import android.opengl.GLUtils; import android.os.SystemClock; public class MazeRenderer implements GLSurfaceView.Renderer{ int ts; float angelx,angely; angelVdevilActivity parent; Tile[][] myMaze; int maze_width,maze_height; Key key; Hammer hammer; Door door; ModelObj glDevil,glRobe,glHalo,glWings,glEyes,glHead,glYEyes; void render_item(int x,int y,int i,GL10 gl) { float xf,yf,zf; xf=((float) x)/10f; yf=((float) y)/10f; zf=0; if (myMaze[x][y].floordirection>0) zf-=0.05; if (myMaze[x][y].floordirection==5) zf-=0.05; if (i==1) { Star star=new Star (xf,yf+0.05f,zf+0.1f,xf+0.1f,yf+0.05f,zf); star.draw(gl); } if (i==2) { set_glcolor_mode(gl); key.x=xf+0.05f; key.y=yf+0.05f; key.z=zf+0.05f; key.draw(gl); set_glplain_mode(gl); } if (i==3) { set_glcolor_mode(gl); set_glplain_mode(gl); hammer.x=xf+0.05f; hammer.y=yf+0.05f; hammer.z=zf+0.05f; gl.glColor4f(1f,0f,0f,1f); hammer.draw(gl); set_glplain_mode(gl); } if (i==4) { set_glcolor_mode(gl); door.x=xf+0.05f+(parent.dooropen?0.04f:0); door.y=yf+0.05f; door.z=zf+0.05f; door.angle=parent.dooropen?-45:0; door.draw(gl); set_glplain_mode(gl); } } void copyMaze() { int f; myMaze=parent.myMaze; ts=countWalls(); mWall=new Wall[ts]; mFloor=new Floor[maze_width*maze_height]; f=0; int x,y; for (y=0;y<maze_height;y++) for (x=0;x<maze_width;x++) { float xf,yf; xf=((float) x)/10f; yf=((float) y)/10f; parent.set_floor_raisers(myMaze[x][y].floordirection); float p1,p2,p3,p4; p1=0.f;p2=0.f;p3=0.f;p4=0.f; if (myMaze[x][y].floordirection==5) {p1=-0.1f;p2=-0.1f;p3=-0.1f;p4=-0.1f;} if (myMaze[x][y].floordirection==Tile.directions.NORTH.i) {p1=-0.1f;p2=-0.1f;p3=-0.f;p4=-0.f;} if (myMaze[x][y].floordirection==Tile.directions.SOUTH.i) {p1=-0.f;p2=-0.f;p3=-0.1f;p4=-0.1f;} if (myMaze[x][y].floordirection==Tile.directions.EAST.i) {p1=-0.f;p2=-0.1f;p3=-0.1f;p4=-0.f;} if (myMaze[x][y].floordirection==Tile.directions.WEST.i) {p1=-0.1f;p2=-0.f;p3=-0.f;p4=-0.1f;} mFloor[y*maze_width+x]=new Floor(xf,yf,.1f,xf+.1f,yf+.1f,.01f,myMaze[x][y].color,p1,p2,p3,p4); if (myMaze[x][y].NorthDown) { mWall[f]=new Wall(xf,yf,0f,xf+0.1f,yf+0.01f,0.1f,0,0,0,0); f++; } if (myMaze[x][y].SouthDown) { mWall[f]=new Wall(xf,yf+.09f,0,xf+.1f,yf+.1f,0.1f,0,0,0,0); f++; } if (myMaze[x][y].EastDown) { mWall[f]=new Wall(xf+.09f,yf,0,xf+.1f,yf+.1f,.1f,0,0,0,0); f++; } if (myMaze[x][y].WestDown) { mWall[f]=new Wall(xf,yf,0,xf+0.01f,yf+.1f,.1f,0,0,0,0); f++; } if (myMaze[x][y].NorthUp) { mWall[f]=new Wall(xf,yf,0f,xf+0.1f,yf+0.01f,0.11f,p1,p2,p3,p4); f++; } if (myMaze[x][y].SouthUp) { mWall[f]=new Wall(xf,yf+.09f,0f,xf+.1f,yf+.1f,0.11f,p1,p2,p3,p4); f++; } if (myMaze[x][y].EastUp) { mWall[f]=new Wall(xf+.09f,yf,0f,xf+.1f,yf+.1f,0.11f,p1,p2,p3,p4); f++; } if (myMaze[x][y].WestUp) { mWall[f]=new Wall(xf,yf,0f,xf+0.01f,yf+.1f,0.11f,p1,p2,p3,p4); f++; } } } public MazeRenderer(angelVdevilActivity context) { parent=context; mContext = context; copyMaze(); glDevil=new ModelObj(context,"devil.obj",8f,0.5f,0f,0f,0f,0f); glHalo=new ModelObj(context,"halo.obj",8f,1f,1f,0f,0f,0f); glWings=new ModelObj(context,"wings.obj",8f,1f,1f,0f,0f,0f); glRobe=new ModelObj(context,"robe.obj",8f,1f,0f,1f,0f,0f); glEyes=new ModelObj(context,"eyes.obj",8f,1f,1f,1f,0f,0f); glYEyes=new ModelObj(context,"eyes.obj",8f,1f,1f,0f,0f,0f); glHead=new ModelObj(context,"head.obj",8f,1f,0.8f,0.8f,0f,0f); key=new Key(); hammer=new Hammer(); door=new Door(); } private int countWalls() { int x,y; int t; maze_height=parent.maze_height; maze_width=parent.maze_width; t=0; for (y=0;y<maze_height;y++) for (x=0;x<maze_width;x++) { if (myMaze[x][y].NorthDown) t++; if (myMaze[x][y].SouthDown) t++; if (myMaze[x][y].EastDown) t++; if (myMaze[x][y].WestDown) t++; if (myMaze[x][y].NorthUp) t++; if (myMaze[x][y].SouthUp) t++; if (myMaze[x][y].EastUp) t++; if (myMaze[x][y].WestUp) t++; } return t; } public void onSurfaceCreated(GL10 gl, EGLConfig config) { glDisable(GL_DITHER); glHint(GL_PERSPECTIVE_CORRECTION_HINT,GL_FASTEST); glClearColor(0f, 0.85f, 0.85f, 0f); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); int[] textures = new int[2]; glGenTextures(2, textures, 0); mTextureIDfloor = textures[0]; mTextureIDwall = textures[1]; glBindTexture(GL_TEXTURE_2D, mTextureIDfloor); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_REPLACE); glBindTexture(GL_TEXTURE_2D, mTextureIDwall); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_NEAREST); InputStream is1 = mContext.getResources().openRawResource(R.drawable.floor); InputStream is2 = mContext.getResources().openRawResource(R.drawable.wall); Bitmap bitmap1,bitmap2; try { bitmap1 = BitmapFactory.decodeStream(is1); bitmap2 = BitmapFactory.decodeStream(is2); } finally { try { is1.close(); is2.close(); } catch(IOException e) { // Ignore. } } gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); GLUtils.texImage2D(GL_TEXTURE_2D, 0, bitmap1, 0); gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[1]); GLUtils.texImage2D(GL_TEXTURE_2D, 0, bitmap2, 0); bitmap1.recycle(); bitmap2.recycle(); } public void onDrawFrame(GL10 gl) { glDisable(GL_DITHER); glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_MODULATE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, mTextureIDfloor); glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glBindTexture(GL_TEXTURE_2D, mTextureIDwall); glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); float angelx=parent.angel.x; float angely=parent.angel.y; float angelz=parent.angel.z; float devilx=parent.devil.x; float devily=parent.devil.y; float devilz=parent.devil.z; gl.glPushMatrix(); set_glplain_mode(gl); // commenting out this creates randomly a nice gold letters effect gl.glScalef(0.1f, 0.1f, 0.1f); gl.glTranslatef(-4f, 0, -20f); gl.glRotatef(90f,0,0,1); gl.glRotatef(1f,1f,0,0); gl.glDisable(GL_CULL_FACE); gl.glTranslatef(2f, 0, 0f); Letter mL=new Letter(parent.score); Letter mT=new Letter((int) (parent.timeleft/1000)); Letter mLvl=new Letter(parent.level,parent); gl.glColor4f(0,.8f,1,1); Letter.drawtriangle(gl, 0, 0, 0.1f, 2, 7f, 0.1f, 0, 7.5f, 0.1f); Letter.drawtriangle(gl, 0, 0, 0.1f, 2, 7f, 0.1f, 2, 0, 0.1f); mL.draw(gl); Letter.line_width=1; gl.glColor4f(0,0,1,1); Letter.drawtriangle(gl, 0, 8, 0.1f, 1, 9, 0.1f, 2, 8, 0.1f); Letter.drawtriangle(gl, 0, 8, 0.1f, 1, 7, 0.1f, 2, 8, 0.1f); gl.glColor4f(1,1,0,1); mL.moveto(7.75f, 1); mL.draw_star(gl); glTranslatef(3,0,0); gl.glColor4f(0,.8f,1,1); gl.glColor4f(0,0,1,1); Letter.drawtriangle(gl, 0, 0, 0.1f, 2, 7f, 0.1f, 0, 7.5f, 0.1f); Letter.drawtriangle(gl, 0, 0, 0.1f, 2, 7f, 0.1f, 2, 0, 0.1f); mT.draw(gl); Letter.line_width=1; gl.glColor4f(0,.8f,1,1); Letter.drawtriangle(gl, 0, 8, 0.1f, 1, 9, 0.1f, 2, 8, 0.1f); Letter.drawtriangle(gl, 0, 8, 0.1f, 1, 7, 0.1f, 2, 8, 0.1f); gl.glColor4f(1,0,1,1); mT.moveto(8, 1); mT.draw_clock(gl); glTranslatef(-6,0,0); gl.glColor4f(0,.8f,1,1); Letter.drawtriangle(gl, 0, 0, 0.1f, 2, 10f, 0.1f, 0, 9.5f, 0.1f); Letter.drawtriangle(gl, 0, 0, 0.1f, 2, 10f, 0.1f, 2, 0, 0.1f); mLvl.moveto(3.5f, 0); mLvl.draw(gl,4); Letter.line_width=7; gl.glColor4f(0,0,1,1); mLvl.moveto(7.75f, 1); gl.glColor4f(1,0,0,0); mLvl.moveto(1.5f, 0); mLvl.drawtext(gl,"Lvl:".toCharArray()); gl.glColor4f(1,1,1,1); Letter.line_width=1; gl.glPopMatrix(); set_glcolor_mode(gl); set_glplain_mode(gl); if (parent.havehammer) { hammer.x=hammer.y=hammer.z=0; gl.glPushMatrix(); gl.glRotatef(180f, 1, 0, 0); gl.glTranslatef(-0.3f, 0, 0); hammer.draw(gl); gl.glPopMatrix(); } if (parent.havekey) { key.x=key.y=key.z=0; gl.glPushMatrix(); gl.glRotatef(180f, 1, 0, 0); gl.glTranslatef(-0.3f, -0.2f, 0f); key.draw(gl); gl.glPopMatrix(); } set_gl_texture_mode(gl); glRotatef(35f,1f,0,0); if (parent.third_person) { if (!parent.network || !parent.network_devil) glRotatef(180-glRobe.tangle,0,0,1); // use this to make it third person else glRotatef(180-glDevil.tangle,0,0,1); } float centerx,centery; centerx=angelx/10.0f; centery=angely/10.0f; if (parent.network && parent.network_devil) { centerx=devilx/10.0f; centery=devily/10.0f; } centerx/=(float) (parent.tile_width); centery/=(float) (parent.tile_height); glScalef(3.0f,3.0f,3.0f); if (parent.third_person) glScalef(2.0f,2.0f,2.0f); glTranslatef(centerx*2,centery*2,0.3f); glRotatef(180f,0,0,1f); glBindTexture(GL_TEXTURE_2D, mTextureIDwall); int f; gl.glColor4f(1,1,1,1f); for (f=0;f<ts;f++) mWall[f].draw(gl); glBindTexture(GL_TEXTURE_2D, mTextureIDfloor); for (f=0;f<maze_width*maze_height;f++) mFloor[f].draw(gl); set_glplain_mode(gl); int x,y; for (y=0;y<maze_height;y++) for (x=0;x<maze_width;x++) if (myMaze[x][y].item>0) { render_item(x,y,myMaze[x][y].item,gl); } { float xf,yf,zf; xf=(angelx/(float)parent.tile_width)/10f; yf=(angely/(float) parent.tile_height)/10f; zf=0; if (angelz!=0) { int tile_x,tile_y; tile_x=(int) (angelx)/parent.tile_width; tile_y=(int) (angely)/parent.tile_height; if (tile_x<0) tile_x=0; if (tile_y<0) tile_y=0; if (tile_x>maze_width-1) tile_x=maze_width-1; if (tile_y>maze_height-1) tile_y=maze_height-1; if (myMaze[tile_x][tile_y].floordirection==Tile.directions.BRIDGE.i) zf=-0.1f; if (myMaze[tile_x][tile_y].floordirection==Tile.directions.SOUTH.i) zf=-0.1f/(float)(parent.tile_height)*(angely-(tile_y*parent.tile_height)); if (myMaze[tile_x][tile_y].floordirection==Tile.directions.NORTH.i) zf=-0.1f/(float)(parent.tile_height)*(1-angely+(tile_y*parent.tile_height)); if (myMaze[tile_x][tile_y].floordirection==Tile.directions.EAST.i) zf=-0.1f/(float)(parent.tile_width)*(angelx-(tile_x*parent.tile_width)); if (myMaze[tile_x][tile_y].floordirection==Tile.directions.WEST.i) zf=-0.1f/(float)(parent.tile_width)*(1-angelx+(tile_x*parent.tile_width)); } else {zf=0.05f;} glRobe.x_translate=xf+0.05f; glRobe.y_translate=yf+0.05f; glRobe.z_translate=zf; if (parent.havekey) { key.x=xf+0.05f; key.y=yf+0.05f; key.z=zf; gl.glPushMatrix(); gl.glTranslatef(2*key.x, 2*key.y, -0.01f+2*key.z); gl.glRotatef(glRobe.tangle,0,0,1); gl.glRotatef(90f,1, 0, 0); gl.glRotatef(-60f,0, 1, 0); gl.glTranslatef(-2*key.x-0.1f, -2*key.y, -2*key.z); key.draw(gl); gl.glPopMatrix(); } if (parent.havehammer) { hammer.x=xf+0.05f; hammer.y=yf+0.05f; hammer.z=zf; gl.glPushMatrix(); gl.glTranslatef(2*hammer.x, 2*hammer.y, -0.01f+2*hammer.z); gl.glRotatef(glRobe.tangle,0,0,1); gl.glRotatef(90f,1, 0, 0); gl.glRotatef(60f,0, 1, 0); gl.glTranslatef(-2*hammer.x+0.1f, -2*hammer.y, -2*hammer.z); hammer.draw(gl); gl.glPopMatrix(); } glRobe.setdirection(1+((4-parent.playerDir)%4)); glHalo.x_translate=xf+0.05f; glHalo.y_translate=yf+0.05f; glHalo.z_translate=zf; glWings.x_translate=xf+0.05f; glWings.y_translate=yf+0.05f; glWings.z_translate=zf; glEyes.x_translate=xf+0.05f; glEyes.y_translate=yf+0.05f; glEyes.z_translate=zf; glEyes.setdirection(1+((4-parent.playerDir)%4)); glWings.setdirection(1+((4-parent.playerDir)%4)); glEyes.angle=glRobe.tangle; glWings.angle=glRobe.tangle; glEyes.sync_angle(); glWings.sync_angle(); glHead.x_translate=xf+0.05f; glHead.y_translate=yf+0.05f; glHead.z_translate=zf; } { float xf,yf,zf; xf=(devilx/(float)parent.tile_width)/10f; yf=(devily/(float) parent.tile_height)/10f; zf=0; if (devilz!=0) { int tile_x,tile_y; tile_x=(int) (devilx)/parent.tile_width; tile_y=(int) (devily)/parent.tile_height; if (tile_x<0) tile_x=0; if (tile_y<0) tile_y=0; if (tile_x>maze_width-1) tile_x=maze_width-1; if (tile_y>maze_height-1) tile_y=maze_height-1; if (myMaze[tile_x][tile_y].floordirection==Tile.directions.BRIDGE.i) zf=-0.1f; if (myMaze[tile_x][tile_y].floordirection==Tile.directions.SOUTH.i) zf=-0.1f/(float)(parent.tile_height)*(devily-(tile_y*parent.tile_height)); if (myMaze[tile_x][tile_y].floordirection==Tile.directions.NORTH.i) zf=-0.1f/(float)(parent.tile_height)*(1-devily+(tile_y*parent.tile_height)); if (myMaze[tile_x][tile_y].floordirection==Tile.directions.EAST.i) zf=-0.1f/(float)(parent.tile_width)*(devilx-(tile_x*parent.tile_width)); if (myMaze[tile_x][tile_y].floordirection==Tile.directions.WEST.i) zf=-0.1f/(float)(parent.tile_width)*(1-devilx+(tile_x*parent.tile_width)); } else {zf=0.05f;} glDevil.x_translate=xf+0.05f; glDevil.y_translate=yf+0.05f; glDevil.z_translate=zf; if (parent.devildizzy>0) { hammer.x=xf+0.05f; hammer.y=yf+0.05f; hammer.z=zf; gl.glPushMatrix(); gl.glTranslatef(2*hammer.x, 2*hammer.y, -0.01f+2*hammer.z); gl.glRotatef(glDevil.tangle,0,0,1); gl.glRotatef(90f,1, 0, 0); gl.glRotatef(60f,0, 1, 0); gl.glTranslatef(-2*hammer.x+0.1f, -2*hammer.y, -2*hammer.z); hammer.draw(gl); gl.glPopMatrix(); } } glBindTexture(GL_TEXTURE_2D, mTextureIDfloor); set_glcolor_mode(gl); glRobe.draw(gl); glHalo.draw(gl); glWings.draw(gl); glEyes.draw(gl); glHead.draw(gl); glDevil.draw(gl); glDevil.setdirection(parent.devil_direction); glYEyes.x_translate=glDevil.x_translate; glYEyes.y_translate=glDevil.y_translate; glYEyes.z_translate=glDevil.z_translate; glYEyes.setdirection(parent.devil_direction); glYEyes.angle=glDevil.tangle; glYEyes.sync_angle(); glYEyes.draw(gl); } void set_glcolor_mode(GL10 gl) { gl.glDisableClientState(GL_TEXTURE_COORD_ARRAY); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); } void set_glplain_mode(GL10 gl) { gl.glDisableClientState(GL_TEXTURE_COORD_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } void set_gl_texture_mode(GL10 gl) { gl.glEnableClientState(GL_TEXTURE_COORD_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } public void onSurfaceChanged(GL10 gl, int w, int h) { glViewport(0, 0, w, h); float ratio = (float) w / h; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustumf(-ratio, ratio, -1, 1, 3, 17); // is this the limit of view? } private Context mContext; private Wall mWall[]; private Floor mFloor[]; private int mTextureIDfloor,mTextureIDwall; static class Floor { int color; public Floor(float x1,float y1,float z,float x2,float y2,float zw,int c,float p1,float p2,float p3,float p4) { color=c; ByteBuffer vbb = ByteBuffer.allocateDirect(36 * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(36 * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(36 * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); float coords[] = { x1, y1, z+p1, x2, y1, z+p2, x2, y2, z+p3, x1, y2, z+p4, x1, y1, z+zw+p1, x2, y1, z+zw+p2, x2, y2, z+zw+p3, x1, y2, z+zw+p4, }; for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(coords[i*3+j] * 2.0f); } } for (int i = 0; i < VERTS; i++) { mTexBuffer.put(coords[i*3] * 32f ); mTexBuffer.put(coords[i*3+1] * 32f ); } byte indices[] = { 0, 4, 5, 0, 5, 1, 1, 5, 6, 1, 6, 2, 2, 6, 7, 2, 7, 3, 3, 7, 4, 3, 4, 0, 4, 7, 6, 4, 6, 5, 3, 0, 1, 3, 1, 2 }; for(int i = 0; i < 36 ; i++) { mIndexBuffer.put((short) indices[i]); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { glDisable(GL_CULL_FACE); glVertexPointer(3, GL_FLOAT, 0, mFVertexBuffer); glEnable(GL_TEXTURE_2D); glTexCoordPointer(2, GL_FLOAT, 0, mTexBuffer); int r = (color >> 16) & 0xFF; int g = (color >> 8) & 0xFF; int b = (color >> 0) & 0xFF; float red=(float)r/256f; float green=(float)g/256f; float blue=(float)b/256f; gl.glColor4f(red, green, blue, 1f); glDrawElements(GL_TRIANGLE_STRIP, 36, GL_UNSIGNED_SHORT, mIndexBuffer); gl.glColor4f(1f, 1f, 1f, 1f); } private final static int VERTS = 8; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; } static class Wall { public Wall(float x1,float y1,float z,float x2,float y2,float zw,float p1,float p2,float p3,float p4) { ByteBuffer vbb = ByteBuffer.allocateDirect(36 * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(36 * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(36 * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); float coords[] = { x1, y1, z+p1, x2, y1, z+p2, x2, y2, z+p3, x1, y2, z+p4, x1, y1, z+zw+p1, x2, y1, z+zw+p2, x2, y2, z+zw+p3, x1, y2, z+zw+p4 }; for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(coords[i*3+j] * 2.0f); } } for (int i = 0; i < VERTS; i++) { mTexBuffer.put(coords[i*3] * 16f ); mTexBuffer.put(coords[i*3+2] * 16f ); } byte indices[] = { 0, 4, 5, 0, 5, 1, 1, 5, 6, 1, 6, 2, 2, 6, 7, 2, 7, 3, 3, 7, 4, 3, 4, 0, 4, 7, 6, 4, 6, 5, 3, 0, 1, 3, 1, 2 }; for(int i = 0; i < 36 ; i++) { mIndexBuffer.put((short) indices[i]); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { glDisable(GL_CULL_FACE); glVertexPointer(3, GL_FLOAT, 0, mFVertexBuffer); glEnable(GL_TEXTURE_2D); glTexCoordPointer(2, GL_FLOAT, 0, mTexBuffer); glDrawElements(GL_TRIANGLE_STRIP, 36, GL_UNSIGNED_SHORT, mIndexBuffer); } private final static int VERTS = 8; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; } static class Star { float x,y,z; public Star(float x1,float y1,float z1,float x2,float y2,float z2) { x=2*(x2+x1)/2; y=2*(y2+y1)/2; z=2*(z2+z1)/2; ByteBuffer vbb = ByteBuffer.allocateDirect(36 * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(36 * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(36 * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); float xb=(x1+x2)/2; float yb=(y1+y2)/2; float zb=(z1+z2)/2; long time = SystemClock.uptimeMillis() % 40000L; angle = 0.09f * ((int) time); float coords[] = new float [30]; int p=0; for (double a=0; a<Math.PI*2;a+=Math.PI*2/5) { coords[p] = (float) (xb + 0.01*Math.sin(a)); coords[p+1]= (float) (yb ); coords[p+2]= (float) (zb+ 0.01*Math.cos(a)); p+=3; coords[p] = (float) (xb + 0.03*Math.sin(a+Math.PI*2/10)); coords[p+1]= (float) (yb ); coords[p+2]= (float) (zb+ 0.03*Math.cos(a+Math.PI*2/10)); p+=3; }; for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(coords[i*3+j] * 2.0f); } } for(int i = 0; i < 5 ; i++) for(int j = 0; j < 3; j++){ mIndexBuffer.put((short) (i*2+j)); } mIndexBuffer.put(14,(short) 0); mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { glDisable(GL_CULL_FACE); glVertexPointer(3, GL_FLOAT, 0, mFVertexBuffer); glDisable(GL_TEXTURE_2D); gl.glColor4f(1f,1f,0f,1f); gl.glPushMatrix(); gl.glTranslatef(x, y, z); long time = SystemClock.uptimeMillis() % 40000L; angle = 0.09f * ((int) time); gl.glRotatef(angle, 0, 0, 1f); gl.glTranslatef(-x, -y, -z); glDrawElements(GL_TRIANGLES, 15, GL_UNSIGNED_SHORT, mIndexBuffer); gl.glColor4f(1f,1f,1f,1f); gl.glPopMatrix(); } private final static int VERTS = 10; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; float angle; } }
package com.tencent.mm.ak.a.b; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public final class b implements com.tencent.mm.ak.a.c.b { public final com.tencent.mm.ak.a.d.b mb(String str) { x.d("MicroMsg.imageload.DefaultImageDownloader", "[cpan] get image data from url:%s", new Object[]{str}); try { HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(str).openConnection(); httpURLConnection.setConnectTimeout(15000); httpURLConnection.setReadTimeout(20000); if (httpURLConnection == null) { x.i("MicroMsg.imageload.DefaultImageDownloader.HttpClientFactory", "open connection failed."); } if (httpURLConnection.getResponseCode() >= 300) { httpURLConnection.disconnect(); x.w("MicroMsg.imageload.DefaultImageDownloader.HttpClientFactory", "dz[httpURLConnectionGet 300]"); return null; } InputStream inputStream = httpURLConnection.getInputStream(); String contentType = httpURLConnection.getContentType(); byte[] m = e.m(inputStream); httpURLConnection.disconnect(); return new com.tencent.mm.ak.a.d.b(m, contentType); } catch (Throwable e) { x.e("MicroMsg.imageload.DefaultImageDownloader", "[cpan] get image data failed.:%s", new Object[]{bi.i(e)}); return new com.tencent.mm.ak.a.d.b(null, null); } catch (Throwable e2) { x.e("MicroMsg.imageload.DefaultImageDownloader", "[cpan] get image data failed.:%s", new Object[]{bi.i(e2)}); return new com.tencent.mm.ak.a.d.b(null, null); } catch (Throwable e22) { x.e("MicroMsg.imageload.DefaultImageDownloader", "[cpan] get image data failed.:%s", new Object[]{bi.i(e22)}); return new com.tencent.mm.ak.a.d.b(null, null); } catch (Throwable e222) { x.e("MicroMsg.imageload.DefaultImageDownloader", "[cpan] get image data failed.:%s", new Object[]{bi.i(e222)}); return new com.tencent.mm.ak.a.d.b(null, null); } catch (Throwable e2222) { x.e("MicroMsg.imageload.DefaultImageDownloader", "[cpan] get image data failed.:%s", new Object[]{bi.i(e2222)}); return new com.tencent.mm.ak.a.d.b(null, null); } catch (Throwable e22222) { x.e("MicroMsg.imageload.DefaultImageDownloader", "[cpan] get image data failed.:%s", new Object[]{bi.i(e22222)}); return new com.tencent.mm.ak.a.d.b(null, null); } catch (Throwable e222222) { x.e("MicroMsg.imageload.DefaultImageDownloader", "[cpan] get image data failed.:%s", new Object[]{bi.i(e222222)}); return new com.tencent.mm.ak.a.d.b(null, null); } } }
package Lab06.Zad2; public interface Deliver { void deliver(String stuff); }
package com.facebook.react.views.view; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.RippleDrawable; import android.os.Build; import android.util.TypedValue; import com.facebook.react.bridge.JSApplicationIllegalArgumentException; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.SoftAssertions; public class ReactDrawableHelper { private static final TypedValue sResolveOutValue = new TypedValue(); public static Drawable createDrawableFromJSDescription(Context paramContext, ReadableMap paramReadableMap) { String str1; String str2 = paramReadableMap.getString("type"); if ("ThemeAttrAndroid".equals(str2)) { str1 = paramReadableMap.getString("attribute"); SoftAssertions.assertNotNull(str1); int i = paramContext.getResources().getIdentifier(str1, "attr", "android"); if (i != 0) { if (paramContext.getTheme().resolveAttribute(i, sResolveOutValue, true)) return (Build.VERSION.SDK_INT >= 21) ? paramContext.getResources().getDrawable(sResolveOutValue.resourceId, paramContext.getTheme()) : paramContext.getResources().getDrawable(sResolveOutValue.resourceId); StringBuilder stringBuilder1 = new StringBuilder("Attribute "); stringBuilder1.append(str1); stringBuilder1.append(" couldn't be resolved into a drawable"); throw new JSApplicationIllegalArgumentException(stringBuilder1.toString()); } stringBuilder = new StringBuilder("Attribute "); stringBuilder.append(str1); stringBuilder.append(" couldn't be found in the resource list"); throw new JSApplicationIllegalArgumentException(stringBuilder.toString()); } if ("RippleAndroid".equals(str2)) { if (Build.VERSION.SDK_INT >= 21) { int i; if (str1.hasKey("color") && !str1.isNull("color")) { i = str1.getInt("color"); } else if (stringBuilder.getTheme().resolveAttribute(16843820, sResolveOutValue, true)) { i = stringBuilder.getResources().getColor(sResolveOutValue.resourceId); } else { throw new JSApplicationIllegalArgumentException("Attribute colorControlHighlight couldn't be resolved into a drawable"); } if (!str1.hasKey("borderless") || str1.isNull("borderless") || !str1.getBoolean("borderless")) { ColorDrawable colorDrawable = new ColorDrawable(-1); return (Drawable)new RippleDrawable(new ColorStateList(new int[][] { {} }, new int[] { i }), null, (Drawable)colorDrawable); } stringBuilder = null; return (Drawable)new RippleDrawable(new ColorStateList(new int[][] { {} }, new int[] { i }), null, (Drawable)stringBuilder); } throw new JSApplicationIllegalArgumentException("Ripple drawable is not available on android API <21"); } StringBuilder stringBuilder = new StringBuilder("Invalid type for android drawable: "); stringBuilder.append(str2); throw new JSApplicationIllegalArgumentException(stringBuilder.toString()); } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\views\view\ReactDrawableHelper.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package javax.vecmath; import java.io.Serializable; public class AxisAngle4f implements Serializable, Cloneable { static final long serialVersionUID = -163246355858070601L; public float x; public float y; public float z; public float angle; static final double EPS = 1.0E-6D; public AxisAngle4f(float x, float y, float z, float angle) { this.x = x; this.y = y; this.z = z; this.angle = angle; } public AxisAngle4f(float[] a) { this.x = a[0]; this.y = a[1]; this.z = a[2]; this.angle = a[3]; } public AxisAngle4f(AxisAngle4f a1) { this.x = a1.x; this.y = a1.y; this.z = a1.z; this.angle = a1.angle; } public AxisAngle4f(AxisAngle4d a1) { this.x = (float)a1.x; this.y = (float)a1.y; this.z = (float)a1.z; this.angle = (float)a1.angle; } public AxisAngle4f(Vector3f axis, float angle) { this.x = axis.x; this.y = axis.y; this.z = axis.z; this.angle = angle; } public AxisAngle4f() { this.x = 0.0F; this.y = 0.0F; this.z = 1.0F; this.angle = 0.0F; } public final void set(float x, float y, float z, float angle) { this.x = x; this.y = y; this.z = z; this.angle = angle; } public final void set(float[] a) { this.x = a[0]; this.y = a[1]; this.z = a[2]; this.angle = a[3]; } public final void set(AxisAngle4f a1) { this.x = a1.x; this.y = a1.y; this.z = a1.z; this.angle = a1.angle; } public final void set(AxisAngle4d a1) { this.x = (float)a1.x; this.y = (float)a1.y; this.z = (float)a1.z; this.angle = (float)a1.angle; } public final void set(Vector3f axis, float angle) { this.x = axis.x; this.y = axis.y; this.z = axis.z; this.angle = angle; } public final void get(float[] a) { a[0] = this.x; a[1] = this.y; a[2] = this.z; a[3] = this.angle; } public final void set(Quat4f q1) { double mag = (q1.x * q1.x + q1.y * q1.y + q1.z * q1.z); if (mag > 1.0E-6D) { mag = Math.sqrt(mag); double invMag = 1.0D / mag; this.x = (float)(q1.x * invMag); this.y = (float)(q1.y * invMag); this.z = (float)(q1.z * invMag); this.angle = (float)(2.0D * Math.atan2(mag, q1.w)); } else { this.x = 0.0F; this.y = 1.0F; this.z = 0.0F; this.angle = 0.0F; } } public final void set(Quat4d q1) { double mag = q1.x * q1.x + q1.y * q1.y + q1.z * q1.z; if (mag > 1.0E-6D) { mag = Math.sqrt(mag); double invMag = 1.0D / mag; this.x = (float)(q1.x * invMag); this.y = (float)(q1.y * invMag); this.z = (float)(q1.z * invMag); this.angle = (float)(2.0D * Math.atan2(mag, q1.w)); } else { this.x = 0.0F; this.y = 1.0F; this.z = 0.0F; this.angle = 0.0F; } } public final void set(Matrix4f m1) { Matrix3f m3f = new Matrix3f(); m1.get(m3f); this.x = m3f.m21 - m3f.m12; this.y = m3f.m02 - m3f.m20; this.z = m3f.m10 - m3f.m01; double mag = (this.x * this.x + this.y * this.y + this.z * this.z); if (mag > 1.0E-6D) { mag = Math.sqrt(mag); double sin = 0.5D * mag; double cos = 0.5D * ((m3f.m00 + m3f.m11 + m3f.m22) - 1.0D); this.angle = (float)Math.atan2(sin, cos); double invMag = 1.0D / mag; this.x = (float)(this.x * invMag); this.y = (float)(this.y * invMag); this.z = (float)(this.z * invMag); } else { this.x = 0.0F; this.y = 1.0F; this.z = 0.0F; this.angle = 0.0F; } } public final void set(Matrix4d m1) { Matrix3d m3d = new Matrix3d(); m1.get(m3d); this.x = (float)(m3d.m21 - m3d.m12); this.y = (float)(m3d.m02 - m3d.m20); this.z = (float)(m3d.m10 - m3d.m01); double mag = (this.x * this.x + this.y * this.y + this.z * this.z); if (mag > 1.0E-6D) { mag = Math.sqrt(mag); double sin = 0.5D * mag; double cos = 0.5D * (m3d.m00 + m3d.m11 + m3d.m22 - 1.0D); this.angle = (float)Math.atan2(sin, cos); double invMag = 1.0D / mag; this.x = (float)(this.x * invMag); this.y = (float)(this.y * invMag); this.z = (float)(this.z * invMag); } else { this.x = 0.0F; this.y = 1.0F; this.z = 0.0F; this.angle = 0.0F; } } public final void set(Matrix3f m1) { this.x = m1.m21 - m1.m12; this.y = m1.m02 - m1.m20; this.z = m1.m10 - m1.m01; double mag = (this.x * this.x + this.y * this.y + this.z * this.z); if (mag > 1.0E-6D) { mag = Math.sqrt(mag); double sin = 0.5D * mag; double cos = 0.5D * ((m1.m00 + m1.m11 + m1.m22) - 1.0D); this.angle = (float)Math.atan2(sin, cos); double invMag = 1.0D / mag; this.x = (float)(this.x * invMag); this.y = (float)(this.y * invMag); this.z = (float)(this.z * invMag); } else { this.x = 0.0F; this.y = 1.0F; this.z = 0.0F; this.angle = 0.0F; } } public final void set(Matrix3d m1) { this.x = (float)(m1.m21 - m1.m12); this.y = (float)(m1.m02 - m1.m20); this.z = (float)(m1.m10 - m1.m01); double mag = (this.x * this.x + this.y * this.y + this.z * this.z); if (mag > 1.0E-6D) { mag = Math.sqrt(mag); double sin = 0.5D * mag; double cos = 0.5D * (m1.m00 + m1.m11 + m1.m22 - 1.0D); this.angle = (float)Math.atan2(sin, cos); double invMag = 1.0D / mag; this.x = (float)(this.x * invMag); this.y = (float)(this.y * invMag); this.z = (float)(this.z * invMag); } else { this.x = 0.0F; this.y = 1.0F; this.z = 0.0F; this.angle = 0.0F; } } public String toString() { return "(" + this.x + ", " + this.y + ", " + this.z + ", " + this.angle + ")"; } public boolean equals(AxisAngle4f a1) { try { return (this.x == a1.x && this.y == a1.y && this.z == a1.z && this.angle == a1.angle); } catch (NullPointerException e2) { return false; } } public boolean equals(Object o1) { try { AxisAngle4f a2 = (AxisAngle4f)o1; return (this.x == a2.x && this.y == a2.y && this.z == a2.z && this.angle == a2.angle); } catch (NullPointerException e2) { return false; } catch (ClassCastException e1) { return false; } } public boolean epsilonEquals(AxisAngle4f a1, float epsilon) { float diff = this.x - a1.x; if (((diff < 0.0F) ? -diff : diff) > epsilon) return false; diff = this.y - a1.y; if (((diff < 0.0F) ? -diff : diff) > epsilon) return false; diff = this.z - a1.z; if (((diff < 0.0F) ? -diff : diff) > epsilon) return false; diff = this.angle - a1.angle; if (((diff < 0.0F) ? -diff : diff) > epsilon) return false; return true; } public int hashCode() { long bits = 1L; bits = VecMathUtil.hashFloatBits(bits, this.x); bits = VecMathUtil.hashFloatBits(bits, this.y); bits = VecMathUtil.hashFloatBits(bits, this.z); bits = VecMathUtil.hashFloatBits(bits, this.angle); return VecMathUtil.hashFinish(bits); } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } public final float getAngle() { return this.angle; } public final void setAngle(float angle) { this.angle = angle; } public final float getX() { return this.x; } public final void setX(float x) { this.x = x; } public final float getY() { return this.y; } public final void setY(float y) { this.y = y; } public final float getZ() { return this.z; } public final void setZ(float z) { this.z = z; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\javax\vecmath\AxisAngle4f.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.bricenangue.nextgeneration.ebuycamer; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.ShareActionProvider; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.InputType; import android.text.TextUtils; import android.util.Pair; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.appinvite.AppInviteInvitation; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.UserInfo; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.MutableData; import com.google.firebase.database.Transaction; import com.google.firebase.database.ValueEventListener; import com.mikhaellopez.circularimageview.CircularImageView; import com.squareup.picasso.Callback; import com.squareup.picasso.NetworkPolicy; import com.squareup.picasso.Picasso; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.math.BigDecimal; import java.net.HttpURLConnection; import java.net.URL; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import static com.bricenangue.nextgeneration.ebuycamer.ConfigApp.getData; public class ViewContentDealActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener, View.OnClickListener { private static final int REQUEST_INVITE = 237; private Deals publication; private PublicationPhotos publicationPhotos; private FirebaseAuth auth; private DatabaseReference root; private String postUniqueFbId; private TextView textView_title, textView_price, textView_category, textView_description, textView_username, textView_user_type, textView_user_numberofAds, textView_my_current_offer,textView_all_offers; private ProgressDialog progressBar; private String myOffer, user_uid ="",creator_token; private Button button_location, button_time, button_viewer, buttonMakeoffer; private FirebaseUser user; private ViewPager intro_images; private LinearLayout pager_indicator; private int dotsCount; private ImageView[] dots; private ViewPagerAdapter mAdapter; private Toolbar toolbar; private UserSharedPreference userSharedPreference; private ArrayList<PublicationPhotos> arrayList = new ArrayList<>(); private CircularImageView imageView_userPhoto; private DatabaseReference referenceFavorites; private boolean isInFavorite; private MenuItem menuItem; private boolean fromFav = false; private String[] currencyArray; private boolean loaded = false; private UserPublic userPublic; private static final int MY_PERMISSIONS_REQUEST_PHONE_CALL=237; private static final int REQUEST_ID_MULTIPLE_PERMISSIONS=1; private String[] categoriesArray; private ValueEventListener valueEventListener; private DatabaseReference refcreator; private Button button_remove_offer; private ShareActionProvider mShareActionProvider; public boolean haveNetworkConnection() { boolean haveConnectedWifi = false; boolean haveConnectedMobile = false; ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo[] netInfo = cm.getAllNetworkInfo(); for (NetworkInfo ni : netInfo) { if ( "WIFI".equals(ni.getTypeName())) if (ni.isConnected()) haveConnectedWifi = true; if ("MOBILE".equals(ni.getTypeName())) if (ni.isConnected()) haveConnectedMobile = true; } return haveConnectedWifi || haveConnectedMobile; } @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); userSharedPreference = new UserSharedPreference(this); setContentView(R.layout.activity_view_content_deal); intro_images = (ViewPager) findViewById(R.id.pager_introduction_deal); pager_indicator = (LinearLayout) findViewById(R.id.viewPagerCountDots_deal); toolbar = (Toolbar) findViewById(R.id.toolbar_view_content_deal); currencyArray = getResources().getStringArray(R.array.currency); categoriesArray = getResources().getStringArray(R.array.categories_array_activity); textView_title = (TextView) findViewById(R.id.textView_viewcontent_title_deal); textView_price = (TextView) findViewById(R.id.textView_viewcontent_price_deal); textView_description = (TextView) findViewById(R.id.textView_viewcontent_description_deal); textView_category = (TextView) findViewById(R.id.textView_viewcontent_category_deal); textView_username = (TextView) findViewById(R.id.textView_viewcontent_user_name_deal); textView_user_numberofAds = (TextView) findViewById(R.id.textView_viewcontent_numberofAds_deal); textView_my_current_offer=(TextView)findViewById(R.id.textView_viewcontent_offer_deal); textView_all_offers=(TextView)findViewById(R.id.textView_viewcontent_offer_deal_for_creator); button_location = (Button) findViewById(R.id.button_viewcontent_location_deal); button_viewer = (Button) findViewById(R.id.button_viewcontent_viewer_deal); button_time = (Button) findViewById(R.id.button_viewcontent_time_deal); button_remove_offer = (Button) findViewById(R.id.button_delete_my_offer_offer_deal); imageView_userPhoto = (CircularImageView) findViewById(R.id.imageView_viewcontent_userpic_deal); buttonMakeoffer = (Button) findViewById(R.id.button_viewcontent_makeoffer_deal); auth = FirebaseAuth.getInstance(); userSharedPreference.setUserDataRefreshed(haveNetworkConnection()); if (auth== null) { if(userSharedPreference.getUserLoggedIn()){ // user offline if(!userSharedPreference.getUserDataRefreshed()){ // user refreshed data on start } }else { // user online but auth problem Toast.makeText(this,getString(R.string.problem_while_loading_user_data_auth_null),Toast.LENGTH_LONG).show(); startActivity(new Intent(this,MainActivity.class) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK)); finish(); } } else { user = auth.getCurrentUser(); } setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); root = FirebaseDatabase.getInstance().getReference(); referenceFavorites = root.child(ConfigApp.FIREBASE_APP_URL_USERS_FAVORITES).child(user.getUid()); Bundle extras = getIntent().getExtras(); if (extras != null) { postUniqueFbId = extras.getString("post"); if(extras.containsKey("user_uid")){ user_uid=extras.getString("user_uid"); } if (extras.containsKey("FromFav")) { fromFav = extras.getBoolean("FromFav"); } } if (savedInstanceState == null) { } buttonMakeoffer.setOnClickListener(this); if(user_uid!=null){ refcreator =root.child(ConfigApp.FIREBASE_APP_URL_USERS).child(user_uid).child("userPublic/chatId"); refcreator.keepSynced(true); } valueEventListener= new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { creator_token=dataSnapshot.getValue(String.class); } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(getApplicationContext(),databaseError.getMessage(),Toast.LENGTH_SHORT).show(); } }; } public void ButtonRemoveMyOfferClicked(View view){ if (!haveNetworkConnection()){ Toast.makeText(getApplicationContext(),getString(R.string.action_not_avialable_or_offline),Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(),getString(R.string.connection_to_server_not_aviable) ,Toast.LENGTH_SHORT).show(); }else { final DatabaseReference referenceOffers=FirebaseDatabase.getInstance().getReference() .child(ConfigApp.FIREBASE_APP_URL_USERS_DEAL_USER) .child(publication.getPrivateContent().getCreatorid()) .child(publication.getPrivateContent().getUniquefirebaseId()) .child("offers"); updateOffersListMinus(referenceOffers,publication.getPrivateContent().getUniquefirebaseId()); } } private void showProgressbar(){ progressBar = new ProgressDialog(this); progressBar.setCancelable(false); progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressBar.setMessage(getString(R.string.progress_dialog_loading)); progressBar.show(); } private void dismissProgressbar(){ if (progressBar!=null){ progressBar.dismiss(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } private void checkifexist() { showProgressbar(); dotsCount=0; DatabaseReference reffav = root.child(ConfigApp.FIREBASE_APP_URL_DEAL_EXIST) .child(postUniqueFbId); reffav.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot!=null) { getPost(); } else { if (fromFav) { if (haveNetworkConnection()){ Map<String, Object> childreen = new HashMap<>(); childreen.put("/" + ConfigApp.FIREBASE_APP_URL_USERS_FAVORITES + "/" + user.getUid() + "/" + postUniqueFbId, null); childreen.put("/" + ConfigApp.FIREBASE_APP_URL_USERS_FAVORITES_USER + "/" + user.getUid() + "/" + postUniqueFbId, null); root.updateChildren(childreen); Toast.makeText(getApplicationContext(), getString(R.string.string_toast_viewcontent_Post_deleted) , Toast.LENGTH_SHORT).show(); startActivity(new Intent(ViewContentDealActivity.this, MyFavoritesActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); finish(); }else { startActivity(new Intent(ViewContentDealActivity.this, MyFavoritesActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); finish(); } } else { Toast.makeText(getApplicationContext(), getString(R.string.string_toast_viewcontent_Post_deleted) , Toast.LENGTH_SHORT).show(); startActivity(new Intent(ViewContentDealActivity.this, ViewDealsActivity.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); finish(); } } } @Override public void onCancelled(DatabaseError databaseError) { dismissProgressbar(); Toast.makeText(getApplicationContext(),databaseError.getMessage() ,Toast.LENGTH_SHORT).show(); dismissProgressbar(); finish(); } }); if (!haveNetworkConnection()){ dismissProgressbar(); Toast.makeText(getApplicationContext(),getString(R.string.alertDialog_no_internet_connection),Toast.LENGTH_SHORT).show(); } } private void getPost() { if (postUniqueFbId != null) { refcreator.addValueEventListener(valueEventListener); if(user_uid!=null && user_uid.equals(user.getUid())){ DatabaseReference reference = root.child(ConfigApp.FIREBASE_APP_URL_USERS_DEAL_USER) .child(user_uid) .child(postUniqueFbId); reference.keepSynced(true); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { publication = dataSnapshot.getValue(Deals.class); if(publication!=null){ populate(publication); if (publication.getPrivateContent().getCreatorid().equals(user.getUid())) { if (menuItem != null) { menuItem.setEnabled(false); menuItem.setVisible(false); buttonMakeoffer.setVisibility(View.GONE); } } else { buttonMakeoffer.setVisibility(View.VISIBLE); DatabaseReference reference1 = root.child(ConfigApp.FIREBASE_APP_URL_USERS_FAVORITES_USER) .child(user.getUid()).child(publication.getPrivateContent().getUniquefirebaseId()); reference1.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() != null) { Boolean b = dataSnapshot.getValue(boolean.class); if (b) { isInFavorite = b; menuItem.setIcon(getResources().getDrawable(R.drawable.ic_star_white_36dp)); } } } @Override public void onCancelled(DatabaseError databaseError) { dismissProgressbar(); } }); } }else { if (haveNetworkConnection()){ // the post doesn't exist or has been deleted Toast.makeText(getApplicationContext(), getString(R.string.string_toast_viewcontent_Post_deleted) , Toast.LENGTH_SHORT).show(); finish(); } } } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(getApplicationContext(),databaseError.getMessage() ,Toast.LENGTH_SHORT).show(); dismissProgressbar(); finish(); } }); }else { DatabaseReference reference = root.child(ConfigApp.FIREBASE_APP_URL_USERS_DEAL) .child(postUniqueFbId); reference.keepSynced(true); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { publication = dataSnapshot.getValue(Deals.class); if(publication!=null){ populate(publication); if (publication.getPrivateContent().getCreatorid().equals(user.getUid())) { if (menuItem != null) { menuItem.setEnabled(false); menuItem.setVisible(false); buttonMakeoffer.setVisibility(View.GONE); } } else { buttonMakeoffer.setVisibility(View.VISIBLE); DatabaseReference reference1 = root.child(ConfigApp.FIREBASE_APP_URL_USERS_FAVORITES_USER) .child(user.getUid()).child(publication.getPrivateContent().getUniquefirebaseId()); reference1.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() != null) { Boolean b = dataSnapshot.getValue(boolean.class); if (b) { isInFavorite = b; menuItem.setIcon(getResources().getDrawable(R.drawable.ic_star_white_36dp)); } } } @Override public void onCancelled(DatabaseError databaseError) { dismissProgressbar(); } }); } }else { if (haveNetworkConnection()){ // the post doesn't exist or has been deleted Toast.makeText(getApplicationContext(), getString(R.string.string_toast_viewcontent_Post_deleted) , Toast.LENGTH_SHORT).show(); finish(); } } } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(getApplicationContext(),databaseError.getMessage() ,Toast.LENGTH_SHORT).show(); dismissProgressbar(); finish(); } }); } }else { finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_view_content, menu); this.menuItem = menu.findItem(R.id.action_mark_as_favorite_viewcontent); MenuItem item = menu.findItem(R.id.action_share_viewcontent); mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.action_mark_as_favorite_viewcontent: if (!haveNetworkConnection()){ Toast.makeText(getApplicationContext(),getString(R.string.connection_to_server_not_aviable) ,Toast.LENGTH_SHORT).show(); } if (isInFavorite) { if (publication != null) { item.setIcon(getResources().getDrawable(R.drawable.ic_star_border_white_36dp)); isInFavorite = false; if (!haveNetworkConnection()){ Toast.makeText(getApplicationContext(), getString(R.string.string_viewcontent_unmarked_as_favorite), Toast.LENGTH_SHORT).show(); } Map<String, Object> childreen = new HashMap<>(); childreen.put("/" + ConfigApp.FIREBASE_APP_URL_USERS_FAVORITES + "/" + user.getUid() + "/" + publication.getPrivateContent().getUniquefirebaseId(), null); childreen.put("/" + ConfigApp.FIREBASE_APP_URL_USERS_FAVORITES_USER + "/" + user.getUid() + "/" + publication.getPrivateContent().getUniquefirebaseId(), null); root.updateChildren(childreen).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(getApplicationContext(), getString(R.string.string_viewcontent_unmarked_as_favorite), Toast.LENGTH_SHORT).show(); } }); } else { finish(); Toast.makeText(getApplicationContext(), getString(R.string.string_viewcontent_error_post_null), Toast.LENGTH_SHORT).show(); } } else { if (publication != null) { item.setIcon(getResources().getDrawable(R.drawable.ic_star_white_36dp)); isInFavorite = true; if (!haveNetworkConnection()){ Toast.makeText(getApplicationContext(), getString(R.string.string_viewcontent_marked_as_favorite), Toast.LENGTH_SHORT).show(); } Map<String, Object> childreen = new HashMap<>(); childreen.put("/" + ConfigApp.FIREBASE_APP_URL_USERS_FAVORITES + "/" + user.getUid() + "/" + publication.getPrivateContent().getUniquefirebaseId(), publication); childreen.put("/" + ConfigApp.FIREBASE_APP_URL_USERS_FAVORITES_USER + "/" + user.getUid() + "/" + publication.getPrivateContent().getUniquefirebaseId(), true); root.updateChildren(childreen).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(getApplicationContext(), getString(R.string.string_viewcontent_marked_as_favorite), Toast.LENGTH_SHORT).show(); } }); } else { Toast.makeText(getApplicationContext(), getString(R.string.string_viewcontent_error_post_null), Toast.LENGTH_SHORT).show(); dismissProgressbar(); } } return true; case R.id.action_share_viewcontent: // Toast.makeText(getApplicationContext(), getString(R.string.string_toast_text_sharing_unavialable), Toast.LENGTH_SHORT).show(); onInviteClicked(); return true; case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } private void setUiPageViewController() { dotsCount = mAdapter.getCount(); if (dotsCount > 0) { dots = new ImageView[dotsCount]; for (int i = 0; i < dotsCount; i++) { dots[i] = new ImageView(this); dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot)); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ); params.setMargins(4, 0, 4, 0); pager_indicator.addView(dots[i], params); } dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot)); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (mAdapter.getCount() > 0) { for (int i = 0; i < dotsCount; i++) { dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot)); } dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot)); } } @Override public void onPageScrollStateChanged(int state) { } private void populate(final Deals publication) { if(publication.getPrivateContent().getCreatorid().equals(user.getUid())){ textView_my_current_offer.setVisibility(View.GONE); TextView textView=(TextView)findViewById(R.id.textView_deal_my_offer); textView.setVisibility(View.GONE); button_remove_offer.setVisibility(View.GONE); textView_all_offers.setVisibility(View.VISIBLE); textView_all_offers.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // open offer startActivity(new Intent(ViewContentDealActivity.this,SingleDealActivityActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .putExtra("user_uid",publication.getPrivateContent().getCreatorid()) .putExtra("dealid",publication.getPrivateContent().getUniquefirebaseId())); } }); if(publication.getOffers().getOffers()!=null){ if(publication.getOffers().getOffers().size()==1){ String pub= getString(R.string.viewdeal_user_opening) +" "+ publication.getOffers().getOffers().size() +" "+ getString(R.string.viewdeal_user_opening_offer); textView_all_offers.setText(pub); }else { String pub= getString(R.string.viewdeal_user_opening) +" "+ publication.getOffers().getOffers().size() +" "+ getString(R.string.viewdeal_user_opening_offers); textView_all_offers.setText(pub); } }else { String pub= getString(R.string.viewdeal_user_opening) +" 0 "+ getString(R.string.viewdeal_user_opening_offer); textView_all_offers.setText(pub); } }else { textView_my_current_offer.setVisibility(View.VISIBLE); TextView textView=(TextView)findViewById(R.id.textView_deal_my_offer); textView.setVisibility(View.VISIBLE); textView_all_offers.setVisibility(View.GONE); DatabaseReference refOffer=root.child(ConfigApp.FIREBASE_APP_URL_USERS_OFFERS_USER) .child(user.getUid()).child(postUniqueFbId); refOffer.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot!=null){ myOffer=dataSnapshot.getValue(String.class); if(myOffer!=null){ String offerprice=myOffer+ " " +currencyArray[getCurrencyPosition(publication.getPrivateContent().getCurrency())]; textView_my_current_offer.setText(offerprice); button_remove_offer.setVisibility(View.VISIBLE); }else { textView_my_current_offer.setText(getString(R.string.view_deal_content_no_offers_yet)); button_remove_offer.setVisibility(View.GONE); } }else { textView_my_current_offer.setText(getString(R.string.view_deal_content_no_offers_yet)); button_remove_offer.setVisibility(View.GONE); } } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(getApplicationContext(),databaseError.getMessage(),Toast.LENGTH_SHORT).show(); } }); } textView_title.setText(publication.getPrivateContent().getTitle()); String cat= categoriesArray[publication.getCategoriesDeal().getCatNumber() + 1] +" ("+ getString(R.string.textView_category_deal)+ ")"; textView_category.setText(cat); if (publication.getPrivateContent().getDescription() != null) { textView_description.setText(publication.getPrivateContent().getDescription()); } else { textView_description.setText(""); } DecimalFormat decFmt = new DecimalFormat("#,###.##", DecimalFormatSymbols.getInstance(Locale.FRENCH)); decFmt.setMaximumFractionDigits(2); decFmt.setMinimumFractionDigits(2); String p = publication.getPrivateContent().getPrice(); BigDecimal amt = new BigDecimal(p); String preValue = decFmt.format(amt); textView_price.setText(getString(R.string.string_price_of_deal_negotiable)); Date date = new Date(publication.getPrivateContent().getTimeofCreation()); DateFormat formatter = new SimpleDateFormat("HH:mm"); final String dateFormatted = formatter.format(date); CheckTimeStamp checkTimeStamp= new CheckTimeStamp(getApplicationContext(),publication.getPrivateContent().getTimeofCreation()); button_time.setText(checkTimeStamp.checktime()); button_location.setText(publication.getPrivateContent().getLocation().getName()); if (publication.getPublicContent().getNumberofView() > 0) { button_viewer.setText(String.valueOf(publication.getPublicContent().getNumberofView())); } else { button_viewer.setText(String.valueOf(0)); } DatabaseReference refuser = FirebaseDatabase.getInstance().getReference() .child(ConfigApp.FIREBASE_APP_URL_USERS).child(publication.getPrivateContent().getCreatorid()) .child("userPublic"); refuser.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { userPublic = dataSnapshot.getValue(UserPublic.class); if (dataSnapshot.hasChild("name") && !dataSnapshot.child("name").getValue(String.class).isEmpty()) { textView_username.setText(dataSnapshot.child("name").getValue(String.class)); } else if ((dataSnapshot.hasChild("name") && (dataSnapshot.child("name").getValue(String.class).isEmpty() && dataSnapshot.hasChild("email"))) || (!dataSnapshot.hasChild("name") && dataSnapshot.hasChild("email"))) { textView_username.setText(dataSnapshot.child("email").getValue(String.class)); } if (dataSnapshot.hasChild("numberOfAds")) { if (dataSnapshot.child("numberOfAds").getValue() != null) { String ads = String.valueOf(dataSnapshot.child("numberOfAds").getValue(long.class)) + " " + getString(R.string.viewcontent_user_numberof_Ads); textView_user_numberofAds.setText(ads); } else { String ads = "0 " + getString(R.string.viewcontent_user_numberof_Ads); textView_user_numberofAds.setText(ads); } } if (dataSnapshot.hasChild("profilePhotoUri")) { loadPicture(dataSnapshot.child("profilePhotoUri").getValue(String.class)); loaded = true; } dismissProgressbar(); } @Override public void onCancelled(DatabaseError databaseError) { dismissProgressbar(); } }); if (publication.getPrivateContent().getPublictionPhotos() != null) { mAdapter = new ViewPagerAdapter(ViewContentDealActivity.this, publication.getPrivateContent().getPublictionPhotos()); intro_images.setAdapter(mAdapter); intro_images.setCurrentItem(0); intro_images.setOnPageChangeListener(this); setUiPageViewController(); } else { mAdapter = new ViewPagerAdapter(ViewContentDealActivity.this, arrayList); intro_images.setAdapter(mAdapter); intro_images.setCurrentItem(0); intro_images.setOnPageChangeListener(this); setUiPageViewController(); } // if no picture check if facebook picture avialable if (!loaded && publication.getPrivateContent().getCreatorid().equals(user.getUid())) { String facebookUserId = ""; List<? extends UserInfo> list=user.getProviderData(); String providerId=list.get(1).getProviderId(); if (providerId.equals(getString(R.string.facebook_provider_id))) { facebookUserId = list.get(1).getUid(); } // construct the URL to the profile picture, with a custom height // alternatively, use '?type=small|medium|large' instead of ?height= final String photoUrl = "https://graph.facebook.com/" + facebookUserId + "/picture?type=large"; // (optional) use Picasso to download and show to image loadPicture(photoUrl); } } private void loadPicture(final String photoUrl) { Picasso.with(getApplicationContext()).load(photoUrl).networkPolicy(NetworkPolicy.OFFLINE) .into(imageView_userPhoto, new Callback() { @Override public void onSuccess() { dismissProgressbar(); } @Override public void onError() { Picasso.with(getApplicationContext()).load(photoUrl) .into(imageView_userPhoto); dismissProgressbar(); } }); } private int getCurrencyPosition(String currency) { if (currency.equals(getString(R.string.currency_xaf)) || currency.equals("F CFA") || currency.equals("XAF")) { return 0; } return 0; } @Override protected void onResume() { super.onResume(); } @Override protected void onStart() { super.onStart(); checkifexist(); } @Override protected void onPause() { super.onPause(); pager_indicator.removeAllViews(); if(refcreator!=null){ refcreator.removeEventListener(valueEventListener); } dismissProgressbar(); } @Override protected void onStop() { super.onStop(); pager_indicator.removeAllViews(); dismissProgressbar(); if(refcreator!=null){ refcreator.removeEventListener(valueEventListener); } } @Override public void onClick(View view) { switch (view.getId()){ case R.id.button_viewcontent_makeoffer_deal: startOffersMaking(); break; } } private void startOffersMaking() { if(publication!=null){ final DatabaseReference referenceOffers=FirebaseDatabase.getInstance().getReference() .child(ConfigApp.FIREBASE_APP_URL_USERS_DEAL_USER) .child(publication.getPrivateContent().getCreatorid()) .child(publication.getPrivateContent().getUniquefirebaseId()) .child("offers"); final AlertDialog alert = new AlertDialog.Builder(this).create(); final EditText edittext = new EditText(this); edittext.setInputType(InputType.TYPE_CLASS_NUMBER); alert.setMessage(getString(R.string.alertDialog_viewDeal_make_offer_message)); alert.setTitle(getString(R.string.alertDialog_viewDeal_make_offer_title)); alert.setView(edittext); alert.setButton(DialogInterface.BUTTON_POSITIVE,getString(R.string.alertDialog_viewDeal_make_offer_button_ok) , new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //What ever you want to do with the value //OR String price = edittext.getText().toString(); if(TextUtils.isEmpty(price)){ edittext.setError(getString(R.string.maimpage_alertdialog_edittext_error_empty)); edittext.requestFocus(); edittext.performClick(); }else { if (!haveNetworkConnection()){ Toast.makeText(getApplicationContext(),getString(R.string.action_not_avialable_or_offline),Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(),getString(R.string.connection_to_server_not_aviable) ,Toast.LENGTH_SHORT).show(); dialog.dismiss(); }else { updateOffersList(referenceOffers,price,publication.getPrivateContent().getUniquefirebaseId()); dialog.dismiss(); } } } }); alert.setButton(DialogInterface.BUTTON_NEUTRAL,getString(R.string.alertDialog_viewDeal_make_offer_button_cancel) , new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // what ever you want to do with No option. dialog.dismiss(); } }); alert.show(); } } private void updateOffersList(DatabaseReference DealRef, final String price, final String dealId) { DealRef.runTransaction(new Transaction.Handler() { @Override public Transaction.Result doTransaction(MutableData mutableData) { final DealsOffers p = mutableData.getValue(DealsOffers.class); if (p == null) { return Transaction.success(mutableData); } if(!p.getOffers().containsKey(auth.getCurrentUser().getUid())){ long offer = p.getNumberOfoffers(); offer = offer + 1; p.setNumberOfoffers(offer); } HashMap<String,Offer> map=p.getOffers(); if(map!=null){ map.put(auth.getCurrentUser().getUid(),new Offer(price,System.currentTimeMillis())); p.setOffers(map); }else { map=new HashMap<String, Offer>(); map.put(auth.getCurrentUser().getUid(),new Offer(price,System.currentTimeMillis())); p.setOffers(map); } // Set value and report transaction success mutableData.setValue(p); DatabaseReference refMYoffers=FirebaseDatabase.getInstance().getReference() .child(ConfigApp.FIREBASE_APP_URL_USERS_OFFERS_USER) .child(user.getUid()) .child(dealId); refMYoffers.setValue(price); return Transaction.success(mutableData); } @Override public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) { if(b){ sendNotification(getString(R.string.fcm_Notification_new_offers_message),dealId); String offerprice=price+ " " +currencyArray[getCurrencyPosition(publication.getPrivateContent().getCurrency())]; textView_my_current_offer.setText(offerprice); button_remove_offer.setVisibility(View.VISIBLE); } // Transaction completed // Log.d(TAG, "postTransaction:onComplete:" + databaseError); } }); } private void updateOffersListMinus(DatabaseReference DealRef, final String dealId) { DealRef.runTransaction(new Transaction.Handler() { @Override public Transaction.Result doTransaction(MutableData mutableData) { final DealsOffers p = mutableData.getValue(DealsOffers.class); if (p == null) { return Transaction.success(mutableData); } if(p.getOffers().containsKey(user.getUid())){ long offer = p.getNumberOfoffers(); offer = offer - 1; p.setNumberOfoffers(offer); HashMap<String,Offer> map=p.getOffers(); if(map!=null){ map.remove(user.getUid()); p.setOffers(map); } } // Set value and report transaction success mutableData.setValue(p); DatabaseReference refOffer=root.child(ConfigApp.FIREBASE_APP_URL_USERS_OFFERS_USER) .child(user.getUid()).child(dealId); refOffer.removeValue(); return Transaction.success(mutableData); } @Override public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) { if(b){ button_remove_offer.setVisibility(View.GONE); textView_my_current_offer.setVisibility(View.VISIBLE); TextView textView=(TextView)findViewById(R.id.textView_deal_my_offer); textView.setVisibility(View.VISIBLE); textView_all_offers.setVisibility(View.GONE); textView_my_current_offer.setText(getString(R.string.view_deal_content_no_offers_yet)); } // Transaction completed // Log.d(TAG, "postTransaction:onComplete:" + databaseError); } }); } private void sendNotification(String message,String post_id) { new SendNotification(message,post_id).execute(); } public class SendNotification extends AsyncTask<Void,Void,Void> { String message; String post_id; SendNotification(String message, String post_id){ this.post_id=post_id; this.message=message; } @Override protected void onPostExecute(Void reponse) { super.onPostExecute(reponse); } @Override protected Void doInBackground(Void... params) { HttpURLConnection conn=null; try { ArrayList<Pair<String,String>> data=new ArrayList<>(); String title=getString(R.string.fcm_Notification_new_offers); data.add(new Pair<String, String>("message", message)); data.add(new Pair<String, String>("receivertoken",creator_token)); data.add(new Pair<String, String>("post_id",post_id )); data.add(new Pair<String, String>("title",title )); byte[] bytes = getData(data).getBytes("UTF-8"); URL url=new URL(ConfigApp.OOOWEBHOST_SERVER_URL+ "FirebasePushNewOffer.php"); conn=(HttpURLConnection)url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer reponse = new StringBuffer(); while ((inputLine = in.readLine()) != null) { reponse.append(inputLine); } final String response =reponse.toString(); System.out.print(response); } catch (Exception e) { e.printStackTrace(); }finally { if(conn!=null){ conn.disconnect(); } } return null; } } private void onInviteClicked() { Intent intent = new AppInviteInvitation.IntentBuilder(getString(R.string.invitation_title)) .setMessage(getString(R.string.invitation_message)) .setDeepLink(Uri.parse(getString(R.string.invitation_deep_link))) .setCallToActionText(getString(R.string.invitation_cta)) .build(); startActivityForResult(intent, REQUEST_INVITE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode); if (requestCode == REQUEST_INVITE) { if (resultCode == RESULT_OK) { // Get the invitation IDs of all sent messages String[] ids = AppInviteInvitation.getInvitationIds(resultCode, data); for (String id : ids) { // Log.d(TAG, "onActivityResult: sent invitation " + id); } } else { // Sending failed or it was canceled, show failure message to the user // ... } } } @Override public void onBackPressed() { super.onBackPressed(); dismissProgressbar(); finish(); } }
package vshah2212.sih; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import java.io.BufferedReader; import java.io.InputStreamReader; import cz.msebera.android.httpclient.HttpResponse; import cz.msebera.android.httpclient.client.HttpClient; import cz.msebera.android.httpclient.client.methods.HttpGet; import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; class ResourceSubmit extends AsyncTask<String, Void, String> { Context ctx; String usn; public ResourceSubmit(Context context) { ctx = context; } protected String doInBackground(String... message) { HttpClient httpclient; HttpGet request; HttpResponse response = null; String result = ""; try { String send = message[0]; String[] rec = send.split(","); String name = rec[0]; String addr = rec[1]; String phn = rec[2]; String amt = rec[3]; String itm = rec[4]; String desc = rec[5]; httpclient = new DefaultHttpClient(); request = new HttpGet("http://dcshahfamily.esy.es/Register1.php?name="+name+"&loc="+addr+"&phn="+phn+"&amt="+amt+"&item="+itm+"&desc="+desc); response = httpclient.execute(request); } catch (Exception e) { result = "error1"; } try { BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); String line; while ((line = rd.readLine()) != null) { result = result + line; } } catch (Exception e) { Log.e("Error2","err "+e); result = "error2"; } return result; } protected void onPostExecute(String result) { Log.e("Result", "Result" + result); if (result.trim().equalsIgnoreCase("1")) { Toast.makeText(ctx,"Successfully Submitted",Toast.LENGTH_LONG).show(); } else { Toast.makeText(ctx,"Unable to submit please try again",Toast.LENGTH_LONG).show(); } } }
package SebastianMiklaszewski.Excercises.Presentation.UseCase.ExerciseOne; import SebastianMiklaszewski.Excercises.Infrastructure.Adapter.Input.ConsoleInputAdapter; import SebastianMiklaszewski.Excercises.Presentation.Shared.Input.InputInterface; import java.math.BigDecimal; public class MoneyToWithdrawInput { private final InputInterface input; public MoneyToWithdrawInput() { this.input = new ConsoleInputAdapter(); } public BigDecimal inputMoneyToWithdraw() { return new BigDecimal(this.input.getStringInput()); } }
package org.simpleflatmapper.converter.impl; import org.simpleflatmapper.converter.Converter; public class CharSequenceCharacterConverter implements Converter<CharSequence, Character> { @Override public Character convert(CharSequence in) throws Exception { if (in == null) return null; return Character.valueOf((char) Integer.parseInt(in.toString())); } public String toString() { return "CharSequenceToCharacter"; } }
package com.example.strongM.mycalendarview.calendar.formatter; import com.example.strongM.mycalendarview.calendar.CalendarDayData; public interface TitleFormatter { CharSequence format(CalendarDayData day); }
package com.tencent.smtt.sdk; import java.io.File; import java.io.FileFilter; class at implements FileFilter { final /* synthetic */ ar a; at(ar arVar) { this.a = arVar; } public boolean accept(File file) { return file.getName().endsWith("tbs.conf"); } }
package org.wso2.charon3.core.protocol.endpoints; /* * @author{Jayesh} * */ public class AuthenticationObject { /*@Override public String toString() { return "AuthenticationObject [name=" + name + ", description=" + description + ", specUri=" + specUri + ", documentationUri=" + documentationUri + ", type=" + type + ", primary=" + primary + "]"; } */ public String name; public String description; public String specUri; public String documentationUri; public String type; public boolean primary; public AuthenticationObject(String name, String description, String specUri, String documentationUri, String type, boolean primary) { super(); this.name = name; this.description = description; this.specUri = specUri; this.documentationUri = documentationUri; this.type = type; this.primary = primary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getSpecUri() { return specUri; } public void setSpecUri(String specUri) { this.specUri = specUri; } public String getDocumentationUri() { return documentationUri; } public void setDocumentationUri(String documentationUri) { this.documentationUri = documentationUri; } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isPrimary() { return primary; } public void setPrimary(boolean primary) { this.primary = primary; } }
package com.anydecisions.bean; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; import javax.persistence.Transient; import java.io.InputStream; import java.sql.Blob; import java.sql.SQLException; @Entity @Table(name = "CATEGORY") public class Category { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "CATEGORY_ID") private int categoryId; @Column(name = "CATEGORY_NAME") private String categoryName; @Column(name="CATEGORY_IMG") private String categoryImg; @Column(name = "CATEGORY_DESC") private String categoryDesc; public int getCategoryId() { return categoryId; } public void setCategoryId(int categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public String getCategoryImg() { return categoryImg; } public void setCategoryImg(String categoryImg) { this.categoryImg = categoryImg; } public String getCategoryDesc() { return categoryDesc; } public void setCategoryDesc(String categoryDesc) { this.categoryDesc = categoryDesc; } }
package graph; public class Edge { public Node start_node; public Node target_node; public String annotation; public double weight; public Edge(Node start_node, Node target_node, String annotation, double weight) { this.start_node = start_node; this.target_node = target_node; this.annotation = annotation; this.weight = weight; } @Override public String toString() { return super.toString(); } }
package com.slavko.prometeus.week5.patternCommand; public class EchoCommand implements Command{ Menu menu; String string; public EchoCommand(Menu menu, String string) { this.menu = menu; this.string = string; } @Override public void execute() { menu.echo(string); } }
package upper_case_client; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceException; import javax.xml.ws.WebServiceFeature; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.2 * */ @WebServiceClient(name = "UpperCaseServiceService", targetNamespace = "http://services/", wsdlLocation = "file:/home/snavi/Documents/distributed_systems/distributed_systems/client/src/UpperCaseService.wsdl") public class UpperCaseServiceService extends Service { private final static URL UPPERCASESERVICESERVICE_WSDL_LOCATION; private final static WebServiceException UPPERCASESERVICESERVICE_EXCEPTION; private final static QName UPPERCASESERVICESERVICE_QNAME = new QName("http://services/", "UpperCaseServiceService"); static { URL url = null; WebServiceException e = null; try { url = new URL("file:/home/snavi/Documents/distributed_systems/distributed_systems/client/src/UpperCaseService.wsdl"); } catch (MalformedURLException ex) { e = new WebServiceException(ex); } UPPERCASESERVICESERVICE_WSDL_LOCATION = url; UPPERCASESERVICESERVICE_EXCEPTION = e; } public UpperCaseServiceService() { super(__getWsdlLocation(), UPPERCASESERVICESERVICE_QNAME); } public UpperCaseServiceService(WebServiceFeature... features) { super(__getWsdlLocation(), UPPERCASESERVICESERVICE_QNAME, features); } public UpperCaseServiceService(URL wsdlLocation) { super(wsdlLocation, UPPERCASESERVICESERVICE_QNAME); } public UpperCaseServiceService(URL wsdlLocation, WebServiceFeature... features) { super(wsdlLocation, UPPERCASESERVICESERVICE_QNAME, features); } public UpperCaseServiceService(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName); } public UpperCaseServiceService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) { super(wsdlLocation, serviceName, features); } /** * * @return * returns UpperCaseService */ @WebEndpoint(name = "UpperCaseServicePort") public UpperCaseService getUpperCaseServicePort() { return super.getPort(new QName("http://services/", "UpperCaseServicePort"), UpperCaseService.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. * @return * returns UpperCaseService */ @WebEndpoint(name = "UpperCaseServicePort") public UpperCaseService getUpperCaseServicePort(WebServiceFeature... features) { return super.getPort(new QName("http://services/", "UpperCaseServicePort"), UpperCaseService.class, features); } private static URL __getWsdlLocation() { if (UPPERCASESERVICESERVICE_EXCEPTION!= null) { throw UPPERCASESERVICESERVICE_EXCEPTION; } return UPPERCASESERVICESERVICE_WSDL_LOCATION; } }
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Button for handling betAmount multiples * * @author Saksham Ghimire and Densai Moua * @version 12/15/2010 */ public class x2 extends Actor { /** * Act() method updates the betAmount by times and resets the display */ public void act() { if(Greenfoot.mouseClicked(this)){ if(spinButton.count>=4){ spinButton.betAmount=4; betLabel.betlabel="4 points"; } } } }
package com.projekt.app.appprojekt; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Menue extends AppCompatActivity implements View.OnClickListener { Button Routenberechnung, HHNStandorte; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menue); Routenberechnung = (Button) findViewById(R.id.Routenberechnung); HHNStandorte = (Button) findViewById(R.id.HHNStandorte); Routenberechnung.setOnClickListener(this); HHNStandorte.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.Routenberechnung: Intent Maps = new Intent(this, MapsActivity.class); startActivity(Maps); break; case R.id.HHNStandorte: Intent Standorte = new Intent(this, Standortauswahl.class); startActivity(Standorte); break; } } }
package io.vakin.io.nio; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.Channel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.StandardCharsets; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public class ChatRoomNIOServer { private Selector selector = null; static final int port = 9999; // 用来记录在线人数,以及昵称 private static Map<SocketChannel, String> onlineUsers = new ConcurrentHashMap<>(); // 相当于自定义协议格式,与客户端协商好 private static String USER_CONTENT_SPILIT = ":"; public void init() throws IOException { selector = Selector.open(); ServerSocketChannel server = ServerSocketChannel.open(); server.bind(new InetSocketAddress(port)); // 非阻塞的方式 server.configureBlocking(false); // 注册到选择器上,设置为监听状态 server.register(selector, SelectionKey.OP_ACCEPT); System.out.println("启动完成..."); while (true) { int readyChannels = selector.select(); if (readyChannels == 0) continue; Set<SelectionKey> selectedKeys = selector.selectedKeys(); // 可以通过这个方法,知道可用通道的集合 Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); while (keyIterator.hasNext()) { SelectionKey sk = keyIterator.next(); keyIterator.remove(); dealWithSelectionKey(server, sk); } } } public void dealWithSelectionKey(ServerSocketChannel server, SelectionKey sk) throws IOException { if (sk.isAcceptable()) { SocketChannel sc = server.accept(); // 非阻塞模式 sc.configureBlocking(false); // 注册选择器,并设置为读取模式,收到一个连接请求,然后起一个SocketChannel,并注册到selector上,之后这个连接的数据,就由这个SocketChannel处理 sc.register(selector, SelectionKey.OP_READ); // 将此对应的channel设置为准备接受其他客户端请求 sk.interestOps(SelectionKey.OP_ACCEPT); sc.write(StandardCharsets.UTF_8.encode("SUCCESSED")); } // 处理来自客户端的数据读取请求 if (sk.isReadable()) { // 返回该SelectionKey对应的 Channel,其中有数据需要读取 SocketChannel sc = (SocketChannel) sk.channel(); ByteBuffer buff = ByteBuffer.allocate(1024); StringBuilder content = new StringBuilder(); try { while (sc.read(buff) > 0) { buff.flip(); content.append(StandardCharsets.UTF_8.decode(buff)); } if(content.length() == 0){ // 断开 sc.close(); System.out.println("用户【"+onlineUsers.remove(sc)+"】下线"); return; } // 将此对应的channel设置为准备下一次接受数据 sk.interestOps(SelectionKey.OP_READ); } catch (IOException io) { sk.cancel(); if (sk.channel() != null) { sk.channel().close(); } } if (content.length() > 0) { String[] arrayContent = content.toString().split(USER_CONTENT_SPILIT); // 注册用户 if (arrayContent != null && arrayContent.length == 1) { String name = arrayContent[0]; onlineUsers.put(sc, name); int num = onlineUsers.size(); String message = "用户【" + name + "】进入聊天室! 当前在线人数:" + num; System.out.println(message); // 不回发给发送此内容的客户端 BroadCast(selector, sc, message); } else if (arrayContent != null && arrayContent.length > 1) { String name = arrayContent[0]; String message = content.substring(name.length() + USER_CONTENT_SPILIT.length()); message = "【" + name + " 】:" + message; System.out.println(message); BroadCast(selector, null, message); } } } } public void BroadCast(Selector selector, SocketChannel exclude, String content) throws IOException { // 广播数据到所有的SocketChannel中 for (SelectionKey key : selector.keys()) { Channel targetchannel = key.channel(); // 如果except不为空,不回发给发送此内容的客户端 if (targetchannel instanceof SocketChannel && targetchannel != exclude) { SocketChannel dest = (SocketChannel) targetchannel; dest.write(StandardCharsets.UTF_8.encode(content)); } } } public static void main(String[] args) throws IOException { new ChatRoomNIOServer().init(); } }
package org.tyaa.java.springboot.gae.simplespa.JavaSpringBootGaeSimpleSpa.model; import com.google.gson.annotations.Expose; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Index; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @NoArgsConstructor @Getter @Setter @Entity(name = "UserTypes") public class UserTypeModel { @Id @Expose public Long id; @Index @Expose public String name; }
package org.myas.kafka; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.junit.jupiter.api.Test; import org.myas.kafka.consumer.BasicKafkaConsumer; import org.myas.kafka.consumer.KafkaConsumer; import org.myas.kafka.producer.BasicKafkaProducer; import org.myas.kafka.producer.KafkaProducer; import org.myas.kafka.utils.PropertiesHelper; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class ProduceConsumeTest { private static final String BROKERS = System.getProperty("kafka.brokers"); private KafkaProducer<String, String> producer; private KafkaConsumer<String, String> consumer; @Test void testProduceConsume() throws InterruptedException { producer = new BasicKafkaProducer<>(PropertiesHelper.defaultProducerProperties(BROKERS, "my_producer"), "my_topic", new StringSerializer(), new StringSerializer()); consumer = new BasicKafkaConsumer<>(PropertiesHelper.defaultConsumerProperties(BROKERS, "my_consumer"), "my_topic", new StringDeserializer(), new StringDeserializer()); consumer.init(); ExecutorService executorService = Executors.newFixedThreadPool(1); executorService.submit(() -> { consumer.start(record -> { System.out.printf("%s %s\n", record.value(), record.offset()); }); }); executorService.shutdown(); for (int i = 0; i < 100; i++) { producer.send(Integer.toString(i)); } executorService.awaitTermination(2, TimeUnit.SECONDS); consumer.stop(); } @Test void testProduce() throws InterruptedException, ExecutionException { producer = new BasicKafkaProducer<>(PropertiesHelper.defaultProducerProperties(BROKERS, "my_producer"), "my_topic", new StringSerializer(), new StringSerializer()); Future<RecordMetadata> fut = producer.sendAsync("test"); System.out.println(fut.get().offset()); } @Test void testConsume() throws InterruptedException { consumer = new BasicKafkaConsumer<>(PropertiesHelper.defaultConsumerProperties(BROKERS, "my_consumer"), "my_topic", new StringDeserializer(), new StringDeserializer()); consumer.init(); consumer.start(record -> { System.out.printf("%s %s\n", record.value(), record.offset()); }); } }
package ms.ui; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; import javafx.fxml.FXML; import javafx.geometry.Insets; import javafx.scene.control.MenuBar; import javafx.scene.layout.VBox; import javafx.stage.Stage; import ms.events.Difficulties; import ms.events.Difficulty; import ms.events.ResetEvent; import ms.events.StageReadyEvent; @Component public class UIController { private Stage stage; private double padding; @FXML private VBox ui; @FXML private BoardController boardController; @FXML private MenuBar menu; public UIController(@Value("#{${spring.application.ui.blockSize} * 0.3}") double padding, ApplicationEventPublisher publisher) { this.padding = padding; } public void initialize() { ui.setSpacing(padding); ui.setPadding(new Insets(padding, padding, padding, padding)); if ("Mac OS X".equals(System.getProperty("os.name"))) menu.useSystemMenuBarProperty().set(true); onReset(new ResetEvent(Difficulties.BEGINNER.getDifficulty())); } @EventListener public void onReset(ResetEvent event) { Difficulty difficulty = event.getDifficulty(); boardController.setup(difficulty); if (stage != null) stage.sizeToScene(); } @EventListener public void onStageReady(StageReadyEvent event) { this.stage = event.getStage(); } }
package com.sula.service.impl; import com.jfinal.plugin.activerecord.Db; import com.jfinal.plugin.activerecord.Page; import com.jfinal.plugin.activerecord.Record; import com.spatial4j.core.io.GeohashUtils; import com.sula.model.Truck; import com.sula.model.TruckInfo; import com.sula.service.DriverService; import com.sula.util.Status; import org.apache.commons.lang.StringUtils; import java.util.Date; import java.util.List; public class DriverServiceImpl implements DriverService { @Override public int insertCarInfo(Truck truck) { Record record = new Record(); record.set("user_id",truck.getUserId()); record.set("address",truck.getAddress()); record.set("plateno",truck.getPlateno()); record.set("carlength",truck.getCarLength()); record.set("carmodels",truck.getCarModels()); record.set("carload",truck.getCarLoad()); record.set("img",truck.getImg()); record.set("img2",truck.getImg2()); record.set("img3",truck.getImg3()); record.set("img4",truck.getImg4()); record.set("create_time",truck.getCreateTime()); boolean flag = Db.save("sl_user_truck",record); return flag ? Status.success : Status.fail; } @Override public List<Record> queryCarByUserId(Integer userId) { StringBuffer querySQL = new StringBuffer("select *," + "(select dict.value from sl_app_dict dict where dict.type='car-length' and dict.key=truck.carlength) as length,"+ "(select dict.value from sl_app_dict dict where dict.type='car-model' and dict.key=truck.carmodels) as model"+ " from sl_user_truck truck where truck.user_id="+userId); return Db.find(querySQL.toString()); } @Override public int insertTruckInfo(TruckInfo info) { String geoCode = GeohashUtils.encodeLatLon(info.getStartLon(),info.getStartLat()); String endGeoCode = GeohashUtils.encodeLatLon(info.getEndLon(),info.getEndLat()); info.setCreateTime(new Date()); Record record = new Record(); record.set("trucks_id",info.getTruckId()); record.set("loadtime",info.getLoadTime()); record.set("startplace",info.getStartPlace()); record.set("endplace",info.getEndPlace()); record.set("create_time",info.getCreateTime()); record.set("start_lon",info.getStartLon()); record.set("start_lat",info.getStartLat()); record.set("start_geo_code",geoCode); record.set("end_lon",info.getEndLon()); record.set("end_lat",info.getEndLat()); record.set("end_geo_code",endGeoCode); boolean flag = Db.save("sl_trucks_info",record); return flag ? Status.success : Status.fail; } @Override public int driverVerify(Record record) { boolean flag = Db.save("sl_acc_info",record); return flag ? Status.success : Status.fail; } @Override public int addReplayInfo(Integer userId, Integer wayBillId, Integer score, String contents) { Record record = new Record(); record.set("userid",userId); record.set("waybillid",wayBillId); record.set("score",score); record.set("contents",contents); record.set("createtime",new Date()); boolean flag = Db.save("sl_waybill_replay",record); return flag ? Status.success : Status.fail; } @Override public Page<Record> loadReplayInfo(int page,int sourceId) { String sql = "SELECT replay.*,userinfo.nick as username,userinfo.img as avatar "; String exSql = " LEFT JOIN sl_waybill_replay replay on replay.waybillid = waybill.id"; exSql += " LEFT JOIN sl_user_info userinfo on userinfo.id = replay.userid"; exSql += " where waybill.trucks_id="+sourceId; return Db.paginate(page,Status.appPageSize,sql,exSql); } @Override public Page<Record> findDriver(double lonValue, double latValue,int page) { //计算出前三位geo_code 默认查询一百五十公里内 String geoCode = GeohashUtils.encodeLatLon(lonValue, latValue, 3); StringBuffer selectSQL = buildSelectSQL(); StringBuffer querySQL = buildQuerySQL(geoCode); return Db.paginate(page,Status.appPageSize,selectSQL.toString(),querySQL.toString()); } @Override public Page<Record> searchDrivers(String startPatten, String endPatten, Integer carLength, String loadTime, int page) { StringBuffer selectSQL = buildSearchDriversSelect(); StringBuffer querySQL = buildSearchDriversQuery(startPatten,endPatten,carLength,loadTime); return Db.paginate(page,Status.appPageSize,selectSQL.toString(),querySQL.toString()); } private StringBuffer buildSearchDriversQuery(String startPatten, String endPatten, Integer carLength, String loadTime) { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(" FROM"); stringBuffer.append(" (SELECT * FROM sl_trucks_info WHERE 1=1 "); if(StringUtils.isNotEmpty(startPatten)){ stringBuffer.append(" and start_geo_code like '"+startPatten+"%'"); } if(StringUtils.isNotEmpty(endPatten)){ stringBuffer.append(" and end_geo_code like '"+endPatten+"%'"); } if(StringUtils.isNotEmpty(loadTime)){ stringBuffer.append(" and loadtime='"+loadTime+"'"); } stringBuffer.append(" ) trucks"); stringBuffer.append(" LEFT JOIN sl_user_truck truck ON truck.id = trucks.trucks_id"); stringBuffer.append(" LEFT JOIN sl_user_info userinfo ON userinfo.id = truck.user_id where 1=1"); if(carLength != null){ stringBuffer.append(" and truck.carlength ='"+carLength+"'"); } return stringBuffer; } private StringBuffer buildSearchDriversSelect() { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("SELECT "); stringBuffer.append(" trucks.id AS id,"); stringBuffer.append(" trucks.trucks_id AS trucksId,"); stringBuffer.append(" trucks.startplace AS startPlace,"); stringBuffer.append(" trucks.endplace AS endPlace,"); stringBuffer.append(" trucks.loadtime as loadTime,"); stringBuffer.append(" trucks.start_lon as startLon,"); stringBuffer.append(" trucks.start_lat as startLat,"); stringBuffer.append(" trucks.create_time as createTime,"); stringBuffer.append(" (select dict.value from sl_app_dict dict where dict.type='car-length' and dict.key=truck.carlength) as carLength,"); stringBuffer.append(" (select dict.value from sl_app_dict dict where dict.type='car-model' and dict.key=truck.carmodels) as carModels,"); stringBuffer.append(" truck.carload as carLoad,"); stringBuffer.append(" userInfo.img AS image,"); stringBuffer.append(" userInfo.mobile as phone"); return stringBuffer; } private StringBuffer buildQuerySQL(String geoCode) { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(" from (SELECT * FROM sl_trucks_info WHERE start_geo_code LIKE '"+geoCode+"%') trucks"); stringBuffer.append(" LEFT JOIN sl_user_truck truck ON truck.id = trucks.trucks_id"); stringBuffer.append(" LEFT JOIN sl_user_info userinfo ON userinfo.id = truck.user_id"); return stringBuffer; } private StringBuffer buildSelectSQL() { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("SELECT "); stringBuffer.append(" trucks.id as id,"); stringBuffer.append(" trucks.trucks_id as trucksId,"); stringBuffer.append(" trucks.startplace as startPlace,"); stringBuffer.append(" trucks.endplace as endPlace,"); stringBuffer.append(" trucks.loadtime as loadTime,"); stringBuffer.append(" trucks.start_lon as startLon,"); stringBuffer.append(" trucks.start_lat as startLat,"); stringBuffer.append(" trucks.end_lon as endLon,"); stringBuffer.append(" trucks.end_lat as endLat,"); stringBuffer.append(" (SELECT dict.value from sl_app_dict dict WHERE dict.key = truck.carlength and dict.type='car-length') as carLength,"); stringBuffer.append(" (SELECT dict.value from sl_app_dict dict WHERE dict.key = truck.carmodels and dict.type='car-models') as carModels,"); stringBuffer.append(" truck.carload as carLoad,"); stringBuffer.append(" userinfo.img as image,"); stringBuffer.append(" userinfo.mobile as phone"); return stringBuffer; } @Override public Record selectTruckInfo(Integer driverId) { String selectSQL = "SELECT truck.*," + "(select dict.value from sl_app_dict dict where dict.type='car-length' and dict.key=truck.carlength) as carLength," + "(SELECT dict.value from sl_app_dict dict WHERE dict.key = truck.carmodels and dict.type='car-models') as carModels," + "userInfo.img as profile,userInfo.mobile as phone" + " from (SELECT * FROM sl_user_truck WHERE id="+driverId+") truck" + " LEFT JOIN sl_user_info userInfo ON userInfo.id = truck.user_id"; return Db.findFirst(selectSQL); } @Override public Record selectTrucksInfo(Integer trucksId) { String selectSQL = "SELECT * FROM sl_trucks_info WHERE id="+trucksId; return Db.findFirst(selectSQL); } @Override public Record selectRateInfo(Integer trucksId) { String selectSQL = "SELECT count(*) as waybillTimes,(SELECT avg(score) " + "FROM sl_waybill_replay WHERE waybillid = waybill.id) as rate " + "FROM sl_waybill waybill WHERE waybill.trucks_id="+trucksId; return Db.findFirst(selectSQL); } @Override public Page<Record> loadRepay(Integer trucksId, Integer page) { String selectSQL = "SELECT replay.contents,replay.createtime,userinfo.nick,userinfo.img "; String querySQL = "FROM (SELECT * from sl_waybill WHERE trucks_id="+trucksId+") waybill " + "LEFT JOIN sl_waybill_replay replay ON replay.waybillid = waybill.id " + "LEFT JOIN sl_user_info userinfo on userinfo.id = replay.userid"; return Db.paginate(page,Status.appPageSize,selectSQL,querySQL); } @Override public Page<Record> selectMimeWaybill(Integer userId, String type,Integer page) { String selectSQL = "SELECT goods.startplace as startPlace, goods.endplace as endPlace," + "(SELECT dict.value FROM sl_app_dict dict WHERE dict.type='car-length' and dict.key=goods.carlength) as carLength," + "(SELECT dict.value FROM sl_app_dict dict WHERE dict.type='car-model' and dict.key=goods.carmodels) as carModel," + "CASE WHEN waybill.trucks_id is null THEN 0 ELSE (SELECT truck.carload FROM sl_user_truck truck WHERE truck.id" + "=(SELECT trucks.trucks_id FROM sl_trucks_info trucks WHERE trucks.id=waybill.trucks_id )) END as carLoad," + "goods.loadtime as loadTime,goods.id as goodId,goods.create_time as createTime,waybill.trucks_id as trucksId,waybill.id as waybillId," + "CASE waybill.waystate WHEN 0 THEN '接单中' WHEN 1 THEN '装货中' WHEN 2 THEN '运送中' WHEN 3 THEN '已送达' WHEN 4 THEN '待评价' " + "WHEN 5 THEN '完成' WHEN 10 THEN '取消' END AS state,waybill.waystate as waystate"; String querySQL = "FROM (SELECT * FROM sl_waybill WHERE trucks_id IN (" + "SELECT id FROM sl_trucks_info WHERE trucks_id IN " + "(SELECT truck.id FROM sl_user_truck truck WHERE truck.user_id = 2)"; if(Status.TYPE_IN_TRANSIT.equals(type)){ querySQL += " AND waystate not IN (5,10) "; } querySQL += ")) waybill" + "LEFT JOIN sl_goods_info goods ON goods.id = waybill.goods_id"; return Db.paginate(page,Status.appPageSize,selectSQL,querySQL); } }
package day58_polymorphism; public class SuperManTest { public static void main(String[] args) { Father spMan =new SuperMan(); spMan.playWithKid(); spMan.feedKid(); spMan.raiseKid(); //spMan.work("SDET") -->ERROR because left side Father gives just its methods Workable wMan =new SuperMan(); System.out.println("got paid $ " + wMan.getPaid()); wMan.work("SDET"); //wMan.playWithKids(); --->ERROR because it is not left side's workable class method SuperMan sMan = new SuperMan(); //NOT POLYMORPHISM sMan.getPaid(); sMan.work("QE"); sMan.feedKid(); sMan.playWithKid(); sMan.raiseKid(); } }