text
stringlengths
10
2.72M
package com.tencent.f; public interface c { Object cHn(); }
package exam_module5.demo.repository; import exam_module5.demo.model.Car; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface CarRepo extends JpaRepository<Car, Integer> { List<Car> findByNameContaining(String name); }
package com.immotor.bluetoothadvertiser.webAPI; /** * Created by ZhengQingQing on 16/4/9. */ public class Passcode { private Object user_id; private String phone; private int passcode; private String expired; private boolean active; private String id; private String updated_at; private String created_at; public void setUser_id(Object user_id) { this.user_id = user_id; } public void setPhone(String phone) { this.phone = phone; } public void setPasscode(int passcode) { this.passcode = passcode; } public void setExpired(String expired) { this.expired = expired; } public void setActive(boolean active) { this.active = active; } public void setId(String id) { this.id = id; } public void setUpdated_at(String updated_at) { this.updated_at = updated_at; } public void setCreated_at(String created_at) { this.created_at = created_at; } public Object getUser_id() { return user_id; } public String getPhone() { return phone; } public int getPasscode() { return passcode; } public String getExpired() { return expired; } public boolean getActive() { return active; } public String getId() { return id; } public String getUpdated_at() { return updated_at; } public String getCreated_at() { return created_at; } }
/* * created 31.10.2005 * * Copyright 2009, ByteRefinery * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * $Id: CompareValuesDialog.java 215 2006-02-18 21:08:54Z cse $ */ package com.byterefinery.rmbench.export; import java.util.StringTokenizer; import org.eclipse.compare.rangedifferencer.IRangeComparator; import org.eclipse.compare.rangedifferencer.RangeDifference; import org.eclipse.compare.rangedifferencer.RangeDifferencer; import org.eclipse.draw2d.ColorConstants; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; /** * a dialog that shows the compared values in two multiline text fields, with differences * highlighted * * @author cse */ public class CompareValuesDialog extends Dialog { private static final Color DIFF_ADD = ColorConstants.green; private static final Color DIFF_CHG = ColorConstants.red; private static final Color DIFF_BG = ColorConstants.white; private static int TEXT_HEIGHT = 7; private static int TEXT_WIDTH = 75; private final String modelValue; private final String dbValue; private final WordRangeComparator leftComparator, rightComparator; private final RangeDifference[] differences; /** * @param parentShell * @param modelValue the model value * @param dbValue the database value */ protected CompareValuesDialog(Shell parentShell, String modelValue, String dbValue) { super(parentShell); this.modelValue = modelValue; this.dbValue = dbValue; setShellStyle(getShellStyle() | SWT.RESIZE); leftComparator = new WordRangeComparator(modelValue); rightComparator = new WordRangeComparator(dbValue); differences = RangeDifferencer.findDifferences(leftComparator, rightComparator); } protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText(Messages.CompareValuesDialog_title); } protected Control createDialogArea(Composite container) { Composite parent = (Composite) super.createDialogArea(container); Label modelLabel = new Label(parent, SWT.NONE); modelLabel.setLayoutData(new GridData()); modelLabel.setText(Messages.CompareValuesDialog_modelLabel); StyledText modelText = new StyledText(parent, SWT.BORDER | SWT.MULTI | SWT.READ_ONLY | SWT.WRAP); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); gd.widthHint = convertWidthInCharsToPixels(TEXT_WIDTH); gd.heightHint = convertHeightInCharsToPixels(TEXT_HEIGHT); modelText.setLayoutData(gd); modelText.setText(modelValue); Label dbLabel = new Label(parent, SWT.NONE); dbLabel.setLayoutData(new GridData()); dbLabel.setText(Messages.CompareValuesDialog_databaseLabel); StyledText dbText = new StyledText(parent, SWT.BORDER | SWT.MULTI | SWT.READ_ONLY | SWT.WRAP); gd = new GridData(SWT.FILL, SWT.FILL, true, true); gd.widthHint = convertWidthInCharsToPixels(TEXT_WIDTH); gd.heightHint = convertHeightInCharsToPixels(TEXT_HEIGHT); dbText.setLayoutData(gd); dbText.setText(dbValue); int startPos, length; for (int i = 0; i < differences.length; i++) { boolean add = differences[i].rightLength() == 0; boolean delete = differences[i].leftLength() == 0; if(!delete) { startPos = leftComparator.getPosition(differences[i].leftStart()); length = leftComparator.getLength(differences[i].leftStart(), differences[i].leftLength()); modelText.setStyleRange(new StyleRange(startPos, length, add ? DIFF_ADD : DIFF_CHG, DIFF_BG)); } if(!add) { startPos = rightComparator.getPosition(differences[i].rightStart()); length = rightComparator.getLength(differences[i].rightStart(), differences[i].rightLength()); dbText.setStyleRange(new StyleRange(startPos, length, DIFF_CHG, DIFF_BG)); } } return parent; } protected void createButtonsForButtonBar(Composite parent) { createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); } /* * a comparator that uses tokens (words) as compare ranges, and memorizes token positions */ private static class WordRangeComparator implements IRangeComparator { private final String[] tokens; private final int[] positions; WordRangeComparator(String value) { StringTokenizer tokenizer = new StringTokenizer(value); this.tokens = new String[tokenizer.countTokens()]; this.positions = new int[tokens.length]; int i = 0, lastPos = 0; while(tokenizer.hasMoreTokens()) { tokens[i] = tokenizer.nextToken(); lastPos = value.indexOf(tokens[i], lastPos); positions[i] = lastPos; i++; } } public int getPosition(int index) { return positions[index]; } public int getLength(int index, int count) { int endIndex = index + count - 1; int start = positions[index]; int end = positions[endIndex] + tokens[endIndex].length(); return end - start; } public int getRangeCount() { return tokens.length; } public boolean rangesEqual(int thisIndex, IRangeComparator other, int otherIndex) { return ((WordRangeComparator)other).getToken(otherIndex).equals(getToken(thisIndex)); } private String getToken(int index) { return tokens[index]; } public boolean skipRangeComparison(int length, int maxLength, IRangeComparator other) { return false; } } }
package com.goldgov.dygl.module.partyMemberDuty.dutybranch.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.goldgov.dygl.module.partyMemberDuty.dutybranch.dao.IDutyBranchEvaluationDao; import com.goldgov.dygl.module.partyMemberDuty.dutybranch.service.IDutyBranchEvaluationService; import com.goldgov.dygl.module.partymember.exception.NoAuthorizedFieldException; import com.goldgov.dygl.module.partyMemberDuty.dutybranch.domain.DutyBranchEvaluation; import com.goldgov.dygl.module.partyMemberDuty.dutybranch.domain.DutyScore; import com.goldgov.dygl.module.partyMemberDuty.dutybranch.service.DutyBranchEvaluationQuery; @Service("dutybranchevaluationServiceImpl") public class DutyBranchEvaluationServiceImpl implements IDutyBranchEvaluationService { @Autowired @Qualifier("dutybranchevaluationDao") private IDutyBranchEvaluationDao dutybranchevaluationDao; @Override public void addInfo(DutyBranchEvaluation dutybranchevaluation) throws NoAuthorizedFieldException { dutybranchevaluationDao.addInfo(dutybranchevaluation); } @Override public void updateInfo(DutyBranchEvaluation dutybranchevaluation) throws NoAuthorizedFieldException { dutybranchevaluationDao.updateInfo(dutybranchevaluation); } @Override public void deleteInfo(String[] entityIDs) throws NoAuthorizedFieldException { dutybranchevaluationDao.deleteInfo(entityIDs); } @Override public List<DutyBranchEvaluation> findInfoList(DutyBranchEvaluationQuery query) throws NoAuthorizedFieldException { return dutybranchevaluationDao.findInfoListByPage(query); } @Override public DutyBranchEvaluation findInfoById(String entityID) throws NoAuthorizedFieldException { return dutybranchevaluationDao.findInfoById(entityID); } @Override public void deleteDutyBranch(DutyBranchEvaluationQuery query) throws NoAuthorizedFieldException { dutybranchevaluationDao.deleteDutyBranch(query); } @Override public void saveDutyScore(List<DutyScore> list, String dutyId) { dutybranchevaluationDao.deleteDutyScore(list,dutyId); dutybranchevaluationDao.saveDutyScore(list,dutyId); } }
package com.google.cacheserver; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.naming.OperationNotSupportedException; public class CacheServer { public static void main(final String[] args) {new Thread(){ public void run(){ try { new CacheServer().init(Integer.parseInt(args[0])); } catch (IOException e) { e.printStackTrace(); } } }.start(); } private void init(int port) throws IOException{ final ExecutorService executor = Executors.newFixedThreadPool(1000); final ServerSocket serverSocket = new ServerSocket(port, 128); try { while(true){ executor.submit(new ServerJob(serverSocket.accept())); } } catch (IOException e) { e.printStackTrace(); } } private static class ServerJob implements Runnable{ final Socket socket; ServerJob(Socket socket){ this.socket = socket; } @Override public void run(){ InputStream is = null; OutputStream outStream = null; try { is = socket.getInputStream(); BufferedReader stream = new BufferedReader( new InputStreamReader(is)); String line; //Serialzation type Serializer serializer = null; Operations.OPCODE opcode = null; String data = null; //Read input data while( (line = stream.readLine())!=null){ // System.out.println(line); if(line.equals("EOM")) break; if(line.startsWith("Type")){ serializer = Utils.newSerializerFactory(line); }else if(line.startsWith("OP")){ opcode = Utils.newOperationsFactory(line); }else if(line.startsWith("Data")){ data = line.substring(5); } } //Deserialize CacheEntry entry = serializer.deserialize(data); //put cache CacheProvider provider = new BasicCache(); Integer retVal=-1; if(opcode == Operations.OPCODE.PUT){ provider.put(entry); }else if (opcode == Operations.OPCODE.GET){ retVal = (provider.get(entry).getValue()!=null)? provider.get(entry).getValue(): -1; } System.out.println(opcode+" "+retVal); outStream = new PrintStream(socket.getOutputStream()); outStream.write(("Response: "+retVal.toString()).getBytes()); } catch (IOException e) { e.printStackTrace(); } catch (OperationNotSupportedException e) { e.printStackTrace(); } catch(Exception e){ e.printStackTrace(); }finally{ try { if(outStream!=null) {outStream.flush(); outStream.close();} if(is!=null) {is.close();} } catch (Exception e) { e.printStackTrace(); } } } } }
package ioccontainer.materials; import ioccontainer.CreateOnTheFly; public class DiamondDependencyBean { @CreateOnTheFly private DiamondDependency dependency; @CreateOnTheFly private DiamondDependency anotherDependency; public DiamondDependency getDependency() { return dependency; } public void setDependency(DiamondDependency dependency) { this.dependency = dependency; } public DiamondDependency getAnotherDependency() { return anotherDependency; } public void setAnotherDependency(DiamondDependency anotherDependency) { this.anotherDependency = anotherDependency; } }
/* * Copyright (C) 2009 - 2015 Marko Salmela, http://fuusio.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fuusio.api.db; public enum Tables implements TableDescriptor, TablesDescriptor { TABLE_FOO("Foo", null); private final String mName; private final ColumnDescriptor[] mColumnDescriptors; private Tables(final String name, final ColumnDescriptor[] columnDescriptors) { mName = name; mColumnDescriptors = columnDescriptors; } public final ColumnDescriptor[] getColumnDescriptors() { return mColumnDescriptors; } public final String getName() { return mName; } @Override public TableDescriptor[] getTableDescriptors() { return values(); } }
package playground.ds; import playground.ds.interfaces.VectorAPI; import java.util.Arrays; public class Vector implements VectorAPI { int[] arr; int capacity; int length; final int MIN_CAPACITY = 16; public Vector() { this.capacity = MIN_CAPACITY; this.arr = new int[capacity]; this.length = 0; } public Vector(int... arr) { int base = (int) (Math.log(arr.length) / Math.log(2)); int nextBestCapacity = (int) Math.pow(2, base + 1); int maxCapacity = Math.max(MIN_CAPACITY, nextBestCapacity); this.length = arr.length; this.arr = arr; resize(maxCapacity); } @Override public int size() { return this.length; } @Override public int capacity() { return this.capacity; } @Override public boolean isEmpty() { return this.length == 0; } @Override public int at(int index) { return arr[index]; } @Override public void push(int element) { if (length >= capacity) { resize(capacity * 2); } arr[length++] = element; } @Override public void insert(int index, int item) { if (length >= capacity) { resize(capacity * 2); } for (int i = length; i > index; i--) { arr[i] = arr[i - 1]; } arr[index] = item; length++; } @Override public void prepend(int item) { insert(0, item); } @Override public int pop() { if (isEmpty()) { System.out.println("Error: Vector empty"); return -1; } int valueToDelete = arr[length - 1]; arr[length - 1] = 0; length--; if (length < (int) (.25 * capacity)) { resize(capacity / 2); } return valueToDelete; } @Override public int delete(int index) { if (isEmpty()) { System.out.println("Error: Vector empty"); return -1; } int valueToDelete = arr[index]; for (int i = index + 1; i < length; i++) { arr[i - 1] = arr[i]; } pop(); return valueToDelete; } @Override public int remove(int item) { if (isEmpty()) { System.out.println("Error: Vector empty"); return -1; } int writePtr = 0; for (int readPtr = 0; readPtr < length; readPtr++) { if (arr[readPtr] != item) { arr[writePtr++] = arr[readPtr]; } } int itemsDeleted = 0; int originalLength = length; while (writePtr < originalLength) { itemsDeleted++; writePtr++; pop(); } return itemsDeleted; } @Override public int find(int item) { for (int i = 0; i < length; i++) { if (item == arr[i]) return i; } return -1; } @Override public void resize(int newCapacity) { int lengthOfArrayToCopy = size(); if (newCapacity < size()) { lengthOfArrayToCopy = newCapacity; } int[] tempArr = new int[newCapacity]; System.arraycopy(this.arr, 0, tempArr, 0, lengthOfArrayToCopy); this.arr = tempArr; this.capacity = newCapacity; } @Override public String toString() { return "Vector{" + "arr=" + Arrays.toString(arr) + ", capacity=" + capacity + ", length=" + length + '}'; } }
/******************************************************************************* * Copyright 2020 Grégoire Martinetti * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package org.gmart.devtools.java.serdes.codeGen.javaGen.model; import java.util.Optional; import org.gmart.devtools.java.serdes.codeGen.javaGen.model.reporting.NonOptionalNotInitializedCollection; public class DeserialContextImpl implements DeserialContext { private Object fileRootObject; public void setFileRootObject(Object fileRootObject) { this.fileRootObject = fileRootObject; } public DeserialContextImpl() { super(); } @Override public Object getFileRootObject() { return fileRootObject; } NonOptionalNotInitializedCollection nonOptionalNotInitializedCollection = new NonOptionalNotInitializedCollection(); @Override public NonOptionalNotInitializedCollection getNonOptionalNotInitializedCollection() { return nonOptionalNotInitializedCollection; } public Optional<String> buildReport() { return nonOptionalNotInitializedCollection.buildReport(); } // Stack<HostClassWithConstructorArgs> hostClassContextStack = new Stack<>(); // @Override // public <T> T pushConstructorArgs(AbstractClassDefinition hostClass, List<Function<List<Object>, Optional<Object>>> args, Supplier<T> callBack) { // hostClassContextStack.add(new HostClassWithConstructorArgs(hostClass, args)); // T t = callBack.get(); // hostClassContextStack.pop(); // return t; // } // @Override // public HostClassWithConstructorArgs getHostClassContext() { // return hostClassContextStack.peek(); // } }
package com.google.firebase.example.appindexing; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.Task; import com.google.firebase.appindexing.Action; import com.google.firebase.appindexing.FirebaseAppIndex; import com.google.firebase.appindexing.FirebaseUserActions; import com.google.firebase.appindexing.Indexable; import com.google.firebase.appindexing.builders.Indexables; import com.google.firebase.example.appindexing.model.Note; import com.google.firebase.example.appindexing.model.Recipe; public class MainActivity extends AppCompatActivity { private Note mNote; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } // [START appindexing_onstart_onstop] @Override protected void onStart() { super.onStart(); // If you’re logging an action on content that hasn’t been added to the index yet, // add it first. // See <a href="https://firebase.google.com/docs/app-indexing/android/personal-content#update-the-index">https://firebase.google.com/docs/app-indexing/android/personal-content#update-the-index</a>. FirebaseUserActions.getInstance().start(getRecipeViewAction()); } @Override protected void onStop() { FirebaseUserActions.getInstance().end(getRecipeViewAction()); super.onStop(); } // [END appindexing_onstart_onstop] // [START appindexing_instantaneous] public void displayNoteDialog(final String positiveText, final String negativeText) { // ... // If you’re logging an action on content that hasn’t been added to the index yet, // add it first. // See <a href="https://firebase.google.com/docs/app-indexing/android/personal-content#update-the-index">https://firebase.google.com/docs/app-indexing/android/personal-content#update-the-index</a>. FirebaseUserActions.getInstance().end(getNoteCommentAction()); // ... } public Action getNoteCommentAction() { return new Action.Builder(Action.Builder.COMMENT_ACTION) .setObject(mNote.getTitle(), mNote.getNoteUrl()) // Keep action data for personal connulltent on the device .setMetadata(new Action.Metadata.Builder().setUpload(false)) .build(); } // [END appindexing_instantaneous] // [START appindexing_update] public void indexNote(Recipe recipe) { Note note = recipe.getNote(); Indexable noteToIndex = Indexables.noteDigitalDocumentBuilder() .setName(recipe.getTitle()) .setText(note.getText()) .setUrl(recipe.getNoteUrl()) .build(); Task<Void> task = FirebaseAppIndex.getInstance().update(noteToIndex); // ... } // [END appindexing_update] private void removeNote(Recipe recipe) { // [START appindexing_remove_one] // Deletes or removes the corresponding notes from index. String noteUrl = recipe.getNoteUrl(); FirebaseAppIndex.getInstance().remove(noteUrl); // [END appindexing_remove_one] } public void removeAll() { // [START appindexing_remove_all] FirebaseAppIndex.getInstance().removeAll(); // [END appindexing_remove_all] } public Action getRecipeViewAction() { // This is just to make some things compile. return null; } }
package za.co.edusys.domain; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; import za.co.edusys.domain.model.*; import za.co.edusys.domain.model.Class; import za.co.edusys.domain.model.details.Address; import za.co.edusys.domain.model.details.ContactDetails; import za.co.edusys.domain.model.event.Event; import za.co.edusys.domain.model.event.EventItem; import za.co.edusys.domain.model.event.EventStatus; import za.co.edusys.domain.model.event.EventType; import za.co.edusys.domain.repository.*; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; @Component public class DataLoader implements ApplicationRunner { private UserRepository userRepository; private AuthorityRepository authorityRepository; private SchoolRepository schoolRepository; private MenuItemRepository menuItemRepository; private ClassRepository classRepository; private TermRepository termRepository; private EventRepository eventRepository; private EventItemRepository eventItemRepository; @Autowired public DataLoader(UserRepository userRepository, AuthorityRepository authorityRepository, SchoolRepository schoolRepository, MenuItemRepository menuItemRepository, ClassRepository classRepository, TermRepository termRepository, EventRepository eventRepository, EventItemRepository eventItemRepository) { this.userRepository = userRepository; this.authorityRepository = authorityRepository; this.schoolRepository = schoolRepository; this.menuItemRepository = menuItemRepository; this.classRepository = classRepository; this.termRepository = termRepository; this.eventRepository = eventRepository; this.eventItemRepository = eventItemRepository; } @Override public void run(ApplicationArguments applicationArguments) throws Exception { authorityRepository.save(new Authorities("ADMIN")); menuItemRepository.save(new MenuItem("User Admin", "user", Arrays.asList(Role.ADMIN, Role.SUPERADMIN))); menuItemRepository.save(new MenuItem("School Admin", "school", Arrays.asList(Role.SUPERADMIN))); menuItemRepository.save(new MenuItem("Main Admin", "", Arrays.asList(Role.ADMIN, Role.SUPERADMIN))); menuItemRepository.save(new MenuItem("Class Admin", "class", Arrays.asList(Role.ADMIN, Role.SUPERADMIN))); schoolRepository.save(new School("RedHill High School", true, Grade.getHighSchool(), Arrays.asList(Subject.values()))); schoolRepository.save(new School("Crawford College Benmore", true, Grade.getHighSchool(), Arrays.asList(Subject.values()))); termRepository.save(new Term("Term 1", LocalDate.of(2017,2,1), LocalDate.of(2017,4,1), schoolRepository.findOneByName("RedHill High School"))); termRepository.save(new Term("Term 1", LocalDate.of(2017,2,1), LocalDate.of(2017,4,1), schoolRepository.findOneByName("Crawford College Benmore"))); userRepository.save(new User("admin", "admin", "admin", "admin", Role.ADMIN, schoolRepository.findOne(1L), null, new ContactDetails("0116781000","0116781000","0116781000","0116781000"), new Address("137A Cedar Place", null, "Northcliff", "Randburg", "South Africa", "2196"))); userRepository.save(new User("superadmin", "superadmin", "superadmin", "superadmin", Role.SUPERADMIN, null, null)); userRepository.save(new User("MarcTest", "marctest", "Marc", "Marais", Role.ADMIN, schoolRepository.findOne(1L), null)); userRepository.save(new User("Test1", "1", "Test1", "Test1", Role.TEACHER, schoolRepository.findOne(1L), null)); userRepository.save(new User("Test2", "2", "Test2", "Test2", Role.PARENT, null, null)); userRepository.save(new User("Test3", "3", "Test3", "Test3", Role.PUPIL, schoolRepository.findOne(1L), Grade.Grade_10)); userRepository.save(new User("Test4", "4", "Test4", "Test4", Role.PUPIL, schoolRepository.findOne(1L), Grade.Grade_10)); classRepository.save(new Class("Class A", schoolRepository.findOne(1L), userRepository.findOne(4L), Subject.ENGLISH, Grade.Grade_10, Arrays.asList(userRepository.findOne(6L), userRepository.findOne(7L)), null)); eventRepository.save(new Event("Test 1", EventType.TEST, Arrays.asList(EventStatus.values()), EventStatus.CLOSED, "Test 1", Arrays.asList(classRepository.findOne(1L)), LocalDateTime.of(2017,3,6,11,30), LocalDateTime.of(2017,3,6,1,30), 80)); eventItemRepository.save(new EventItem(EventStatus.OPEN, eventRepository.findOne(1L), userRepository.findOne(6L), LocalDateTime.of(2017,3,9,11,30), LocalDateTime.of(2017,3,9,12,30), "40")); eventItemRepository.save(new EventItem(EventStatus.OPEN, eventRepository.findOne(1L), userRepository.findOne(7L), LocalDateTime.of(2017,3,9,11,30), LocalDateTime.of(2017,3,9,12,30), "70")); eventItemRepository.save(new EventItem(EventStatus.OPEN, eventRepository.findOne(1L), userRepository.findOne(4L), LocalDateTime.of(2017,3,9,11,30), LocalDateTime.of(2017,3,9,12,30), null)); } }
package com.salesforce.cdp.queryservice.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; @Data @JsonIgnoreProperties(ignoreUnknown = true) public class QueryConfigResponse { String queryengine; }
import server.Billboard; import java.io.*; public class Test { public static void main(String args[]) throws IOException, ClassNotFoundException { } }
package com.df.parcial_uno; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import Models.Producto; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private EditText codigo; private EditText nombreProducto; private EditText valor; private EditText exento; private EditText categoria; private EditText descripcion; private Button btnAgregar; private Button btnExento; private Button btnMasCostoso; private Button btnMenosCostoso; private ListView respuesta; public ArrayList<Producto> listaProducto = new ArrayList<Producto>(); private ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); codigo = findViewById(R.id.txtCodigo); nombreProducto = findViewById(R.id.txtProducto); valor = findViewById(R.id.txtValor); exento = findViewById(R.id.txtExento); categoria = findViewById(R.id.txtCategoria); descripcion = findViewById(R.id.txtDescripcion); btnAgregar = findViewById(R.id.btnAgregar); btnExento = findViewById(R.id.btnExento); btnMasCostoso = findViewById(R.id.btnMasCostosos); btnMenosCostoso = findViewById(R.id.btnMenosCostoso); respuesta = findViewById(R.id.lvRespuesta); btnAgregar.setOnClickListener(this); btnExento.setOnClickListener(this); btnMenosCostoso.setOnClickListener(this); btnMasCostoso.setOnClickListener(this); } @Override public void onClick(View v) { if (v.getId() == R.id.btnAgregar) { agregarProducto(); limpiarTexto(); } else if (v.getId() == R.id.btnMasCostosos) { ordenarListaProducto(); Collections.reverse(listaProducto); ArrayList<String> masCostoso = new ArrayList<>(); String masCosto = "10 Productos más costosos: \n"; for (int i = 0; i < listaProducto.size(); i++){ if (!listaProducto.get(i).toString().isEmpty()) { masCosto = listaProducto.get(i).getNombreProducto() + ": " +listaProducto.get(i).getValor(); masCostoso.add(masCosto); } } getAdapter(masCostoso); } else if (v.getId() == R.id.btnMenosCostoso) { ordenarListaProducto(); ArrayList<String> menosCostoso = new ArrayList<>(); String menosCosto = "10 Productos más costosos: \n"; for (int i = 0; i < listaProducto.size(); i++){ if (!listaProducto.get(i).toString().isEmpty()) { menosCosto = listaProducto.get(i).getNombreProducto() + ": " + listaProducto.get(i).getValor(); menosCostoso.add(menosCosto); } } getAdapter(menosCostoso); } else if (v.getId() == R.id.btnExento) { Intent myIntent = new Intent(this, Exento.class); Bundle bundle = new Bundle(); bundle.putParcelableArrayList("Productos", listaProducto); myIntent.putExtras(bundle); startActivity(myIntent); } } private void getAdapter(ArrayList<String> list) { adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list); respuesta.setAdapter(adapter); } private void ordenarListaProducto() { Collections.sort(listaProducto, new Comparator<Producto>() { @Override public int compare(Producto o1, Producto o2) { return new Double(o1.getValor()).compareTo(new Double(o2.getValor())); } }); } private void limpiarTexto(){ codigo.setText(""); nombreProducto.setText(""); valor.setText(""); exento.setText(""); categoria.setText(""); descripcion.setText(""); } private void agregarProducto(){ String _codigo = codigo.getText().toString(); String _nombreProducto = nombreProducto.getText().toString(); double _valor = Double.parseDouble(valor.getText().toString()); String _exento = exento.getText().toString().toLowerCase(); String _categoria = categoria.getText().toString(); String _descripcion = descripcion.getText().toString(); Producto producto = new Producto(_codigo, _nombreProducto, _valor, _exento, _categoria, _descripcion); listaProducto.add(producto); } }
package com.codezjsos.log.entity; import org.hibernate.annotations.GenericGenerator; import java.util.Date; import javax.persistence.*; @Entity @Table(name="tracklog_entity") public class TrackLogEntity extends TrackBase{ private String optiontype; private String createid; private String classname; public String getCreateid() { return createid; } public void setCreateid(String createid) { this.createid = createid; } public String getClassname() { return classname; } public void setClassname(String classname) { this.classname = classname; } public String getOptiontype() { return optiontype; } public void setOptiontype(String optiontype) { this.optiontype = optiontype; } }
package operations.graphoperations; import graphana.UserInterface; import graphana.graphs.GraphLibrary; import graphana.operationsystem.GraphOperation; import graphana.operationsystem.OperationArguments; import graphana.operationsystem.OperationDescFile; import graphana.operationsystem.OperationGroup; import graphana.script.bindings.basictypes.GEdge; import graphana.script.bindings.basictypes.GVertex; import scriptinterface.defaulttypes.*; import scriptinterface.execution.returnvalues.ExecutionErrorMessage; import scriptinterface.execution.returnvalues.ExecutionResult; import scriptinterface.execution.returnvalues.ExecutionReturn; import java.util.LinkedList; public class GrOpsGraphElements extends OperationGroup implements OperationDescFile { public GraphOperation[] getOperations() { return new GraphOperation[]{new ExecGetVertexByIdent(), new ExecVertexExists(), new ExecGetEdge(), new ExecGetEdgeByIdent(), new ExecEdgeExists(), new ExecGetNeighbours(), new ExecGetNeighbourCount(), new ExecGetVertexData(), new ExecHasVertexData(), new ExecGetVertexStatus(), new ExecIsVertexStatusSet(), new ExecSetVertexData(), new ExecSetVertexStatus(), new ExecDeleteVertexData(), new ExecDeleteVertexStatus(), new ExecGetEdgeData(), new ExecHasEdgeData(), new ExecGetEdgeStatus(), new ExecIsEdgeStatusSet(), new ExecSetEdgeData(), new ExecSetEdgeStatus(), new ExecDeleteEdgeData(), new ExecDeleteEdgeStatus(), new ExecMarkVertexAsDeleted(), new ExecIsVertexMarkedAsDeleted(), new ExecMarkEdgeAsDeleted(), new ExecIsEdgeMarkedAsDeleted(), new ExecRemoveVertexDeletionMark(), new ExecRemoveEdgeDeletionMark(), new ExecVerticesToSet(), new ExecEdgesToSet(), new ExecDeleteVertexStates(), new ExecDeleteVertexDates(), new ExecDeleteEdgeStates(), new ExecDeleteEdgeDates()}; } @Override public String getDescriptionFilename() { return GROPDIR + "graphelements.xml"; } private class ExecGetVertexByIdent extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { VertexType vertex = graph.getVertexByIdent(args.getStringArg(0), args.getBoolArg(1)); if (vertex == null) return new ExecutionErrorMessage("The graph does not contain a vertex '" + args.getStringArg(0) + "'."); else return new GVertex<>(vertex); } @Override protected String getSignatureString() { return "getVertexByIdent|getVertexByIdentifier|getVertex (vertexIdentifier:String; " + "addAutomatically:Boolean) : Vertex"; } } private class ExecVertexExists extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { return GBoolean.create(graph.vertexExistsByIdent(args.getStringArg(0))); } @Override protected String getSignatureString() { return "vertexExists (vertexIdentifier:String) : Boolean"; } } private class ExecGetEdge extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { VertexType vertex1 = args.getVertexArg(0); VertexType vertex2 = args.getVertexArg(1); EdgeType edge = graph.getEdge(vertex1, vertex2); if (edge == null) return new ExecutionErrorMessage("In the graph, there is no edge connecting '" + graph.getVertexIdent (vertex1) + "' and '" + graph.getVertexIdent(vertex2) + "'."); return new GEdge<>(graph, edge); } @Override protected String getSignatureString() { return "getEdge (vertex1:Vertex; vertex2:Vertex) : Edge"; } } private class ExecGetEdgeByIdent extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { VertexType vertex1 = graph.getVertexByIdent(args.getStringArg(0), false); VertexType vertex2 = graph.getVertexByIdent(args.getStringArg(1), false); if (vertex1 == null) return new ExecutionErrorMessage("The graph does not contain a vertex '" + args.getStringArg(0) + "'."); if (vertex2 == null) return new ExecutionErrorMessage("The graph does not contain a vertex '" + args.getStringArg(1) + "'."); EdgeType edge = graph.getEdge(vertex1, vertex2); if (edge == null) return new ExecutionErrorMessage("In the graph, there is no edge connecting '" + graph.getVertexIdent (vertex1) + "' and '" + graph.getVertexIdent(vertex2) + "'."); return new GEdge<>(graph, edge); } @Override protected String getSignatureString() { return "getEdgeByIdent|getEdgeByIdentifiers (vertexIdentifier1:String; vertexIdentifier2:String) : Edge"; } } private class ExecEdgeExists extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { VertexType vertex1 = args.getVertexArg(0); VertexType vertex2 = args.getVertexArg(1); return GBoolean.create(graph.edgeExists(vertex1, vertex2)); } @Override protected String getSignatureString() { return "edgeExists|connected (vertex1:Vertex; vertex2:Vertex) : Boolean"; } } private class ExecGetNeighbours extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { LinkedList<ExecutionResult<?>> res = new LinkedList<>(); VertexType vertex = args.getVertexArg(0); for (VertexType neighbour : graph.getNeighbors(vertex)) res.add(args.getOriginalGVertex(graph, neighbour)); return new GList(res); } @Override protected String getSignatureString() { return "getNeighbors|getNeighbours (vertex:Vertex) : List"; } } private class ExecGetNeighbourCount extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { VertexType vertex = args.getVertexArg(0); return new GInteger(new Integer(graph.getNeighborCount(vertex))); } @Override protected String getSignatureString() { return "getNeighborCount|getNeighbourCount|getDegree|getVertexDegree (vertex:Vertex) : Integer"; } } private class ExecGetVertexData extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { VertexType vertex = args.getVertexArg(0); Object data = graph.getVertexData(vertex); if (data == null) return new ExecutionErrorMessage("The vertex '" + graph.getVertexIdent(vertex) + "' has no data."); else return new GObject(data); } @Override protected String getSignatureString() { return "getVertexData (vertex:Vertex) : Object"; } } private class ExecHasVertexData extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { VertexType vertex = args.getVertexArg(0); return GBoolean.create(graph.hasVertexData(vertex)); } @Override protected String getSignatureString() { return "hasVertexData (vertex:Vertex) : Boolean"; } } private class ExecGetVertexStatus extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { VertexType vertex = args.getVertexArg(0); Object data = graph.getVertexStatus(vertex); if (data == null) return new ExecutionErrorMessage("The status of the vertex '" + graph.getVertexIdent(vertex) + "' is " + "" + "" + "" + "not set."); else return new GObject(data); } @Override protected String getSignatureString() { return "getVertexStatus (vertex:Vertex) : Object"; } } private class ExecIsVertexStatusSet extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { VertexType vertex = args.getVertexArg(0); return GBoolean.create(graph.isVertexStatusSet(vertex)); } @Override protected String getSignatureString() { return "isVertexStatusSet|hasVertexStatus (vertex:Vertex) : Boolean"; } } private class ExecSetVertexData extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { VertexType vertex = args.getVertexArg(0); graph.setVertexData(vertex, args.getObjectArg(1)); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "setVertexData (vertex:Vertex; data:Any) : void"; } } private class ExecSetVertexStatus extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { VertexType vertex = args.getVertexArg(0); graph.setVertexStatus(vertex, args.getObjectArg(1)); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "setVertexStatus (vertex:Vertex; status:Any=true) : void"; } } private class ExecDeleteVertexData extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { VertexType vertex = args.getVertexArg(0); graph.clearVertexData(vertex, args.getBoolArg(1)); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "deleteVertexData|clearVertexData (vertex:Vertex; includeIncidentEdges:Boolean=false) : void"; } } private class ExecDeleteVertexStatus extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { VertexType vertex = args.getVertexArg(0); graph.clearVertexStatus(vertex, args.getBoolArg(1)); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "deleteVertexStatus|clearVertexStatus (vertex:Vertex; includeIncidentEdges:Boolean=false) : void"; } } private class ExecDeleteVertexStates extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { graph.clearVertexStates(true); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "deleteVertexStates|clearVertexStates () : void"; } } private class ExecDeleteVertexDates extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { graph.clearVertexDates(); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "deleteVertexDates|clearVertexDates () : void"; } } private class ExecDeleteEdgeStates extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { graph.clearEdgeStates(true); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "deleteEdgeStates|clearEdgeStates () : void"; } } private class ExecDeleteEdgeDates extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { graph.clearEdgeDates(); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "deleteEdgeDates|clearEdgeDates () : void"; } } private class ExecRemoveVertexDeletionMark extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { VertexType vertex = args.getVertexArg(0); graph.removeVertexDeletionMark(vertex, args.getBoolArg(1)); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "removeVertexDeletionMark|removeVertexDeletion (vertex:Vertex; includeIncidentEdges:Boolean=true) " + "" + "" + "" + ": void"; } } private class ExecRemoveEdgeDeletionMark extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { EdgeType edge = args.getEdgeArg(0); graph.removeEdgeDeletionMark(edge); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "removeEdgeDeletionMark|removeEdgeDeletion (edge:Edge) : void"; } } private class ExecGetEdgeData extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { EdgeType edge = args.getEdgeArg(0); Object data = graph.getEdgeData(edge); if (data == null) return new ExecutionErrorMessage("The edge '" + graph.edgeToString(edge) + "' has no data."); else return new GObject(data); } @Override protected String getSignatureString() { return "getEdgeData (edge:Edge) : Object"; } } private class ExecHasEdgeData extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { EdgeType edge = args.getEdgeArg(0); return GBoolean.create(graph.hasEdgeData(edge)); } @Override protected String getSignatureString() { return "hasEdgeData (edge:Edge) : Boolean"; } } private class ExecGetEdgeStatus extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { EdgeType edge = args.getEdgeArg(0); Object data = graph.getEdgeStatus(edge); if (data == null) return new ExecutionErrorMessage("The status of the edge '" + graph.edgeToString(edge) + "' is not " + "set."); else return new GObject(data); } @Override protected String getSignatureString() { return "getEdgeStatus (edge:Edge) : Object"; } } private class ExecIsEdgeStatusSet extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { EdgeType edge = args.getEdgeArg(0); return GBoolean.create(graph.isEdgeStatusSet(edge)); } @Override protected String getSignatureString() { return "isEdgeStatusSet|hasEdgeStatus (edge:Edge) : Boolean"; } } private class ExecSetEdgeData extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { EdgeType edge = args.getEdgeArg(0); graph.setEdgeData(edge, args.getObjectArg(1)); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "setEdgeData (edge:Edge; data:Any) : void"; } } private class ExecSetEdgeStatus extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { EdgeType edge = args.getEdgeArg(0); graph.setEdgeStatus(edge, args.getObjectArg(1)); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "setEdgeStatus (edge:Edge; status:Any=true) : void"; } } private class ExecDeleteEdgeData extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { EdgeType edge = args.getEdgeArg(0); graph.clearEdgeData(edge); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "deleteEdgeData|clearEdgeData (edge:Edge) : void"; } } private class ExecDeleteEdgeStatus extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { EdgeType edge = args.getEdgeArg(0); graph.clearEdgeStatus(edge); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "deleteEdgeStatus|clearEdgeStatus (edge:Edge) : void"; } } private class ExecMarkVertexAsDeleted extends GraphOperation { @SuppressWarnings("unchecked") @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { graph.markVertexAsDeleted((VertexType) args.getVertexArg(0), args.getBoolArg(1)); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "markVertexAsDeleted|markVertexDeleted (vertex:Vertex; includeEdges:Boolean=true) : void"; } } private class ExecIsVertexMarkedAsDeleted extends GraphOperation { @SuppressWarnings("unchecked") @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { return GBoolean.create(graph.isVertexMarkedAsDeleted((VertexType) args.getVertexArg(0))); } @Override protected String getSignatureString() { return "isVertexMarkedAsDeleted|isVertexMarkedDeleted (vertex:Vertex) : Boolean"; } } private class ExecMarkEdgeAsDeleted extends GraphOperation { @SuppressWarnings("unchecked") @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { graph.markEdgeAsDeleted((EdgeType) args.getEdgeArg(0)); return ExecutionReturn.VOID; } @Override protected String getSignatureString() { return "markEdgeAsDeleted|markEdgeDeleted (edge:Edge) : void"; } } private class ExecIsEdgeMarkedAsDeleted extends GraphOperation { @SuppressWarnings("unchecked") @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { return GBoolean.create(graph.isEdgeMarkedAsDeleted((EdgeType) args.getEdgeArg(0))); } @Override protected String getSignatureString() { return "isEdgeMarkedAsDeleted|isEdgeMarkedDeleted (edge:Edge) : Boolean"; } } private class ExecVerticesToSet extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { GSet result = new GSet(); for (VertexType vertex : graph.getVertices()) { result.add(new GVertex<>(vertex)); } return result; } @Override protected String getSignatureString() { return "verticesToSet|getVertexSet () : Set"; } } private class ExecEdgesToSet extends GraphOperation { @Override protected <VertexType, EdgeType> ExecutionReturn execute(GraphLibrary<VertexType, EdgeType> graph, UserInterface userInterface, OperationArguments args) { GSet result = new GSet(); for (EdgeType edge : graph.getEdges()) { result.add(new GEdge<>(graph, edge)); } return result; } @Override protected String getSignatureString() { return "edgesToSet|getEdgeSet () : Set"; } } }
package com.tencent.mm.plugin.honey_pay.ui; import android.content.Intent; import android.os.Bundle; import android.text.SpannableString; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.tencent.mm.ab.l; import com.tencent.mm.model.q; import com.tencent.mm.plugin.honey_pay.a.e; import com.tencent.mm.plugin.honey_pay.a.m; import com.tencent.mm.plugin.wxpay.a; import com.tencent.mm.plugin.wxpay.a.c; import com.tencent.mm.plugin.wxpay.a.f; import com.tencent.mm.pluginsdk.ui.a.b; import com.tencent.mm.pluginsdk.ui.applet.CdnImageView; import com.tencent.mm.pluginsdk.ui.d.g; import com.tencent.mm.pluginsdk.ui.d.j; import com.tencent.mm.protocal.c.amp; import com.tencent.mm.protocal.c.bdk; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.wallet_core.c.h$a; import com.tencent.mm.wallet_core.c.v; import com.tencent.mm.wallet_core.ui.WalletTextView; public class HoneyPayReceiveCardUI extends HoneyPayBaseUI { private int fdx; private String kkc; private ImageView klP; private TextView klQ; private WalletTextView klR; private TextView klS; private TextView klT; private TextView klU; private TextView klV; private TextView klW; private TextView klX; private TextView klY; private LinearLayout klZ; private CdnImageView kma; private g kmb = new 1(this); static /* synthetic */ void b(HoneyPayReceiveCardUI honeyPayReceiveCardUI) { x.i(honeyPayReceiveCardUI.TAG, "go to honey pay card detail"); Intent intent = new Intent(honeyPayReceiveCardUI, HoneyPayCardDetailUI.class); intent.putExtra("key_scene", 0); intent.putExtra("key_card_no", honeyPayReceiveCardUI.kkc); honeyPayReceiveCardUI.startActivity(intent); } public void onCreate(Bundle bundle) { this.kjV = c.honey_pay_grey_bg_2; super.onCreate(bundle); j.a(this.kmb); jr(2613); jr(1983); this.kkc = getIntent().getStringExtra("key_card_no"); this.fdx = getIntent().getIntExtra("key_scene", 0); initView(); if (this.fdx == 1) { bdk bdk = new bdk(); try { bdk.aG(getIntent().getByteArrayExtra("key_qry_response")); a(bdk); if (bdk.rIz != null) { setMMTitle(bdk.rIz.hwg); return; } return; } catch (Throwable e) { x.printErrStackTrace(this.TAG, e, "", new Object[0]); aWf(); return; } } aWf(); } protected final void initView() { this.klP = (ImageView) findViewById(f.hprc_avatar_iv); this.klQ = (TextView) findViewById(f.hprc_payer_name_tv); this.klW = (TextView) findViewById(f.hprc_user_name_tv); this.klR = (WalletTextView) findViewById(f.hprc_quota_tv); this.klS = (TextView) findViewById(f.hprc_quota_desc_tv); this.klT = (TextView) findViewById(f.hprc_check_payway_tv); this.klU = (TextView) findViewById(f.hprc_receive_btn); this.klV = (TextView) findViewById(f.hprc_receive_tip_tv); this.klZ = (LinearLayout) findViewById(f.hprc_quota_layout); this.klX = (TextView) findViewById(f.hprc_wishing_tv); this.klY = (TextView) findViewById(f.hprc_explain_tv); this.kma = (CdnImageView) findViewById(f.hprc_quota_logo_1_iv); this.klR.setPrefix(v.cDm()); this.klU.setOnClickListener(new 2(this)); } public void onDestroy() { super.onDestroy(); j.b(this.kmb); js(2613); js(1983); } public final boolean d(int i, int i2, String str, l lVar) { if (lVar instanceof m) { final m mVar = (m) lVar; mVar.a(new h$a() { public final void g(int i, int i2, String str, l lVar) { HoneyPayReceiveCardUI.this.a(mVar.kjN); } }).b(new 4(this)).c(new 3(this)); } else if (lVar instanceof e) { e eVar = (e) lVar; eVar.a(new 8(this, eVar)).b(new 7(this, eVar)).c(new 6(this)); } return true; } protected final int getLayoutId() { return a.g.honey_pay_receive_card_ui; } private void a(bdk bdk) { if (bdk.rIz != null) { amp amp = bdk.rIz; this.klV.setText(amp.rPn); this.klX.setText(j.a(this.mController.tml, amp.kLf, this.klX.getTextSize())); Bundle bundle = new Bundle(); bundle.putBoolean("click_help", true); this.klY.setText(j.a(this.mController.tml, amp.muD, (int) this.klY.getTextSize(), bundle)); this.klY.setClickable(true); this.klY.setOnTouchListener(new com.tencent.mm.pluginsdk.ui.d.m(this)); if (bi.oW(bdk.sda)) { x.d(this.TAG, "no help url"); this.klT.setVisibility(8); } else { com.tencent.mm.plugin.wallet_core.ui.m mVar = new com.tencent.mm.plugin.wallet_core.ui.m(new 9(this, bdk)); CharSequence spannableString = new SpannableString(bdk.sda); spannableString.setSpan(mVar, 0, spannableString.length(), 18); this.klT.setText(spannableString); this.klT.setOnTouchListener(new com.tencent.mm.pluginsdk.ui.d.m(this)); this.klT.setClickable(true); } this.klR.setText(com.tencent.mm.plugin.honey_pay.model.c.dK(amp.rPl)); b.a(this.klP, amp.qYy, 0.06f, false); com.tencent.mm.wallet_core.ui.e.f(this.klQ, amp.qYy); this.klW.setText(j.a(this, com.tencent.mm.wallet_core.ui.e.dx(q.GH(), 16), this.klW.getTextSize())); CdnImageView cdnImageView; int i; if (bi.oW(amp.lMY)) { cdnImageView = this.kma; i = amp.huV; cdnImageView.setImageResource(com.tencent.mm.plugin.honey_pay.model.c.aWc()); return; } cdnImageView = this.kma; String str = amp.lMY; i = amp.huV; cdnImageView.cS(str, com.tencent.mm.plugin.honey_pay.model.c.aWc()); } } private void aWf() { x.i(this.TAG, "qry user detail"); l mVar = new m(this.kkc); mVar.m(this); a(mVar, true, false); } }
package ru.krasview.kvlib.widget.lists; import android.content.Context; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.HashMap; import java.util.Map; import ru.krasview.kvlib.adapter.LoadDataToGUITask; import ru.krasview.kvlib.indep.Parser; import ru.krasview.kvlib.indep.consts.TypeConsts; import ru.krasview.kvlib.widget.List; import ru.krasview.secret.ApiConst; public class AllGenreShowList extends List { String section; public AllGenreShowList(Context context,Map<String, Object> map){ super(context, map); section = (String)map.get("section"); } protected void setType(Map<String, Object> map) { map.put("type", section); } protected String getApiAddress() { return ApiConst.BASE+"/genres"; } @SuppressWarnings("unchecked") @Override public void parseData(String doc, LoadDataToGUITask task) { Document mDocument; mDocument = Parser.XMLfromString(doc); if(mDocument == null) { return; } mDocument.normalizeDocument(); NodeList nListChannel = mDocument.getElementsByTagName("unit"); int numOfChannel = nListChannel.getLength(); Map<String, Object> m; if(numOfChannel == 0) { m = new HashMap<>(); m.put("name", "<пусто>"); m.put("type", null); task.onStep(m); return; } for (int nodeIndex = 0; nodeIndex < numOfChannel; nodeIndex++) { Node locNode = nListChannel.item(nodeIndex); m = new HashMap<>(); m.put("id", Parser.getValue("id", locNode)); m.put("name", Parser.getValue("title", locNode)); m.put("type", section ); if(task.isCancelled()) { return; } task.onStep(m); } } }
package com.dominion.prog2.modules; import com.dominion.prog2.Driver; import com.dominion.prog2.game.Player; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.HPos; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.layout.GridPane; import javafx.util.Callback; import javafx.util.Duration; import java.util.ArrayList; import java.util.HashMap; public class GameOver extends Module { private Driver d; private Player p; private TableView<String> players; private ObservableList<String> nameScores; /** * Constructor for GameOver * Parent Class: Module * This is the screen where the final scores for each user is displayed * Players is the table where the scores will be kept * nameScores is the strings that are put in the tables ("*name* has a score of: *score*") * The plays have the option of quiting the whole game or going back to the lobby */ public GameOver(ObservableList<String> userNames, Player p, Driver d) { this.d = d; this.p = p; boolean host = d.name.equals(userNames.get(0)); GridPane root = new GridPane(); root.setPrefSize(400, 600); root.setAlignment(Pos.CENTER); Label end = new Label("Game Over"); end.setStyle("-fx-border-color: black;-fx-font-size: 25pt;"); GridPane.setHalignment(end, HPos.CENTER); root.add(end,0,0); players = new TableView<>(); nameScores = FXCollections.observableArrayList(); nameScores.add("Waiting for Scores..."); players.setItems(nameScores); players.setMaxSize(200,200); TableColumn<String,String> users = new TableColumn<>("User | Final Scores"); users.setPrefWidth(190); users.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<String, String>, ObservableValue<String>>() { public ObservableValue<String> call(TableColumn.CellDataFeatures<String, String> p) { return new ReadOnlyObjectWrapper(p.getValue()); } }); players.getColumns().addAll(users); root.add(players, 0,1); //Buttons GridPane buttons = new GridPane(); Button leave = new Button("Play again"); leave.setOnMouseClicked(a -> playAgainClicked()); buttons.add(leave, 0,0); Button quit = new Button("Quit Game"); quit.setOnMouseClicked(a -> System.exit(0)); buttons.add(quit, 1,0); GridPane.setHalignment(buttons, HPos.CENTER); root.add(buttons, 0,2); setScene(new Scene(root, 745, 700)); if(host) { Timeline timeline = new Timeline(new KeyFrame(Duration.millis(2000), a -> readyForScores())); timeline.play(); } } /** * The Host calls this method when they first get to this screen * This sends out a message to the players and says requesting scores */ private void readyForScores() { HashMap<String, String> ready = new HashMap<>(); ready.put("type", "readyScores"); d.broadcast(ready); } /** * The Play again Button has the player leave the lobby and go back to the Lobby List Screen * changes module in Driver to ChooseLobby(passes Driver, "Game Finished") */ private void playAgainClicked() { HashMap<String, String> result = d.simpleCommand("leave"); if(result.get("type").equals("accepted")) { d.setCurrentModule(new ChooseLobby(d, "Game Finished")); } else { System.exit(48); } } /** * The players broadcast a message that contains their name and their score, which they get from Player.getTotalScore() */ private void submitScores() { HashMap<String, String> submit = new HashMap<>(); submit.put("type", "submitScore"); submit.put("user", p.name); submit.put("score", ""+p.getTotalScore()); d.broadcast(submit); } /** * This method parses out the different messages that are passed to the client * Receives the "ready for scores" from host, which calls Submit scores * Receives the "submit Scores" from everyone, and adds their name and score to the table * @param server_msg the array list of hashmaps representing new messages from the server */ @Override public void serverMsg(ArrayList<HashMap<String, String>> server_msg) { for(HashMap<String, String> msg : server_msg) { switch (msg.get("type")) { case "readyScores": nameScores.clear(); submitScores(); break; case "submitScore": nameScores.add(msg.get("user") + " has a score of: " + msg.get("score")); break; } } } }
package com.mobica.rnd.parking.parkingbetests.support; import com.mobica.rnd.parking.parkingbetests.support.extractors.IDataExtractor; import com.mobica.rnd.parking.parkingbetests.support.extractors.RESTExtractor; import org.json.simple.JSONObject; /** * Created by int_eaja on 2017-08-04. */ public class TestSuiteExtender { private TestSuiteData suiteData; private RESTExtractor extractor; // TODO - dorobic mozliwosc korzystania z dowolnego extractora (tak jak dla test casow) public TestSuiteExtender(TestSuiteData suiteData) { this.suiteData = suiteData; this.extractor = new RESTExtractor(suiteData.getBaseURL()); } public TestSuiteExtender extractSuiteConfigurationJSONResponses(IDataExtractor extractor, String key) { JSONObject obj = suiteData.getConfigurationRequest(key); JSONObject[] responses = extractor.extractData(obj, key); suiteData.addConfigurationResponses(key, responses); return this; } public TestSuiteExtender extractSuiteConfigurationJSONResponses(String key) { JSONObject obj = suiteData.getConfigurationRequest(key); JSONObject[] responses = extractor.extractData(obj, key); suiteData.addConfigurationResponses(key, responses); return this; } public TestSuiteExtender extendSuiteConfigurationRequestQueryParam(String queryParamKey, String[] assignmentData, int index) { suiteData.extendSuiteConfigurationQueryParam(queryParamKey, assignmentData, index); return this; } public TestSuiteExtender extendSuiteConfigurationRequestBody(DataAssociationType assoType, String targetKey, String[] assignmentData, int[] indexesData) { suiteData.extendSuiteConfigurationRequestBody(assoType, targetKey, assignmentData, indexesData); return this; } }
/* * Copyright 2018 original authors * * 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 example.offers; import io.micronaut.runtime.Micronaut; import io.micronaut.runtime.event.annotation.EventListener; import io.micronaut.runtime.server.event.ServerStartupEvent; import io.micronaut.scheduling.TaskScheduler; import io.micronaut.scheduling.annotation.Async; import javax.inject.Singleton; import java.time.Duration; /** * @author graemerocher * @since 1.0 */ @Singleton public class Application { private final TaskScheduler taskScheduler; private final OffersRepository offersRepository; public Application( TaskScheduler taskScheduler, OffersRepository offersRepository) { this.taskScheduler = taskScheduler; this.offersRepository = offersRepository; } public static void main(String... args) { Micronaut.run(Application.class); } @EventListener @Async public void onStartup(ServerStartupEvent event) { offersRepository.createInitialOffers(); } }
package pe.gob.trabajo.repository; import pe.gob.trabajo.domain.Oficina; import org.springframework.stereotype.Repository; import org.springframework.data.jpa.repository.*; import java.util.List; /** * Spring Data JPA repository for the Oficina entity. */ @SuppressWarnings("unused") @Repository public interface OficinaRepository extends JpaRepository<Oficina, Long> { @Query("select oficina from Oficina oficina where oficina.nFlgactivo = true") List<Oficina> findAll_Activos(); }
package test3; public class Hero { public Hero() { System.out.println("Hero"); } }
package com.tencent.mm.plugin.brandservice.ui.b; import com.tencent.mm.protocal.c.avq; public final class b { public static String avq() { avq Qa = com.tencent.mm.an.b.Qa(); if (Qa == null || Qa.rsp == null || Qa.rYj != 0 || !com.tencent.mm.an.b.PY()) { return null; } return Qa.rsp; } }
package com.mrlittlenew.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class DemoController { protected static final Logger logger = LoggerFactory.getLogger(DemoController.class); @RequestMapping("/") String index() { logger.debug("index hello!!!"); return "Hello Spring Boot"; } @RequestMapping("/hello") String hello() { logger.debug("index hello!!!"); return "Hello Spring Boot"; } }
package com.tt.miniapp.locate; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.text.TextUtils; import com.tt.miniapp.maplocate.TMALocation; import com.tt.miniapp.permission.BrandPermissionUtils; import com.tt.miniapp.process.bridge.InnerHostProcessBridge; import com.tt.miniapp.secrecy.SecrecyManager; import com.tt.miniapphost.AppBrandLogger; import com.tt.miniapphost.process.callback.IpcCallback; import com.tt.miniapphost.process.data.CrossProcessDataEntity; import org.json.JSONObject; public class LocateCrossProcessRequester implements Handler.Callback { public static volatile TMALocation sCachedLocation; private Handler handler; boolean isLocateFinished; private String mCallApi; private LocateResultCallbck mCallback; private IpcCallback mIPCCallback; private long mTimeoutForLocate; public LocateCrossProcessRequester(String paramString) { this.mCallApi = paramString; this.handler = new Handler(Looper.getMainLooper(), this); this.mIPCCallback = new IpcCallback() { public void onIpcCallback(CrossProcessDataEntity param1CrossProcessDataEntity) { AppBrandLogger.d("LocateCrossProcessRequester", new Object[] { "onIpcCallback ", param1CrossProcessDataEntity }); LocateCrossProcessRequester.this.stopTimer(); if (param1CrossProcessDataEntity == null) { LocateCrossProcessRequester.this.callBackFailedWithCache("callback failed"); return; } String str = param1CrossProcessDataEntity.getString("locationResult"); if (TextUtils.isEmpty(str)) { LocateCrossProcessRequester.this.callBackFailedWithCache("ipcnull"); return; } try { TMALocation tMALocation = TMALocation.fromJson(new JSONObject(str)); if (tMALocation == null) { LocateCrossProcessRequester.this.callBackFailedWithCache("other"); return; } if (param1CrossProcessDataEntity.getInt("code") == -1) { LocateCrossProcessRequester locateCrossProcessRequester = LocateCrossProcessRequester.this; StringBuilder stringBuilder = new StringBuilder("loctype:"); stringBuilder.append(tMALocation.getLocType()); stringBuilder.append("_code:"); stringBuilder.append(tMALocation.getStatusCode()); stringBuilder.append("_rawcode:"); stringBuilder.append(tMALocation.getRawImplStatusCode()); locateCrossProcessRequester.callBackFailedWithCache(stringBuilder.toString()); return; } if (tMALocation.getStatusCode() == 0) { AppBrandLogger.d("LocateCrossProcessRequester", new Object[] { "onIpcCallback SUCCESS" }); LocateCrossProcessRequester.sCachedLocation = tMALocation; LocateCrossProcessRequester.this.callBackSuccess(tMALocation); } return; } catch (Exception exception) { AppBrandLogger.eWithThrowable("LocateCrossProcessRequester", "fromjson", exception); LocateCrossProcessRequester.this.callBackFailedWithCache("tmalocation_fromjson"); return; } } public void onIpcConnectError() { LocateCrossProcessRequester.this.callBackFailedWithCache("ipc fail"); } }; } private void notifyFailed(String paramString) { LocateResultCallbck locateResultCallbck = this.mCallback; if (locateResultCallbck != null) locateResultCallbck.onFailed(paramString); SecrecyManager.inst().notifyStateStop(12); } private void notifySuccess(TMALocation paramTMALocation) { if (SecrecyManager.inst().isSecrecyDenied(12)) { notifyFailed(BrandPermissionUtils.makePermissionErrorMsg(this.mCallApi)); return; } LocateResultCallbck locateResultCallbck = this.mCallback; if (locateResultCallbck != null) locateResultCallbck.onSuccess(new TMALocation(paramTMALocation)); SecrecyManager.inst().notifyStateStop(12); } public void callBackFailedWithCache(String paramString) { if (this.isLocateFinished) return; StringBuilder stringBuilder = new StringBuilder("callBackFailedWithCache:"); stringBuilder.append(paramString); AppBrandLogger.d("LocateCrossProcessRequester", new Object[] { stringBuilder.toString() }); TMALocation tMALocation = sCachedLocation; if (TMALocation.isSuccess(tMALocation)) { notifySuccess(tMALocation); return; } notifyFailed(paramString); stopTimer(); this.isLocateFinished = true; } public void callBackSuccess(TMALocation paramTMALocation) { if (this.isLocateFinished) return; notifySuccess(paramTMALocation); this.isLocateFinished = true; } public TMALocation getCachedLocation() { SecrecyManager.inst().notifyStateStart(12); SecrecyManager.inst().notifyStateStop(12); return sCachedLocation; } public boolean handleMessage(Message paramMessage) { if (paramMessage.what == 1) { AppBrandLogger.d("LocateCrossProcessRequester", new Object[] { "locate timeout" }); this.mIPCCallback.finishListenIpcCallback(); callBackFailedWithCache("timeout"); return true; } return false; } public void startCrossProcessLocate(long paramLong, LocateResultCallbck paramLocateResultCallbck) { SecrecyManager.inst().notifyStateStart(12); this.mTimeoutForLocate = paramLong; this.handler.sendEmptyMessageDelayed(1, this.mTimeoutForLocate); this.mCallback = paramLocateResultCallbck; AppBrandLogger.d("LocateCrossProcessRequester", new Object[] { "startCrossProcessLocate cross process" }); InnerHostProcessBridge.startLocate(this.mIPCCallback); } public void stopTimer() { AppBrandLogger.d("LocateCrossProcessRequester", new Object[] { "locate stopTimer" }); this.handler.removeMessages(1); } public static interface LocateResultCallbck { void onFailed(String param1String); void onSuccess(TMALocation param1TMALocation); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\locate\LocateCrossProcessRequester.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package exercise1; import javax.swing.JFrame; public class LabelTest { public static void main(String[] args) { StudentInfos studentInfos = new StudentInfos(); studentInfos.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); studentInfos.setSize(800, 450); studentInfos.setVisible(true); } }
package del.group10.java_ee.repository; import org.springframework.data.jpa.repository.JpaRepository; import del.group10.java_ee.model.Transaksi; public interface TransaksiRepository extends JpaRepository<Transaksi, Integer>{ }
package com.example.network; import com.example.network.task.GetAddressTask; import com.example.network.task.GetAddressTask.OnAddressListener; import com.example.network.util.DateUtil; import com.example.network.util.SwitchUtil; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView; import android.widget.Toast; /** * Created by ouyangshen on 2017/11/11. */ @SuppressLint(value={"SetTextI18n","DefaultLocale"}) public class HttpRequestActivity extends AppCompatActivity implements OnAddressListener { private final static String TAG = "HttpRequestActivity"; private TextView tv_location; private String mDesc = ""; private LocationManager mLocationMgr; // 声明一个定位管理器对象 private Criteria mCriteria = new Criteria(); // 声明一个定位准则对象 private Handler mHandler = new Handler(); // 声明一个处理器 private boolean isLocationEnable = false; // 定位服务是否可用 private Location mLocation; // 定位信息 private String mAddress = ""; // 详细地址描述 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_http_request); tv_location = findViewById(R.id.tv_location); SwitchUtil.checkGpsIsOpen(this, "需要打开定位功能才能查看定位结果信息"); } @Override protected void onResume() { super.onResume(); mHandler.removeCallbacks(mRefresh); // 移除定位刷新任务 initLocation(); mHandler.postDelayed(mRefresh, 100); // 延迟100毫秒启动定位刷新任务 } // 初始化定位服务 private void initLocation() { // 从系统服务中获取定位管理器 mLocationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // 设置定位精确度。Criteria.ACCURACY_COARSE表示粗略,Criteria.ACCURACY_FIN表示精细 mCriteria.setAccuracy(Criteria.ACCURACY_FINE); // 设置是否需要海拔信息 mCriteria.setAltitudeRequired(true); // 设置是否需要方位信息 mCriteria.setBearingRequired(true); // 设置是否允许运营商收费 mCriteria.setCostAllowed(true); // 设置对电源的需求 mCriteria.setPowerRequirement(Criteria.POWER_LOW); // 获取定位管理器的最佳定位提供者 String bestProvider = mLocationMgr.getBestProvider(mCriteria, true); if (mLocationMgr.isProviderEnabled(bestProvider)) { // 定位提供者当前可用 tv_location.setText("正在获取" + bestProvider + "定位对象"); mDesc = String.format("定位类型=%s", bestProvider); beginLocation(bestProvider); isLocationEnable = true; } else { // 定位提供者暂不可用 tv_location.setText("\n" + bestProvider + "定位不可用"); isLocationEnable = false; } } // 在找到详细地址后触发 public void onFindAddress(String address) { mAddress = address; refreshLocationInfo(); // 刷新定位信息 } // 刷新定位信息 private void refreshLocationInfo() { String desc = String.format("%s\n定位对象信息如下: " + "\n\t其中时间:%s" + "\n\t其中经度:%f,纬度:%f" + "\n\t其中高度:%d米,精度:%d米" + "\n\t其中地址:%s", mDesc, DateUtil.getNowDateTime("yyyy-MM-dd HH:mm:ss"), mLocation.getLongitude(), mLocation.getLatitude(), Math.round(mLocation.getAltitude()), Math.round(mLocation.getAccuracy()), mAddress); Log.d(TAG, desc); tv_location.setText(desc); } // 设置定位结果文本 private void setLocationText(Location location) { if (location != null) { mLocation = location; refreshLocationInfo(); // 刷新定位信息 // 创建一个详细地址查询的线程 GetAddressTask addressTask = new GetAddressTask(); // 设置详细地址查询的监听器 addressTask.setOnAddressListener(this); // 把详细地址查询线程加入到处理队列 addressTask.execute(location); } else { tv_location.setText(mDesc + "\n暂未获取到定位对象"); } } // 开始定位 private void beginLocation(String method) { // 检查当前设备是否已经开启了定位功能 if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "请授予定位权限并开启定位功能", Toast.LENGTH_SHORT).show(); return; } // 设置定位管理器的位置变更监听器 mLocationMgr.requestLocationUpdates(method, 300, 0, mLocationListener); // 获取最后一次成功定位的位置信息 Location location = mLocationMgr.getLastKnownLocation(method); setLocationText(location); } // 定义一个位置变更监听器 private LocationListener mLocationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { setLocationText(location); } @Override public void onProviderDisabled(String arg0) {} @Override public void onProviderEnabled(String arg0) {} @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) {} }; // 定义一个刷新任务,若无法定位则每隔一秒就尝试定位 private Runnable mRefresh = new Runnable() { @Override public void run() { if (!isLocationEnable) { initLocation(); mHandler.postDelayed(this, 1000); } } }; @Override protected void onDestroy() { if (mLocationMgr != null) { // 移除定位管理器的位置变更监听器 mLocationMgr.removeUpdates(mLocationListener); } super.onDestroy(); } }
package com.manju.service; import java.rmi.RemoteException; import javax.xml.rpc.ServiceException; public class clienttest { public static void main(String[] args) { CalculatorServiceImplServiceLocator loc= new CalculatorServiceImplServiceLocator(); try { CalculatorServiceImpl cal=loc.getCalculatorServiceImpl(); System.out.println(cal.add(3, 15)); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package tw.org.iii.java; import tw.org.iii.myclass.TWId; public class Brad38 { public static void main(String[] args) { if (TWId.checkID("712345678Y")) { System.out.println("OK"); }else { System.out.println("XX"); } System.out.println("----------------"); } }
package com.wshoto.user.anyong.ui.activity; import android.app.AlertDialog; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.jakewharton.rxbinding.view.RxView; import com.wshoto.user.anyong.Bean.HealthyTaskBean; import com.wshoto.user.anyong.R; import com.wshoto.user.anyong.SharedPreferencesUtils; import com.wshoto.user.anyong.http.HttpJsonMethod; import com.wshoto.user.anyong.http.ProgressSubscriber; import com.wshoto.user.anyong.http.SubscriberOnNextListener; import com.wshoto.user.anyong.ui.widget.InitActivity; import org.json.JSONObject; import java.util.Calendar; import java.util.concurrent.TimeUnit; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class HealthyLifeActivity extends InitActivity { @BindView(R.id.tv_healthy_number) TextView mTvHealthyNumber; @BindView(R.id.tv_healthy_gather) TextView mTvHealthyGather; @BindView(R.id.tv_option_yanbao) TextView mTvOptionYanbao; @BindView(R.id.tv_option_jingzhui) TextView mTvOptionJingzhui; private SubscriberOnNextListener<JSONObject> healthTaskOnNext; private SubscriberOnNextListener<JSONObject> healthCommitOnNext; private HealthyTaskBean mHealthyTaskBean; private Gson mGson = new Gson(); @Override protected void onResume() { super.onResume(); HttpJsonMethod.getInstance().healthTask( new ProgressSubscriber(healthTaskOnNext, HealthyLifeActivity.this), (String) com.wshoto.user.anyong.SharedPreferencesUtils.getParam(this, "session", ""), (String) SharedPreferencesUtils.getParam(this, "language", "zh")); } @Override public void initView(Bundle savedInstanceState) { setContentView(R.layout.activity_healthy_life); ButterKnife.bind(this); mTvHealthyNumber.setText((String) SharedPreferencesUtils.getParam(this, "step", "0")); } @Override public void initData() { SubscriberOnNextListener<JSONObject> footsetpOnNext = jsonObject -> { }; healthTaskOnNext = jsonObject -> { if (jsonObject.getInt("code") == 1) { mHealthyTaskBean = mGson.fromJson(jsonObject.toString(), HealthyTaskBean.class); if (mHealthyTaskBean.getData().get(0).getIs_done() == 1) { mTvOptionYanbao.setBackground(getResources().getDrawable(R.drawable.boder_healthy_grey)); mTvOptionYanbao.setText(getText(R.string.point_success)); mTvOptionYanbao.setClickable(false); } if (mHealthyTaskBean.getData().get(1).getIs_done() == 1) { mTvOptionJingzhui.setBackground(getResources().getDrawable(R.drawable.boder_healthy_grey)); mTvOptionJingzhui.setText(getText(R.string.point_success)); mTvOptionJingzhui.setClickable(false); } } else { Toast.makeText(this, jsonObject.getJSONObject("message").getString("status"), Toast.LENGTH_SHORT).show(); } }; healthCommitOnNext = jsonObject -> { if (jsonObject.getInt("code") == 1) { Toast.makeText(HealthyLifeActivity.this, getText(R.string.point_successfully), Toast.LENGTH_SHORT).show(); HttpJsonMethod.getInstance().healthTask( new ProgressSubscriber(healthTaskOnNext, HealthyLifeActivity.this), (String) com.wshoto.user.anyong.SharedPreferencesUtils.getParam(this, "session", ""), (String) SharedPreferencesUtils.getParam(this, "language", "zh")); } else { Toast.makeText(HealthyLifeActivity.this, jsonObject.getJSONObject("message").getString("status"), Toast.LENGTH_SHORT).show(); } }; Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); if (hour >= 10 && hour <= 18) { mTvOptionYanbao.setClickable(true); RxView.clicks(mTvOptionYanbao) .throttleFirst(3, TimeUnit.SECONDS) .subscribe((o -> { show(1); HttpJsonMethod.getInstance().healthCommit( new ProgressSubscriber(healthCommitOnNext, HealthyLifeActivity.this), (String) com.wshoto.user.anyong.SharedPreferencesUtils.getParam(this, "session", ""), "1", (String) SharedPreferencesUtils.getParam(this, "language", "zh")); })); mTvOptionYanbao.setBackground(getResources().getDrawable(R.drawable.boder_healthy_yellow)); mTvOptionYanbao.setText(getText(R.string.complete)); } if (hour >= 15 && hour <= 20) { mTvOptionJingzhui.setClickable(true); RxView.clicks(mTvOptionJingzhui) .throttleFirst(3, TimeUnit.SECONDS) .subscribe((o -> { show(2); HttpJsonMethod.getInstance().healthCommit( new ProgressSubscriber(healthCommitOnNext, HealthyLifeActivity.this), (String) SharedPreferencesUtils.getParam(this, "session", ""), "2", (String) SharedPreferencesUtils.getParam(this, "language", "zh")); })); mTvOptionJingzhui.setBackground(getResources().getDrawable(R.drawable.boder_healthy_yellow)); mTvOptionJingzhui.setText(getText(R.string.complete)); } if (Integer.valueOf((String) SharedPreferencesUtils.getParam(this, "step", "0")) >= 8000) { if ((Boolean) SharedPreferencesUtils.getParam(this, "fresh", false)) { HttpJsonMethod.getInstance().footstep( new ProgressSubscriber(footsetpOnNext, HealthyLifeActivity.this), (String) com.wshoto.user.anyong.SharedPreferencesUtils.getParam(this, "session", ""), (String) SharedPreferencesUtils.getParam(this, "language", "zh")); } else { mTvHealthyGather.setText(getText(R.string.point_success)); } } } @OnClick(R.id.iv_comfirm_back) public void onViewClicked() { finish(); } public void show(int type) { AlertDialog.Builder builder = new AlertDialog.Builder(HealthyLifeActivity.this); builder.setMessage(getText(R.string.jiaocheng)); builder.setTitle(R.string.app_name); builder.setCancelable(false); builder.setPositiveButton(getText(R.string.confirm), (dialog, which) -> { dialog.dismiss(); Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); Uri content_url; if (type == 1) { content_url = Uri.parse("http://www.iqiyi.com/w_19ruyhjsup.html?list=19rrlgq9iu"); } else { content_url = Uri.parse("http://www.iqiyi.com/w_19rsyzm3yd.html?list=19rrklo3yu"); } intent.setData(content_url); startActivity(intent); }); builder.setNegativeButton(getText(R.string.cancel), (dialog, which) -> dialog.dismiss()); builder.create().show(); } }
package com.ym.lockdemo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Bank bank = new Bank(2, 100); for (int i = 0;i<10;i++){ // 转账 new Thread(new Runnable() { @Override public void run() { try { bank.transfer(0, 1, 50); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); // 存钱 new Thread(new Runnable() { @Override public void run() { bank.save(0,50); } }).start(); } } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.acceleratorservices.process.email.context; import de.hybris.platform.acceleratorservices.document.context.AbstractHybrisVelocityContext; import de.hybris.platform.acceleratorservices.model.cms2.pages.EmailPageModel; import de.hybris.platform.basecommerce.model.site.BaseSiteModel; import de.hybris.platform.commerceservices.customer.CustomerEmailResolutionService; import de.hybris.platform.core.model.c2l.LanguageModel; import de.hybris.platform.core.model.user.CustomerModel; import de.hybris.platform.processengine.model.BusinessProcessModel; import de.hybris.platform.servicelayer.config.ConfigurationService; import java.util.Locale; import org.springframework.beans.factory.annotation.Required; import org.apache.velocity.tools.generic.DateTool; /** * The email velocity context. */ public abstract class AbstractEmailContext<T extends BusinessProcessModel> extends AbstractHybrisVelocityContext { public static final String TITLE = "title"; public static final String DISPLAY_NAME = "displayName"; public static final String EMAIL = "email"; public static final String FROM_EMAIL = "fromEmail"; public static final String FROM_DISPLAY_NAME = "fromDisplayName"; public static final String EMAIL_LANGUAGE = "email_language"; public static final String DATE_TOOL = "dateTool"; private CustomerEmailResolutionService customerEmailResolutionService; private ConfigurationService configurationService; protected CustomerEmailResolutionService getCustomerEmailResolutionService() { return customerEmailResolutionService; } @Required public void setCustomerEmailResolutionService(final CustomerEmailResolutionService customerEmailResolutionService) { this.customerEmailResolutionService = customerEmailResolutionService; } protected ConfigurationService getConfigurationService() { return configurationService; } @Required public void setConfigurationService(final ConfigurationService configurationService) { this.configurationService = configurationService; } public String getTitle() { return (String) get(TITLE); } public String getDisplayName() { return (String) get(DISPLAY_NAME); } public String getEmail() { return (String) get(EMAIL); } public String getToEmail() { return getEmail(); } public String getToDisplayName() { return getDisplayName(); } public String getFromEmail() { return (String) get(FROM_EMAIL); } public String getFromDisplayName() { return (String) get(FROM_DISPLAY_NAME); } public LanguageModel getEmailLanguage() { return (LanguageModel) get(EMAIL_LANGUAGE); } public void init(final T businessProcessModel, final EmailPageModel emailPageModel) { super.setBaseSite(getSite(businessProcessModel)); super.init(businessProcessModel, emailPageModel); put(FROM_EMAIL, emailPageModel.getFromEmail()); final LanguageModel language = getEmailLanguage(businessProcessModel); if (language != null) { put(EMAIL_LANGUAGE, language); String fromName = emailPageModel.getFromName(new Locale(language.getIsocode())); if (fromName == null) { fromName = emailPageModel.getFromName(); } put(FROM_DISPLAY_NAME, fromName); } else { put(FROM_DISPLAY_NAME, emailPageModel.getFromName()); } final CustomerModel customerModel = getCustomer(businessProcessModel); if (customerModel != null) { put(TITLE, (customerModel.getTitle() != null && customerModel.getTitle().getName() != null) ? customerModel.getTitle().getName() : ""); put(DISPLAY_NAME, customerModel.getDisplayName()); put(EMAIL, getCustomerEmailResolutionService().getEmailForCustomer(customerModel)); } put(DATE_TOOL, new DateTool()); } protected abstract BaseSiteModel getSite(final T businessProcessModel); protected abstract CustomerModel getCustomer(final T businessProcessModel); protected abstract LanguageModel getEmailLanguage(final T businessProcessModel); }
package cn.gavinliu.notificationbox.ui.main; import android.content.pm.PackageManager; import java.util.List; import cn.gavinliu.notificationbox.model.AppInfo; import cn.gavinliu.notificationbox.ui.BasePresenter; import cn.gavinliu.notificationbox.ui.BaseView; /** * Created by Gavin on 2016/10/11. */ public interface MainContract { interface Presenter extends BasePresenter { void addApp(); void openDetail(AppInfo app); void startLoad(PackageManager pm); } interface View extends BaseView<Presenter> { void showProgress(boolean isShown); void showEmpty(); void showApp(List<AppInfo> apps); void showAppList(); void showDetail(String appName, String packageName); } }
package alwrite; /* * @author Xingqilin * */ import java.util.Arrays; import java.util.LinkedList; public class MyAlAchieve { /** * 懒构造 * final属性,默认长度,空object数组,Object元素数组 * 私有属性,元素个数size * 方法: * 有长度,无长度构造 * 添加,位置添加,触发扩容机制 * 修改 * 下标删除,条件删除 * 查找 constant * size() * 清空clear() * 下标判断方法 * 容量判断方法 * 扩容方法 */ private int size = 0; private static final Object[] DEFAULT_ELEMENTDATA = {}; private static final int DEFAULT_CAPACITY = 10; private Object[] elementmy; MyAlAchieve() { elementmy = DEFAULT_ELEMENTDATA; } MyAlAchieve(int i) { if (i > 0) { elementmy = new Object[i]; } else { elementmy = DEFAULT_ELEMENTDATA; System.err.println("长度异常,自动建立空链表"); } } //尾添加 public void addele(Object ob) { if (ensureCapacity(size + 1)) { elementmy[size++] = ob; return; } extendCapacity(); elementmy[size++] = ob; } //下标添加 public void addele(int index, Object ob) { if (checkLegal(index)) { if (ensureCapacity(size + 1)) { System.arraycopy(elementmy, index, elementmy, index + 1, size - index); elementmy[index] = ob; } else { Object[] obn = new Object[(int) (elementmy.length * 1.5)]; System.arraycopy(elementmy, 0, obn, 0, index - 1); size++; elementmy[index] = ob; System.arraycopy(elementmy, index, obn, index + 1, size - index); elementmy = obn; } } } //修改 public void setAl(int index, Object ob) { checkLegals(index); elementmy[index - 1] = ob; } //下标删除 public void remove(int index) { setAl(index, null); } //条件删除//lambda泛型编程 public void removeif() { } //查找indexOf() public int indexOf(Object ob) { if (ob == null) { for (int i = 0; i < elementmy.length; i++) { if (elementmy[i] == null) return i; } } else { for (int i = 0; i < elementmy.length; i++) { if (ob.equals(elementmy[i])) return i; } } return -1; } //获得size() public int getSize() { return size; } //clean() public void clean() { for (int i = 0; i < elementmy.length; i++) { elementmy[i] = null; } size = 0; } //add下标合法验证 private boolean checkLegal(int index) { if (size == 0 && index != 0) return false; return (-1 < index && index < size + 2); } //set下标合法验证 private void checkLegals(int index) { if (index >= size) throw new ArrayIndexOutOfBoundsException("输入下标越界了"); } //容量判断 private boolean ensureCapacity(int i) { return i < elementmy.length; } //扩容方法 private void extendCapacity() { if (size == 0) { elementmy = new Object[DEFAULT_CAPACITY]; } else { elementmy = Arrays.copyOf(elementmy, (int) (elementmy.length * 1.5)); } } }
láthatóságai módosítószo - public - private - nincs semmi: félnyilvános (package-private, csomagszintű) láthatóság ugyanabban a csomagban elérhető a tag csomag: logikai összetartozás, fizikai összetartozás a félnyilvános tagok mentén alcsomagra már nem ad hozzáférést (bár logikai kapcsolat ott is fennáll) - protected (majd később) csomagok - akönyvtárakba szervezett programkód kis program esetén zavaró, kényelmetlen lehet -> névtelen csomag, minden ebben a csomagban (ha nincs package utasítás a kódban) osztály teljes neve == a rövid névvel a public nem bír jelentőséggel nagy program esetén segíti az átláthatóságot változók, formális paraméterek tipizálására primitív típusok és osztályok is osztály: egyben recept arra nézve, hogyan működik az objektum int i i egész szám tárolására alkalmas Rational r r nem tárol racionális objektumot hivatkozás egy objektumra az objektum a példányosítás hatására jön létre: new Rational(2,5) Rational r = new Rational(2,5) összekapcsolva létrejön egy referencia és egy objektum, és a kettő összekapcsolódik a referenciát ráállítom az objektumra virtuális gép, program belső működése, adatok tárolása - dinamikus tárhelyen (heap) - statikus tárhelyen - automatikus tárhelyen (stack, végrtehajtási verem) objektumok (és benne az adattagok) a heapen jönnek létre élettartam: new-tól gc-ig lásd ábra program működése: metódushívások láncolata, gráfja public static void main( String[] ) ezzel kezdődik, és pontosan addig tart, amíg be nem fejeződik közben a main által hívott metódusok futnak (advanced: ennél picit pontosabban kellene fogalmazni, pl. többszálú prg) a prg egy adott pontján éppen futó metódusok tárolása: execution stack minden metódushívásról (aktiválásról) bejegyzés (record) készül a veremben aktivációs rekord (activation record, stack frame) metódus hívása: új aktivációs rekord metódus befejeződése: az aktivációs rekordja törlődik a veremből a hívott előbb fejeződik be, mint a hívó last in first out viselkedés LIFO - verem lásd: ábra stack: metódushívások nyilvántartása heap: objektumok/adatok tárolása aktivációs rekord tartalma: - technically: fordítóprogramok című tárgy - absztrakt értelemben, erlvonatkoztatva a technikai részletektől: metódusok paraméterei és lokális változói class Point { double x, y; double distance( Point that ){ double dx = this.x - that.x; double dy = this.y - that.y; return Math.sqrt( dx*dx + dy*dy ); } } class Main { public static void main( String[] args ){ Point p = new Point(); Point q = new Point(); p.x = 3.14; System.out.println( p.distance(q) ); } } végrehajtás: lásd ábra ha nem írok egy osztályba konstruktort, automatikusan képződik egy (és csak ekkor képződik ilyen), a fordítóprogram beilleszt a kódba egy ún. default konstruktort. pl. a Pointba bekerül: Point(){} paraméter nélküli, "üres törzsű" amikor a metódus meghívódik, létrejönnek a lokális változói és a formális paraméterek(-nek megfelelő lokális változók) használhatom ezeket, amíg a metódus fut lokális, azaz csak abban a metódusban használhatók megszűnnek, amikor a metódus befejeződik, és törlődik az aktivációs rekord automatikus változók, automatikusan létrejönnek és megszűnnek metódusba való be- és kilépésnél ez az élettartamuk p.x: dereferálom a p referenciát (megkeresem a heapen az objektumot) és szelektálom az x mezőjét (az objektumon belül megkeresem az x adatot) ugyanarra az objektumra hivatkozhat több referencia is: aliasing (paraméterátadás) amikor létrejön egy objektum, a JVM minden példánymezőjét inicializálja 0-ra (az osztályszintű mezők is valahogy így inicioalizálódnak) lokális válzotó: inicializálatlan az első értékadásáig a fordítóprg véd az inicializálatlan változó használatától fordítási hiba, ha olvasom a lokális változót értékadás előtt szigorú szabály, ami visszadobhat "jó" programot azzal, hogy nem helyes át kell fogalmazni a programot, hogy ne csak jó legyen, hanem helyes is
public class DogExamples { public static void main(String[] args) { Dog maya = new Dog(67); Dog humphrey = new Dog(69); maya.size = 15; System.out.printf("%d\n", maya.size); maya.makeNoise(); maya.name = "Maya"; System.out.printf("%s\n", maya.name); Dog[] someDogs = new Dog[2]; someDogs[0] = new Dog(90); someDogs[1] = new Dog(15); Dog.Barky(); someDogs[0].makeNoise(); System.out.printf("%s", maxDog(humphrey, maya)); } public static Dog maxDog(Dog d1, Dog d2){ if (d1.size > d2.size){ return d1; } else{ return d2; } } }
package org.tecsup.tecunity_api; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TecunityApiApplication { public static void main(String[] args) { SpringApplication.run(TecunityApiApplication.class, args); } }
package org.apache.commons.net.examples.ntp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import org.apache.commons.net.ntp.NtpUtils; import org.apache.commons.net.ntp.NtpV3Impl; import org.apache.commons.net.ntp.TimeStamp; public class SimpleNTPServer implements Runnable { private int port; private volatile boolean running; private boolean started; private DatagramSocket socket; public SimpleNTPServer() { this(123); } public SimpleNTPServer(int port) { if (port < 0) throw new IllegalArgumentException(); this.port = port; } public int getPort() { return this.port; } public boolean isRunning() { return this.running; } public boolean isStarted() { return this.started; } public void connect() throws IOException { if (this.socket == null) { this.socket = new DatagramSocket(this.port); if (this.port == 0) this.port = this.socket.getLocalPort(); System.out.println("Running NTP service on port " + this.port + "/UDP"); } } public void start() throws IOException { if (this.socket == null) connect(); if (!this.started) { this.started = true; (new Thread(this)).start(); } } public void run() { this.running = true; byte[] buffer = new byte[48]; DatagramPacket request = new DatagramPacket(buffer, buffer.length); do { try { this.socket.receive(request); long rcvTime = System.currentTimeMillis(); handlePacket(request, rcvTime); } catch (IOException e) { if (this.running) e.printStackTrace(); } } while (this.running); } protected void handlePacket(DatagramPacket request, long rcvTime) throws IOException { NtpV3Impl ntpV3Impl = new NtpV3Impl(); ntpV3Impl.setDatagramPacket(request); System.out.printf("NTP packet from %s mode=%s%n", new Object[] { request.getAddress().getHostAddress(), NtpUtils.getModeName(ntpV3Impl.getMode()) }); if (ntpV3Impl.getMode() == 3) { NtpV3Impl ntpV3Impl1 = new NtpV3Impl(); ntpV3Impl1.setStratum(1); ntpV3Impl1.setMode(4); ntpV3Impl1.setVersion(3); ntpV3Impl1.setPrecision(-20); ntpV3Impl1.setPoll(0); ntpV3Impl1.setRootDelay(62); ntpV3Impl1.setRootDispersion(1081); ntpV3Impl1.setOriginateTimeStamp(ntpV3Impl.getTransmitTimeStamp()); ntpV3Impl1.setReceiveTimeStamp(TimeStamp.getNtpTime(rcvTime)); ntpV3Impl1.setReferenceTime(ntpV3Impl1.getReceiveTimeStamp()); ntpV3Impl1.setReferenceId(1279478784); ntpV3Impl1.setTransmitTime(TimeStamp.getNtpTime(System.currentTimeMillis())); DatagramPacket dp = ntpV3Impl1.getDatagramPacket(); dp.setPort(request.getPort()); dp.setAddress(request.getAddress()); this.socket.send(dp); } } public void stop() { this.running = false; if (this.socket != null) { this.socket.close(); this.socket = null; } this.started = false; } public static void main(String[] args) { int port = 123; if (args.length != 0) try { port = Integer.parseInt(args[0]); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } SimpleNTPServer timeServer = new SimpleNTPServer(port); try { timeServer.start(); } catch (IOException e) { e.printStackTrace(); } } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\net\examples\ntp\SimpleNTPServer.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.openkm.util.metadata; import java.util.Calendar; /** * See also @org.apache.poi.hpsf.SummaryInformation * * @author pavila */ public class OfficeMetadata { private String title; private String subject; private String author; private String lastAuthor; private String keywords; private String comments; private String template; private String revNumber; private String applicationName; private Calendar lastPrinted; private Calendar createDateTime; private Calendar lastSaveDateTime; private long editTime; private int pageCount; private int wordCount; private int charCount; private int security; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getLastAuthor() { return lastAuthor; } public void setLastAuthor(String lastAuthor) { this.lastAuthor = lastAuthor; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } public String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; } public String getRevNumber() { return revNumber; } public void setRevNumber(String revNumber) { this.revNumber = revNumber; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public Calendar getLastPrinted() { return lastPrinted; } public void setLastPrinted(Calendar lastPrinted) { this.lastPrinted = lastPrinted; } public Calendar getCreateDateTime() { return createDateTime; } public void setCreateDateTime(Calendar createDateTime) { this.createDateTime = createDateTime; } public Calendar getLastSaveDateTime() { return lastSaveDateTime; } public void setLastSaveDateTime(Calendar lastSaveDateTime) { this.lastSaveDateTime = lastSaveDateTime; } public long getEditTime() { return editTime; } public void setEditTime(long editTime) { this.editTime = editTime; } public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public int getWordCount() { return wordCount; } public void setWordCount(int wordCount) { this.wordCount = wordCount; } public int getCharCount() { return charCount; } public void setCharCount(int charCount) { this.charCount = charCount; } public int getSecurity() { return security; } public void setSecurity(int security) { this.security = security; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("title=").append(title); sb.append(", subject=").append(subject); sb.append(", author=").append(author); sb.append(", lastAuthor=").append(lastAuthor); sb.append(", keywords=").append(keywords); sb.append(", comments=").append(comments); sb.append(", template=").append(template); sb.append(", revNumber=").append(revNumber); sb.append(", applicationName=").append(applicationName); sb.append(", lastPrinted=").append(lastPrinted==null?null:lastPrinted.getTime()); sb.append(", createDateTime=").append(createDateTime==null?null:createDateTime.getTime()); sb.append(", lastSaveDateTime=").append(lastSaveDateTime==null?null:lastSaveDateTime.getTime()); sb.append(", editTime=").append(editTime); sb.append(", pageCount=").append(pageCount); sb.append(", wordCount=").append(wordCount); sb.append(", charCount=").append(charCount); sb.append(", security=").append(security); sb.append("}"); return sb.toString(); } }
package negocios; import java.time.*; import java.util.List; import beans.Cliente; import beans.Fornecedor; import beans.Funcionario; import beans.MateriaPrima; import beans.Produto; import dados.RepositorioCliente; import dados.RepositorioFornecedor; import dados.RepositorioFuncionario; import dados.RepositorioMateriaPrima; import dados.RepositorioProduto; import exceptions.ClienteJaExisteException; import exceptions.ClienteNaoExisteException; import exceptions.FuncionarioJaExisteException; import exceptions.FuncionarioNaoExisteException; import exceptions.FornecedorNaoExisteException; import exceptions.FornecedorJaExisteException; import exceptions.MateriaPrimaNaoExisteException; import exceptions.MateriaPrimaJaExisteException; import exceptions.ProdutoJaExisteException; import exceptions.ProdutoNaoExisteException; public class PanelaFit implements IPanelaFit{ private ControladorClientes clientes; private ControladorFornecedores fornecedores; private ControladorFuncionarios funcionarios; private ControladorMateriaPrimas materiaPrimas; private ControladorProdutos produtos; private static PanelaFit instance; private PanelaFit(){ this.clientes = new ControladorClientes(RepositorioCliente.getInstance()); this.fornecedores = new ControladorFornecedores(RepositorioFornecedor.getInstance()); this.funcionarios = new ControladorFuncionarios(RepositorioFuncionario.getInstance()); this.materiaPrimas = new ControladorMateriaPrimas(RepositorioMateriaPrima.getInstance()); this.produtos = new ControladorProdutos(RepositorioProduto.getInstance()); } public static PanelaFit getInstance(){ if(instance == null){ instance = new PanelaFit(); } return instance; } //CLIENTES public void cadastrarCliente(Cliente c) throws ClienteJaExisteException, ClienteNaoExisteException { clientes.cadastrar(c); } public void removerCliente(Cliente c) throws ClienteNaoExisteException { clientes.remover(c); } public Cliente buscarCliente(int codigo) throws ClienteNaoExisteException { return clientes.buscar(codigo); } public void alterarCliente(Cliente clienteAlterado, Cliente novoCliente) throws ClienteNaoExisteException, ClienteJaExisteException { clientes.alterar(clienteAlterado, novoCliente); } public List<Cliente> listarClientes(){ return this.clientes.listaClientes(); } //FORNECEDORES public void cadastrarFornecedor(Fornecedor f) throws FornecedorJaExisteException { fornecedores.cadastrar(f); } public void removerFornecedor(Fornecedor f) throws FornecedorNaoExisteException { fornecedores.remover(f); } public Fornecedor buscarFornecedor(int codigo) throws FornecedorNaoExisteException { return fornecedores.buscar(codigo); } public void alterarFornecedor(Fornecedor fornAlterado, Fornecedor novoFornecedor) throws FornecedorNaoExisteException { fornecedores.alterar(fornAlterado, novoFornecedor); } public String getTelefoneFornecedor(int codigo) throws FornecedorNaoExisteException { return fornecedores.getTelefone(codigo); } public void cadastrarFuncionario(Funcionario f) throws FuncionarioJaExisteException { funcionarios.cadastrar(f); } public void removerFuncionario(Funcionario f) throws FuncionarioNaoExisteException { funcionarios.remover(f); } public Funcionario buscarFuncionario(int codigo) throws FuncionarioNaoExisteException { return funcionarios.buscar(codigo); } public void alterarFuncionario(Funcionario funcAlterado, Funcionario novoFuncionario) throws FuncionarioNaoExisteException { funcionarios.alterar(funcAlterado, novoFuncionario); } public int getNivelFuncionario(int codigo) throws FuncionarioNaoExisteException { return funcionarios.getNivel(codigo); } public void cadastrarMateriaPrima(MateriaPrima m) throws MateriaPrimaJaExisteException{ materiaPrimas.cadastrar(m); } public void removerMateriaPrima(MateriaPrima m) throws MateriaPrimaNaoExisteException { materiaPrimas.remover(m); } public MateriaPrima buscarMateriaPrima(int codigo) throws MateriaPrimaNaoExisteException { return materiaPrimas.buscar(codigo); } public void alterarMateriaPrima(MateriaPrima mpAlterada, MateriaPrima novaMateriaPrima) throws MateriaPrimaNaoExisteException { materiaPrimas.alterar(mpAlterada, novaMateriaPrima); } public int getQuantidadeMateriaPrima(int codigo) throws MateriaPrimaNaoExisteException { return materiaPrimas.getQuantidade(codigo); } public void cadastrarProduto(Produto p) throws ProdutoJaExisteException{ produtos.cadastrar(p); } public void removerProduto(Produto p) throws ProdutoNaoExisteException { produtos.remover(p); } public Produto buscarProduto(int codigo) throws ProdutoNaoExisteException { return produtos.buscar(codigo); } public void alterarProdutos(Produto produtoAlterado, Produto novoProduto) throws ProdutoNaoExisteException { produtos.alterar(produtoAlterado, novoProduto); } public LocalDate getDataFabricacao(int codigo){ return produtos.getDataValidade(codigo); } public LocalDate getDataValidade(int codigo){ return produtos.getDataValidade(codigo); } @Override public void removerFornecedor(int codigo) { // TODO Auto-generated method stub } @Override public void removerFuncionario(int codigo) { // TODO Auto-generated method stub } @Override public void removerMateriaPrima(int codigo) { // TODO Auto-generated method stub } @Override public void removerProduto(int codigo) { // TODO Auto-generated method stub } @Override public boolean alterarFornecedor(Fornecedor novoFornecedor) { // TODO Auto-generated method stub return false; } @Override public boolean alterarFuncionario(Funcionario novoFuncionario) { // TODO Auto-generated method stub return false; } @Override public boolean alterarMateriaPrima(MateriaPrima novaMateriaPrima) { // TODO Auto-generated method stub return false; } @Override public boolean alterarProdutos(Produto novoProduto) { // TODO Auto-generated method stub return false; } }
/* 1: */ package com.kaldin.test.executetest.dto; /* 2: */ /* 3: */ public class TemporaryExamInfoDTO /* 4: */ { /* 5: */ private int tempInfoid; /* 6: */ private int userid; /* 7: */ private String testid; /* 8: */ private int examid; /* 9: */ private int startime; /* 10: */ private int endtime; /* 11: */ /* 12: */ public int getTempInfoid() /* 13: */ { /* 14:23 */ return this.tempInfoid; /* 15: */ } /* 16: */ /* 17: */ public void setTempInfoid(int tempInfoid) /* 18: */ { /* 19:27 */ this.tempInfoid = tempInfoid; /* 20: */ } /* 21: */ /* 22: */ public int getUserid() /* 23: */ { /* 24:31 */ return this.userid; /* 25: */ } /* 26: */ /* 27: */ public void setUserid(int userid) /* 28: */ { /* 29:35 */ this.userid = userid; /* 30: */ } /* 31: */ /* 32: */ public String getTestid() /* 33: */ { /* 34:39 */ return this.testid; /* 35: */ } /* 36: */ /* 37: */ public void setTestid(String testid) /* 38: */ { /* 39:43 */ this.testid = testid; /* 40: */ } /* 41: */ /* 42: */ public int getExamid() /* 43: */ { /* 44:47 */ return this.examid; /* 45: */ } /* 46: */ /* 47: */ public void setExamid(int examid) /* 48: */ { /* 49:51 */ this.examid = examid; /* 50: */ } /* 51: */ /* 52: */ public int getStartime() /* 53: */ { /* 54:55 */ return this.startime; /* 55: */ } /* 56: */ /* 57: */ public void setStartime(int startime) /* 58: */ { /* 59:59 */ this.startime = startime; /* 60: */ } /* 61: */ /* 62: */ public int getEndtime() /* 63: */ { /* 64:63 */ return this.endtime; /* 65: */ } /* 66: */ /* 67: */ public void setEndtime(int endtime) /* 68: */ { /* 69:67 */ this.endtime = endtime; /* 70: */ } /* 71: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.test.executetest.dto.TemporaryExamInfoDTO * JD-Core Version: 0.7.0.1 */
package net.javango.carcare.widget; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.RemoteViews; import android.widget.RemoteViewsService; import net.javango.carcare.R; import net.javango.carcare.ServiceListActivity; import net.javango.carcare.model.AppDatabase; import net.javango.carcare.model.Service; import net.javango.carcare.util.Formatter; import java.util.List; public class WidgetService extends RemoteViewsService { public static Intent newIntent(Context context, int carId) { Intent intent = new Intent(context, WidgetService.class); intent.setData(Uri.fromParts("content", String.valueOf(carId), null)); return intent; } @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { return new ListRemoteViewsFactory(getApplicationContext(), intent); } private static class ListRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { private List<Service> serviceList; private Context context; private int carId; public ListRemoteViewsFactory(Context context, Intent intent) { this.context = context; carId = Integer.valueOf(intent.getData().getSchemeSpecificPart()); } @Override public void onCreate() { // empty } @Override public boolean hasStableIds() { return true; } @Override public int getViewTypeCount() { return 1; // all items in the view are the same } @Override public int getCount() { return serviceList.size(); } @Override public long getItemId(int position) { return position; } @Override public RemoteViews getLoadingView() { return null; } @Override public void onDestroy() { // empty } @Override public void onDataSetChanged() { serviceList = AppDatabase.getDatabase().serviceDao().getForCarSync(carId); } @Override public RemoteViews getViewAt(int position) { final RemoteViews remoteView = new RemoteViews( context.getPackageName(), R.layout.widget_item_service); Service service = serviceList.get(position); remoteView.setTextViewText(R.id.widget_item_description, service.getDescription()); remoteView.setTextViewText(R.id.widget_item_date, Formatter.format(service.getDate())); Intent fillInIntent = ServiceListActivity.newFillInIntent(carId); remoteView.setOnClickFillInIntent(R.id.widget_item_description, fillInIntent); return remoteView; } } }
package com.example.opencvpractice.datamodel; import java.util.ArrayList; import java.util.List; public class ChapterUtils implements AppConstants { public static List<ItemDto> getChapters() { List<ItemDto> items = new ArrayList<>(); ItemDto item1 = new ItemDto(1, CHAPTER_1TH, "OpenCV For Android框架"); ItemDto item2 = new ItemDto(2, CHAPTER_2TH, "Mat与Bitmap对象"); ItemDto item3 = new ItemDto(3, CHAPTER_3TH, "像素操作"); ItemDto item4 = new ItemDto(4, CHAPTER_4TH, "图像操作"); ItemDto item5 = new ItemDto(5, CHAPTER_5TH, "分析与测量"); ItemDto item6 = new ItemDto(6, CHAPTER_6TH, "特征检测与匹配"); ItemDto item7 = new ItemDto(7, CHAPTER_7TH, "摄像头"); ItemDto item8 = new ItemDto(8, CHAPTER_8TH, "OCR识别"); ItemDto item9 = new ItemDto(9, CHAPTER_9TH, "人脸美化"); ItemDto item10 = new ItemDto(10, CHAPTER_10TH, "人眼实时跟踪与渲染"); items.add(item1); items.add(item2); items.add(item3); items.add(item4); items.add(item5); items.add(item6); items.add(item7); items.add(item8); items.add(item9); items.add(item10); return items; } public static List<ItemDto> getSections(int chapterNum) { List<ItemDto> items = new ArrayList<>(); if(chapterNum == 1) { items.add(new ItemDto(1, CHAPTER_1TH_PGM_01,CHAPTER_1TH_PGM_01)); } if(chapterNum == 2) { items.add(new ItemDto(1, CHAPTER_2TH_PGM_01,CHAPTER_2TH_PGM_01)); } if(chapterNum == 3) { items.add(new ItemDto(1, CHAPTER_3TH_PGM,CHAPTER_3TH_PGM)); } if(chapterNum == 4) { items.add(new ItemDto(1, CHAPTER_4TH_PGM,CHAPTER_4TH_PGM)); } if(chapterNum == 5) { items.add(new ItemDto(1, CHAPTER_5TH_PGM,CHAPTER_5TH_PGM)); } if(chapterNum == 6) { items.add(new ItemDto(1, CHAPTER_6TH_PGM,CHAPTER_6TH_PGM)); } if(chapterNum == 7) { items.add(new ItemDto(1, CHAPTER_7TH_PGM,CHAPTER_7TH_PGM)); items.add(new ItemDto(2, CHAPTER_7TH_PGM_VIEW_MODE,CHAPTER_7TH_PGM_VIEW_MODE)); } if(chapterNum == 8) { items.add(new ItemDto(1, CHAPTER_8TH_PGM_OCR,CHAPTER_8TH_PGM_OCR)); items.add(new ItemDto(2, CHAPTER_8TH_PGM_ID_NUM,CHAPTER_8TH_PGM_ID_NUM)); items.add(new ItemDto(3, CHAPTER_8TH_PGM_DESKEW, CHAPTER_8TH_PGM_DESKEW)); } if(chapterNum == 9) { items.add(new ItemDto(1, CHAPTER_9TH_PGM_II,CHAPTER_9TH_PGM_II)); items.add(new ItemDto(2, CHAPTER_9TH_PGM_EPF,CHAPTER_9TH_PGM_EPF)); items.add(new ItemDto(3, CHAPTER_9TH_PGM_MASK,CHAPTER_9TH_PGM_MASK)); items.add(new ItemDto(4, CHAPTER_9TH_PGM_FACE, CHAPTER_9TH_PGM_FACE)); } if(chapterNum == 10) { items.add(new ItemDto(1, CHAPTER_10TH_PGM,CHAPTER_10TH_PGM)); } return items; } }
package no.hiof.larseknu.jsonskriving.model; public class Superhelt { private String navn; private String alterEgo; public Superhelt(String navn, String alterEgo) { this.navn = navn; this.alterEgo = alterEgo; } public String getNavn() { return navn; } public void setNavn(String navn) { this.navn = navn; } public String getAlterEgo() { return alterEgo; } public void setAlterEgo(String alterEgo) { this.alterEgo = alterEgo; } @Override public String toString() { return navn; } }
package matth.dungeon.Utility; import android.content.Context; import java.util.ArrayList; import matth.dungeon.GameUI.Inventory; import matth.dungeon.GameUI.LevelTile; public class LevelTileGenerationUtility { private MainUtility mainUtility; private ArrayList<ArrayList<LevelTile>> levelMap = new ArrayList<>(); public LevelTileGenerationUtility(MainUtility mainUtility) { this.mainUtility = mainUtility; } public ArrayList<ArrayList<LevelTile>> initLevel(int size, DungeonInitUtility dungeonInitUtility) { if (!dungeonInitUtility.loadSave()) { initMap(size); genEnemies(); genItems(); genEnd(); genStart(); } else { loadLevel(dungeonInitUtility); } if (!dungeonInitUtility.loadSave() && !dungeonInitUtility.loadPlayer()) { genPlayerInfo(mainUtility.getCon()); } FileUtility.saveMap(mainUtility.getCon(), levelMap); return levelMap; } private void initMap(int size) { for (int i = 0; i < size; i++) { levelMap.add(i, new ArrayList<LevelTile>()); for (int j = 0; j < size; j++) { levelMap.get(i).add(j, new LevelTile(LevelTile.WALL)); } } createLevel(); //set all outer tiles to wall for (int i = 0; i < levelMap.size(); i++) { getTile(i, 0).setType(LevelTile.WALL); getTile(i, levelMap.size() -1).setType(LevelTile.WALL); } for (int i = 0; i < levelMap.size(); i++) { getTile(0, i).setType(LevelTile.WALL); getTile(levelMap.size() - 1, i).setType(LevelTile.WALL); } } private void loadLevel(DungeonInitUtility dungeonInitUtility) { levelMap = FileUtility.loadMap(mainUtility.getCon()); int pos[] = getPos(); if (dungeonInitUtility.deleteCurrentTile()) { getTile(pos[0], pos[1]).setEvent(LevelTile.EMPTY); getTile(pos[0], pos[1]).setType(LevelTile.PLAYER_POS); } } private void createLevel() { int tunnelLength = (int) (levelMap.size() * 0.7); int tunnelNum = (levelMap.size() * 2); int currentRow = (int) Math.floor(Math.random() * (levelMap.size() - 1)) + 1; int currentCol = (int) Math.floor(Math.random() * (levelMap.size() - 1)) + 1; int lastDir = -10; int randDir; int randLength; int currentLength; while (tunnelNum > 0 && tunnelLength > 0) { do { randDir = (int) (Math.random() * 4); } while (randDir == lastDir || Math.abs(randDir - lastDir) == 2); randLength = (int) Math.ceil(Math.random() * tunnelLength); currentLength = 0; while (currentLength < randLength && !(currentRow <= 1 && randDir == 0 || currentCol >= levelMap.size() - 2 && randDir == 1 || currentRow >= levelMap.size() - 2 && randDir == 2 || currentCol <= 1 && randDir == 3)) { getTile(currentCol, currentRow).setType(LevelTile.EMPTY); if (randDir == 0) { currentRow--; } else if (randDir == 1) { currentCol++; } else if (randDir == 2) { currentRow++; } else if (randDir == 3) { currentCol--; } currentLength++; } if (currentLength > 0) { lastDir = randDir; tunnelNum--; } } } private void genEnemies() { for (int i = 0; i < levelMap.size()/5; i++) { int enemyCol; int enemyRow; do { enemyCol = (int) Math.floor(Math.random() * (levelMap.size() - 1)) + 1; enemyRow = (int) Math.floor(Math.random() * (levelMap.size() - 1)) + 1; } while (cannotGen(enemyCol, enemyRow)); getTile(enemyCol, enemyRow).setEvent(LevelTile.ENEMY_EVENT); int numEnemies = (int)(Math.random() * 4) + 2; for (int j = 0; j < numEnemies; j++) { //TODO change enemy generation int randEnemy = (int)(Math.random() * LevelTile.ENEMY_TYPES.size()); getTile(enemyCol, enemyRow).addEnemy(randEnemy); } } } private void genItems() { for (int i = 0; i < levelMap.size()/4; i++) { int itemCol; int itemRow; do { itemCol = (int) Math.floor(Math.random() * (levelMap.size() - 1)) + 1; itemRow = (int) Math.floor(Math.random() * (levelMap.size() - 1)) + 1; } while (cannotGen(itemCol, itemRow)); getTile(itemCol, itemRow).setEvent(LevelTile.ITEM_EVENT); getTile(itemCol, itemRow).setRandomEvent(genRandomEvent()); } } private void genStart() { int playerRow; int playerCol; do { playerRow = (int) Math.floor(Math.random() * (levelMap.size() - 1)) + 1; playerCol = (int) Math.floor(Math.random() * (levelMap.size() - 1)) + 1; } while (cannotGen(playerCol, playerRow)); getTile(playerCol, playerRow).setType(LevelTile.PLAYER_POS); } private void genEnd() { int col; int row; do { row = (int) Math.floor(Math.random() * (levelMap.size() - 1)) + 1; col = (int) Math.floor(Math.random() * (levelMap.size() - 1)) + 1; } while(cannotGen(col, row)); getTile(col, row).setEvent(LevelTile.END_POS); getTile(col, row).addBoss(1); //temp boss adding } private void genPlayerInfo(Context con) { PlayerInfoPassUtility playerInfoPassUtility = new PlayerInfoPassUtility(); FileUtility.savePlayer(playerInfoPassUtility, con); Inventory inventory = new Inventory(); FileUtility.saveInventory(inventory, con); } private boolean cannotGen(int col, int row) { return !(getTile(col, row).getType() == LevelTile.EMPTY && getTile(col, row).getEvent() == LevelTile.NO_EVENT); } private int[] getPos() { int col = 1; int row = 1; for (int i = 0; i < levelMap.size(); i++) { for (int j = 0; j < levelMap.get(i).size(); j++) { if (levelMap.get(i).get(j).getType() == LevelTile.PLAYER_POS) { col = i; row = j; break; } } } return new int[]{col, row}; } private int genRandomEvent() { return (int)(Math.random() * LevelTile.RANDOM_EVENT_TYPES.size()); } private LevelTile getTile(int col, int row) { return levelMap.get(col).get(row); } }
package entities.fields.ownable; import java.util.Properties; import desktop_resources.GUI; import entities.fields.abstracts.Field; import entities.fields.abstracts.Ownable; import game.Account; import game.Player; public class Territory extends Ownable { private int rent[] = new int [6]; private String groupName; private int houses; private int hotels; private final int MAX_HOUSES = 4; private final int MAX_HOTELS = 1; private final int HOUSE_PRICE = 500; private final int HOTEL_PRICE = 2000; /** * Creates a territory field * * @param name * Field name (string) * @param description * Field description (string) * @param price * Field Ownable price (int) * @param rent * rent (int) */ public Territory(String name, String description, String groupName, int fieldID, int price, int[] rent) { super(name, description, fieldID, price); this.rent = rent; this.houses = 0; this.hotels = 0; this.groupName = groupName; } public Territory() //konstruktør uden parametre, som bruges til getOwnedFieldsOfType, da den kun bruger typen af felt, og ikke behøver alle parametrene { super("", "", 0, 0); // TODO Auto-generated constructor stub } @Override public int getRent() { return rent[houses + hotels]; } @Override public void landOnField(Player player) { if (player == owner) { GUI.showMessage("You own this field"); } /** * If the field is not owned, the player is asked whether he wants to buy * the field or not It then checks the player's balance to see if there * is sufficient money If the player buys the field he is set as the * owner and withdraws the price from the players account The GUI is * updated with the correct information */ else if (owner == null && player.getAccount().getBalance() >= price) { if (GUI.getUserLeftButtonPressed("Do you want to buy this field", "Yes", "No")) { owner = player; GUI.showMessage("You are the proud owner of this."); //GUI isn't 0 indexed so we add 1 GUI.setOwner(fieldID + 1, owner.getName()); player.getAccount().withdraw(price); GUI.setBalance(player.getName(), player.getAccount().getBalance()); } } /** * If the player is not the owner it then withdraws the rent of the * given field and deposit it on the players account */ else if (owner != null && owner != player) { if (owner.getJailed()== false) { owner.getAccount().deposit(player.getAccount().withdraw(getRent())); GUI.setBalance(player.getName(), player.getAccount().getBalance()); GUI.setBalance(owner.getName(), owner.getAccount().getBalance()); } else{ GUI.showMessage("The owner is jailed so you pass through without paying him money"); } } /** * If the players balance is too low, when buying a field - the GUI shows * a message */ else if (price > player.getAccount().getBalance()) { GUI.showMessage("Your balance is too low"); } } /** * Returns the price of a given field */ public int getPrice() { return price; } /** * Returns the owner of a given field */ public Player getOwner() { return owner; } /** * Sets the owner of a given field */ public void setOwner(Player player) { // TODO Auto-generated method stub owner = player; } public int getNumberOfHouses() { return this.houses; } public int getNumberOfHotels() { return this.hotels; } public int getMaxNumberOfHouses() { return this.MAX_HOUSES; } public int getMaxNumberOfHotels() { return this.MAX_HOTELS; } public String[] getPossibleBuildings() { // int maximumNumberOfBuildings = this.MAX_HOUSES + this.MAX_HOTELS; //If they already have the maximum number of hotels we return null if(this.hotels == this.MAX_HOTELS) return null; //Get possible houses int numberOfHousesLeft = this.MAX_HOUSES - this.houses; String[] possibleHouses = new String[numberOfHousesLeft]; int w = 0; for(int i = numberOfHousesLeft; i >= 1; i--) { possibleHouses[w] = "Houses: " + (this.MAX_HOUSES - i +1); w++; } //Get possible Hotels int numberOfHotelsLeft = this.MAX_HOTELS - this.hotels; String[] possibleHotels = new String[numberOfHotelsLeft]; w = 0; for(int i = numberOfHotelsLeft; i >= 1; i--) { possibleHotels[w] = "Hotel: " + (this.MAX_HOTELS - i + 1); w++; } return concatString(possibleHouses, possibleHotels); } public int getNumberOfFieldsInGroup(Territory territory, Field[] allFields) { int i = 0; for(Field field : allFields) { if(field instanceof Territory && ((Territory) field).getGroupName().equals(territory.getGroupName())) i++; } return i; //finder antal grønne felter } public boolean isTerritoryBuildable(Territory territory, Field[] playerFields, Field[] allFields) { int i = 0; for(Field field : playerFields) { if( field instanceof Territory && ((Territory) field).getGroupName().equals(territory.getGroupName()) ) i++; } if(i == getNumberOfFieldsInGroup(territory, allFields)) return true; else return false; } public String getGroupName() { return this.groupName; } public void buyBuildings(String buildingType, int numberOfBuildings, Player player) { Account account = player.getAccount(); if(buildingType == "Hotel") { int hotelPrice = ((this.MAX_HOUSES - this.getNumberOfHouses()) * this.HOUSE_PRICE) + (this.HOTEL_PRICE * numberOfBuildings); if(hotelPrice >= account.getBalance()) { GUI.showMessage("You can't afford to buy a hotel"); } else { account.withdraw(hotelPrice); this.hotels = numberOfBuildings; this.houses = this.MAX_HOUSES; GUI.setHotel(this.fieldID+1, true); } } else if(buildingType == "House") { int housePrice = HOUSE_PRICE * (numberOfBuildings - houses); if(housePrice >= account.getBalance()) { GUI.showMessage("You can't afford to buy a house"); } else { account.withdraw(housePrice); this.houses = numberOfBuildings; GUI.setHouses(this.fieldID+1, this.houses); } } GUI.setBalance(player.getName(), player.getAccount().getBalance()); } public String[] concatString(String[] a, String[] b) { int aLen = a.length; int bLen = b.length; String[] c= new String[aLen+bLen]; System.arraycopy(a, 0, c, 0, aLen); System.arraycopy(b, 0, c, aLen, bLen); return c; } }
public class Frame { private int address; private boolean refBit = false; public Frame(int addr) { this.address = addr; } public Frame(int addr, boolean ref) { this.address = addr; this.refBit = ref; } public void setSecondChance() { this.refBit = true; } public boolean getBit() { return this.refBit; } @Override public String toString() { return "page:" + this.address + " ref:" + this.refBit; } @Override public boolean equals(Object o) { Frame fr = (Frame)o; return fr.address == this.address; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package validator; import domain.Range; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; /** * * @author Przemysław Pająk <bespider@gmail.com> */ public class RangeValidator implements Validator { public boolean supports(Class aClass) { return aClass.equals(Range.class); } public void validate(Object obj, Errors errors) { Range range = (Range)obj; if (range == null) { errors.rejectValue("name", "field.required", null, "Wartość wymagana."); } ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "field.required", "Pole wymagane"); } }
package com.wiipu.mall.activity; import com.wiipu.mall.R; import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; /** * 注册和登录Activity */ public class LoginActivity extends Activity { private ImageButton ibBack; private EditText etAccount; private EditText etPassword; private Button btnLogin; private Button btnRegister; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); initView(); } /** * 初始化视图 */ private void initView() { ibBack = (ImageButton) findViewById(R.id.login_ib_back); ibBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); MyWatcher watcher = new MyWatcher(); etAccount = (EditText) findViewById(R.id.login_et_account); etAccount.addTextChangedListener(watcher); etPassword = (EditText) findViewById(R.id.login_et_password); etPassword.addTextChangedListener(watcher); btnLogin = (Button) findViewById(R.id.login_btn_login); btnLogin.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } }); btnRegister = (Button) findViewById(R.id.login_btn_register); btnRegister.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { } }); } /** * 监听文本框 */ class MyWatcher implements TextWatcher { @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { if ("".equals(etAccount.getText().toString()) || "".equals(etPassword.getText().toString())) { btnLogin.setEnabled(false); btnRegister.setEnabled(false); } else { btnLogin.setEnabled(true); btnRegister.setEnabled(true); } } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void afterTextChanged(Editable arg0) { } } }
package com.cricmania.models; import java.util.Date; public class Base { @javax.persistence.Id protected String id; protected Date createdOn = new Date(); public String getId() { return id; } public void setId(String id) { this.id = id; } public Date getCreatedOn() { return createdOn; } public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } }
package genscript.defaultops.math; import genscript.execution.ExecuterTreeNodeEager; import genscript.parse.IndexReader; import scriptinterface.defaulttypes.GInteger; import scriptinterface.defaulttypes.GVector; import scriptinterface.execution.ExecutionScope; import scriptinterface.execution.returnvalues.ExecutionErrorMessage; import scriptinterface.execution.returnvalues.ExecutionResult; import scriptinterface.execution.returnvalues.ExecutionReturn; import java.util.Vector; public class OpGetVectorElem<ScopeType extends ExecutionScope, ReaderType extends IndexReader> extends ExecuterTreeNodeEager<ScopeType, ReaderType> { @Override public ExecutionReturn derivExecute(ScopeType scope, ExecutionResult<?>[] executedChildren) { Vector<? extends ExecutionResult<?>> vec = ((GVector) executedChildren[0]).getValue(); int index = ((GInteger) executedChildren[1]).getValue(); if (vec.size() == 0) return new ExecutionErrorMessage("Vector size is 0 (index=" + index + ").", "VECTOR_ACCESS"); if (index < 0 || index >= vec.size()) return new ExecutionErrorMessage("Vector index out of bounds (index: " + index + ", valid: 0 to " + (vec .size() - 1) + ").", "VECTOR_ACCESS"); return vec.get(index); } @Override public String getName() { return "getVectorElem"; } @Override public String getSign() { return "vecElem"; } @Override protected String getSignatureString() { return "GetVectorElem(vector:Vector; Index:Integer) : Any"; } }
package ExerDay32; import java.util.*; public class Count2 { public static void main(String[] args) { System.out.println(countNumberOf2s(1000)); } public static int countNumberOf2s(int n) { int count = 0; for(int i = 0;i < n+1;i++){ for(int j = i;j > 0;j /= 10){ if(j%10 == 2){ count++; } } } return count; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.caisa.planilla.entity; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * * @author NCN00973 */ @Entity @Table(name = "tipos_de_cuenta_banco") @XmlRootElement @NamedQueries({ @NamedQuery(name = "TiposDeCuentaBanco.findAll", query = "SELECT t FROM TiposDeCuentaBanco t"), @NamedQuery(name = "TiposDeCuentaBanco.findByIdTiposCuenta", query = "SELECT t FROM TiposDeCuentaBanco t WHERE t.idTiposCuenta = :idTiposCuenta"), @NamedQuery(name = "TiposDeCuentaBanco.findByDescripcion", query = "SELECT t FROM TiposDeCuentaBanco t WHERE t.descripcion = :descripcion"), @NamedQuery(name = "TiposDeCuentaBanco.findByCodCuenta", query = "SELECT t FROM TiposDeCuentaBanco t WHERE t.codCuenta = :codCuenta"), @NamedQuery(name = "TiposDeCuentaBanco.findByNombreCuenta", query = "SELECT t FROM TiposDeCuentaBanco t WHERE t.nombreCuenta = :nombreCuenta")}) public class TiposDeCuentaBanco implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id_tipos_cuenta") private Integer idTiposCuenta; @Column(name = "descripcion") private String descripcion; @Column(name = "cod_cuenta") private String codCuenta; @Column(name = "nombre_cuenta") private String nombreCuenta; public TiposDeCuentaBanco() { } public TiposDeCuentaBanco(Integer idTiposCuenta) { this.idTiposCuenta = idTiposCuenta; } public Integer getIdTiposCuenta() { return idTiposCuenta; } public void setIdTiposCuenta(Integer idTiposCuenta) { this.idTiposCuenta = idTiposCuenta; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getCodCuenta() { return codCuenta; } public void setCodCuenta(String codCuenta) { this.codCuenta = codCuenta; } public String getNombreCuenta() { return nombreCuenta; } public void setNombreCuenta(String nombreCuenta) { this.nombreCuenta = nombreCuenta; } @Override public int hashCode() { int hash = 0; hash += (idTiposCuenta != null ? idTiposCuenta.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof TiposDeCuentaBanco)) { return false; } TiposDeCuentaBanco other = (TiposDeCuentaBanco) object; if ((this.idTiposCuenta == null && other.idTiposCuenta != null) || (this.idTiposCuenta != null && !this.idTiposCuenta.equals(other.idTiposCuenta))) { return false; } return true; } @Override public String toString() { return "com.caisa.planilla.entity.TiposDeCuentaBanco[ idTiposCuenta=" + idTiposCuenta + " ]"; } }
package com.example.demo.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.demo.entity.Course; import com.example.demo.entity.Student; import com.example.demo.repository.CourseRepository; import com.example.demo.service.CourseService; @Service public class CourseServiceImpl implements CourseService{ @Autowired CourseRepository courseRepo; @Override public void deleteCourse(Course course) { // TODO Auto-generated method stub courseRepo.delete(course); } @Override public Course createCourse(Course course) { // TODO Auto-generated method stub return courseRepo.save(course); } @Override public Course updateCourse(Course course) { // TODO Auto-generated method stub return courseRepo.save(course); } @Override public List<Course> getAll() { // TODO Auto-generated method stub return courseRepo.findAll(); } @Override public Course getById(long id) { // TODO Auto-generated method stub return courseRepo.findById(id).orElse(null); } @Override public List<Course> getByStudent(Student student) { // TODO Auto-generated method stub return courseRepo.findByStudents(student); } @Override public List<Course> searchByName(String name) { // TODO Auto-generated method stub return courseRepo.findByNameContainingAllIgnoreCase(name); } }
package com.example.lastminute.Trips; import android.app.usage.NetworkStats; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentTransaction; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.lastminute.Login.LoginPage; import com.example.lastminute.R; import com.firebase.ui.firestore.FirestoreRecyclerOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; 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.ValueEventListener; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.Query; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class TripsFragment extends Fragment implements FirebaseAuth.AuthStateListener, TripsEntryRecyclerAdapter.TripListener { private FloatingActionButton addTripsButton; private RecyclerView trips_recycler; TripsEntryRecyclerAdapter addTripsAdapter; private static final String TAG = "TripsFragment"; FirebaseUser u; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_trips, container, false); setUpUIView(v); entry(); addDividerInRecyclerView(); initializeRecyclerView(FirebaseAuth.getInstance().getCurrentUser()); LinearLayoutManager llm = new LinearLayoutManager(this.getActivity()); llm.setOrientation(LinearLayoutManager.VERTICAL); trips_recycler.setLayoutManager(llm); recyclerViewActions(); return v; } private void setUpUIView(View v) { // declaring elements addTripsButton = (FloatingActionButton) v.findViewById(R.id.addTripsButton); trips_recycler = (RecyclerView) v.findViewById(R.id.trips_recycler); } private void entry() { // transiting to add trips addTripsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getActivity(), TripsEntry.class)); } }); } @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { // ensure user is logged in if not direct to login page if (firebaseAuth.getCurrentUser() == null) { startActivity(new Intent(getActivity(), LoginPage.class)); return; } } @Override public void onStart() { // assign authStateListener super.onStart(); FirebaseAuth.getInstance().addAuthStateListener(this); } @Override public void onStop() { // remove authStateListener super.onStop(); FirebaseAuth.getInstance().removeAuthStateListener(this); // if (addTripsAdapter != null) { // addTripsAdapter.stopListening(); // } } private void initializeRecyclerView(FirebaseUser user) { u = user; Query query = FirebaseFirestore.getInstance() .collection("Trips") .whereEqualTo("userID", user.getUid()); FirestoreRecyclerOptions<TripEntryDetails> options = new FirestoreRecyclerOptions.Builder<TripEntryDetails>() .setQuery(query, TripEntryDetails.class) .build(); addTripsAdapter = new TripsEntryRecyclerAdapter(options, this); trips_recycler.setAdapter(addTripsAdapter); addTripsAdapter.startListening(); } private void addDividerInRecyclerView() { // margin between each each item DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL); trips_recycler.addItemDecoration(divider); } private void recyclerViewActions() { new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { switch (direction) { case ItemTouchHelper.LEFT: case ItemTouchHelper.RIGHT: addTripsAdapter.deleteItem(viewHolder.getAdapterPosition()); Toast.makeText(getActivity(), "Trip Deleted", Toast.LENGTH_SHORT).show(); break; } } }).attachToRecyclerView(trips_recycler); } @Override public void handleEditTrip(DocumentSnapshot snapshot, View v) { TripEntryDetails tripEntryDetails = snapshot.toObject(TripEntryDetails.class); String tripName = tripEntryDetails.getTripName().toString(); String tripPlace = tripEntryDetails.getTripPlace().toString(); String startDate = tripEntryDetails.getStartDate().toString(); String endDate = tripEntryDetails.getEndDate().toString(); String pathToTripDoc = snapshot.getReference().getPath(); Intent intent = new Intent(getActivity(), TripsEdit.class); intent.putExtra("tripName", tripName); intent.putExtra("tripPlace", tripPlace); intent.putExtra("startDate", startDate); intent.putExtra("endDate", endDate); intent.putExtra("pathToTripDoc", pathToTripDoc); v.getContext().startActivity(intent); } @Override public void handleActivities(DocumentSnapshot snapshot, View v) { String pathToTripDoc = snapshot.getReference().getPath(); Intent intent = new Intent(getActivity(), TripActivities.class); intent.putExtra("pathToTripDoc", pathToTripDoc); v.getContext().startActivity(intent); } @Override public void handleShareTrip(DocumentSnapshot snapshot, View v) { TripEntryDetails tripEntryDetails = snapshot.toObject(TripEntryDetails.class); final String tripName = tripEntryDetails.getTripName().toString(); final String tripPlace = tripEntryDetails.getTripPlace().toString(); final String startDate = tripEntryDetails.getStartDate().toString(); final String endDate = tripEntryDetails.getEndDate().toString(); FirebaseFirestore.getInstance() .document(snapshot.getReference().getPath()).collection("Activities") .whereEqualTo("userID", u.getUid()) // .orderBy("activityDate", Query.Direction.ASCENDING) // .orderBy("activityTime", Query.Direction.ASCENDING) // .orderBy("activityName", Query.Direction.ASCENDING) // .orderBy("activityPlace", Query.Direction.ASCENDING) .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { StringBuilder shareSubject = new StringBuilder(); StringBuilder shareBody = new StringBuilder(); shareSubject.append("Check out my itinerary to ").append(tripPlace).append("!"); shareBody.append("TRIP DETAILS\n") .append("Trip Name: " + tripName + "\n") .append("Destination: " + tripPlace + "\n") .append("Duration: " + startDate + " to " + endDate); if (task.getResult().size() != 0) { shareBody.append("\n\nACTIVITIES\n"); } for (QueryDocumentSnapshot document : task.getResult()) { Map<String,Object> activity = document.getData(); String activityName = activity.get("activityName").toString(); String activityPlace = activity.get("activityPlace").toString(); String activityDate = activity.get("activityDate").toString(); String activityTime = activity.get("activityTime").toString(); String activityDescription = activity.get("activityDescription").toString(); shareBody.append(activityDate + " " + activityTime + " - " + activityName + " at " + activityPlace + "\n"); if (activityDescription != "") { shareBody.append("Details: " + activityDescription + "\n"); } } if (task.getResult().size() > 0) { shareBody.deleteCharAt(shareBody.length() - 1); } Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, shareBody.toString()); intent.putExtra(Intent.EXTRA_SUBJECT, shareSubject.toString()); startActivity(Intent.createChooser(intent, "Share via")); } else { Log.d(TAG, "Error getting documents: ", task.getException()); } } }); } }
/* * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. * * 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.tolunayozturk.barrierdemo; import android.Manifest; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.widget.Chronometer; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import com.huawei.hms.analytics.HiAnalytics; import com.huawei.hms.analytics.HiAnalyticsInstance; import com.huawei.hms.kit.awareness.Awareness; import com.huawei.hms.kit.awareness.barrier.AwarenessBarrier; import com.huawei.hms.kit.awareness.barrier.BarrierQueryRequest; import com.huawei.hms.kit.awareness.barrier.BarrierStatus; import com.huawei.hms.kit.awareness.barrier.BarrierUpdateRequest; import com.huawei.hms.kit.awareness.barrier.LocationBarrier; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; import java.util.function.Consumer; public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); private static final String ENTER_BARRIER_LABEL = "ENTER_BARRIER_LABEL"; private static final String EXIT_BARRIER_LABEL = "EXIT_BARRIER_LABEL"; private PendingIntent mPendingIntent; private LocationBarrierReceiver mBarrierReceiver; HiAnalyticsInstance mHiAnalytics; CloudDBHelper mCloudDBHelper; String userId; double latitude = 41.02456; double longitude = 28.85843; double radius = 250; Chronometer mChronometer; TextView tv_log; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_log = findViewById(R.id.tv_log); mChronometer = findViewById(R.id.chronometer); mHiAnalytics = HiAnalytics.getInstance(this); mCloudDBHelper = CloudDBHelper.getInstance(this); userId = getIntent().getStringExtra("userId"); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED) { printLog("Permission(s) denied!"); return; } final String BARRIER_RECEIVER_ACTION = getApplication().getPackageName() + "LOCATION_BARRIER_RECEIVER_ACTION"; Intent intent = new Intent(BARRIER_RECEIVER_ACTION); mPendingIntent = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); mBarrierReceiver = new LocationBarrierReceiver(); registerReceiver(mBarrierReceiver, new IntentFilter(BARRIER_RECEIVER_ACTION)); Awareness.getBarrierClient(this).queryBarriers(BarrierQueryRequest.all()) .addOnSuccessListener(barrierQueryResponse -> { AwarenessBarrier enterBarrier = LocationBarrier.enter( latitude, longitude, radius); AwarenessBarrier exitBarrier = LocationBarrier.exit( latitude, longitude, radius); if (barrierQueryResponse.getBarrierStatusMap().getBarrierLabels() .contains(ENTER_BARRIER_LABEL)) { removeBarrier(ENTER_BARRIER_LABEL, res -> { if (res) { addBarrier(this, ENTER_BARRIER_LABEL, enterBarrier, mPendingIntent); } }); } else { addBarrier(this, ENTER_BARRIER_LABEL, enterBarrier, mPendingIntent); } if (barrierQueryResponse.getBarrierStatusMap().getBarrierLabels() .contains(EXIT_BARRIER_LABEL)) { removeBarrier(EXIT_BARRIER_LABEL, res -> { if (res) { addBarrier(this, EXIT_BARRIER_LABEL, exitBarrier, mPendingIntent); } }); } else { addBarrier(this, EXIT_BARRIER_LABEL, exitBarrier, mPendingIntent); } }).addOnFailureListener(e -> Log.e(TAG, e.getMessage(), e)); // // Test event // Bundle bundle = new Bundle(); // bundle.putString("test_key2", "test_value2"); // mHiAnalytics.onEvent("TEST_EVENT2", bundle); } private void addBarrier(Context context, final String label, AwarenessBarrier barrier, PendingIntent pendingIntent) { BarrierUpdateRequest.Builder builder = new BarrierUpdateRequest.Builder(); BarrierUpdateRequest request = builder.addBarrier(label, barrier, pendingIntent).build(); Awareness.getBarrierClient(context).updateBarriers(request) .addOnSuccessListener(aVoid -> { Toast.makeText(context, "add " + label + " success", Toast.LENGTH_SHORT).show(); Log.i(TAG, "add " + label + " success"); }) .addOnFailureListener(e -> { Toast.makeText(context, "add " + label + " failed", Toast.LENGTH_SHORT).show(); Log.e(TAG, "add " + label + " failed", e); }); } private void removeBarrier(String label, Consumer<Boolean> result) { BarrierUpdateRequest.Builder builder = new BarrierUpdateRequest.Builder(); builder.deleteBarrier(label); Awareness.getBarrierClient(this) .updateBarriers(builder.build()).addOnSuccessListener(aVoid -> { Log.i(TAG, "removeBarrier: success"); result.accept(true); }).addOnFailureListener(e -> { Log.e(TAG, "removeBarrier: " + e.getMessage(), e); result.accept(false); }); } private void printLog(String msg) { DateFormat formatter = SimpleDateFormat.getDateTimeInstance(); String time = formatter.format(new Date(System.currentTimeMillis())); tv_log.append("[" + time + "] " + msg + "\n"); } @Override protected void onDestroy() { if (mBarrierReceiver != null) { unregisterReceiver(mBarrierReceiver); } super.onDestroy(); } final class LocationBarrierReceiver extends BroadcastReceiver { private final String TAG = LocationBarrierReceiver.class.getSimpleName(); @Override public void onReceive(Context context, Intent intent) { BarrierStatus barrierStatus = BarrierStatus.extract(intent); String label = barrierStatus.getBarrierLabel(); switch (barrierStatus.getPresentStatus()) { case BarrierStatus.TRUE: Log.i(TAG, "[" + label + "]" + " BarrierStatus: TRUE"); printLog("[" + label + "]" + " BarrierStatus: TRUE"); if (label.equals("ENTER_BARRIER_LABEL")) { mChronometer.setBase(SystemClock.elapsedRealtime()); mChronometer.start(); } else if (label.equals("EXIT_BARRIER_LABEL")) { mChronometer.stop(); double elapsedMillis = SystemClock.elapsedRealtime() - mChronometer.getBase(); printLog("Length of stay: " + elapsedMillis / 1000 + " seconds"); Log.e(TAG, "Length of stay: " + elapsedMillis); // Send lengthOfStay via a custom event to Analytics Bundle bundle = new Bundle(); bundle.putDouble("length_of_stay", elapsedMillis / 1000); mHiAnalytics.onEvent("LENGTH_OF_STAY", bundle); // Send lengthOfStay to CloudDB User user = new User(); user.setId(UUID.randomUUID().toString()); user.setUserId(userId); user.setLengthOfStay(elapsedMillis / 1000); mCloudDBHelper.upsertUser(user, res -> { if (res) { mCloudDBHelper.queryAverage(avgResult -> { printLog("Average length of stay: " + avgResult); }); } }); } break; case BarrierStatus.FALSE: Log.i(TAG, "[" + label + "]" + " BarrierStatus: FALSE"); printLog("[" + label + "]" + " BarrierStatus: FALSE"); break; case BarrierStatus.UNKNOWN: Log.i(TAG, "[" + label + "]" + " BarrierStatus: UNKNOWN"); printLog("[" + label + "]" + " BarrierStatus: UNKNOWN"); break; } } } }
package com.empwagepackages.test; import com.empwagepackages.model.EmpWagePackage; public class EmpWagePackageTest{ public static void main(String[] arg){ EmpWagePackage emp=new EmpWagePackage(); double EmpCheck=Math.floor(Math.random()*10)%2; System.out.println(emp.DisplayMessage(EmpCheck)); } }
package com.ttan.linkedList; /** * @Description: * @author ttan * @time 2019年12月24日 下午5:52:45 */ public class DeleteDuplication { public static ListNode deleteDuplication(ListNode pHead) { if (pHead == null) { return null; } // 备用头节点,因为头节点可能删除 ListNode firstNode = new ListNode(-1); firstNode.next = pHead; ListNode cur = pHead; // 前节点 ListNode pre = firstNode; while (cur != null && cur.next != null) { // 两节点相等 if (cur.val == cur.next.val) { // 记录val值,循环判断后面是否有相同值的节点 int val = cur.val; // 循环跳过,删除 while (cur != null && cur.val == val) { cur = cur.next; } // 删除操作,直接指向不同于val值的第一个节点 pre.next = cur; }else{ pre = cur; cur = cur.next; } } return firstNode.next; } public static void main(String[] args) { ListNode pHead = new ListNode(1); ListNode listNode = new ListNode(2); ListNode listNode2 = new ListNode(3); ListNode listNode3 = new ListNode(3); ListNode listNode4 = new ListNode(4); ListNode listNode5 = new ListNode(4); ListNode listNode6 = new ListNode(5); pHead.next = listNode; listNode.next = listNode2; listNode2.next = listNode3; listNode3.next = listNode4; listNode4.next = listNode5; listNode5.next = listNode6; System.out.println(deleteDuplication(pHead)); } }
package com.shopguide.webservice; public class GoogleServices { }
package net.crunchdroid.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import javax.persistence.*; @Data @NoArgsConstructor @AllArgsConstructor @Entity public class EntraineurDescipline { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @ManyToOne @OnDelete(action = OnDeleteAction.CASCADE) private Entraineur entraineur; @ManyToOne @OnDelete(action = OnDeleteAction.CASCADE) private Descipline descipline; }
package com.yida.design.command.generator; /** ********************* * 接收者角色 * * @author yangke * @version 1.0 * @created 2018年5月12日 上午10:51:04 *********************** */ public abstract class AbstractReceiver { // 定义每个接收者都必须完成的业务 public abstract void doSomething(); }
package com.prokarma.reference.architecture.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Classification { @SerializedName("primary") @Expose public Boolean primary; @SerializedName("segment") @Expose public Segment segment; @SerializedName("genre") @Expose public Genre genre; @SerializedName("subGenre") @Expose public Genre subGenre; @SerializedName("family") @Expose public Boolean family; @SerializedName("type") @Expose public Type type; @SerializedName("subType") @Expose public Type subType; }
package com.quizcore.quizapp.model.repository; import com.quizcore.quizapp.model.entity.MediaContent; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.UUID; @Repository public interface MediaContentRepository extends CrudRepository<MediaContent, UUID> { }
package ua.lviv.iot.uklon.domain; import javax.persistence.*; import java.math.BigDecimal; import java.util.Objects; @Entity @Table(name = "passenger") public class Passenger { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Integer id; @Column(name = "name") private String name; @Column(name = "surname") private String surName; @Column(name = "tel_num") private String telNum; @OneToOne @JoinColumn(name = "credit_card_id", referencedColumnName = "id", nullable = false) private CreditCard creditCard; @Column(name = "rate") private BigDecimal rate; public Passenger() { } public Passenger(Integer id, String name, String surName, String telNum, CreditCard creditCard, BigDecimal rate) { this.id = id; this.name = name; this.surName = surName; this.telNum = telNum; this.creditCard = creditCard; this.rate = rate; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurName() { return surName; } public void setSurName(String surName) { this.surName = surName; } public String getTelNum() { return telNum; } public void setTelNum(String telNum) { this.telNum = telNum; } public CreditCard getCreditCard() { return creditCard; } public void setCreditCard(CreditCard creditCard) { this.creditCard = creditCard; } public BigDecimal getRate() { return rate; } public void setRate(BigDecimal rate) { this.rate = rate; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Passenger)) return false; Passenger passenger = (Passenger) o; return id.equals(passenger.id) && name.equals(passenger.name) && Objects.equals(surName, passenger.surName) && telNum.equals(passenger.telNum) && creditCard.equals(passenger.creditCard) && Objects.equals(rate, passenger.rate); } @Override public int hashCode() { return Objects.hash(id, name, surName, telNum, creditCard, rate); } @Override public String toString() { return "Passenger{" + "id=" + id + ", name='" + name + '\'' + ", surName='" + surName + '\'' + ", telNum='" + telNum + '\'' + ", creditCard=" + creditCard + ", rate=" + rate + '}'; } }
package com.cz.android.sample.tool; import android.content.Context; import java.util.Map; /** * @author Created by cz * @date 2020/8/6 12:03 PM * @email bingo110@126.com */ public interface ComponentAnalyzer { void registerComponent(Context context); boolean applyInstance(Class<?> clazz); void analysis(Context context,Class<?> clazz,Map<String,Long> traceMap); }
package boletin19_2; import java.util.Arrays; import javax.swing.JOptionPane; public class Programacion { int[] notas = new int[3]; private int aprobados = 0, suspensos = 0; // int [] numAprobados = new int[notas.length]; (tambien valdria haciendolo con arrays) // int [] numSuspensos = new int[notas.length]; public int darValores() { return Integer.parseInt(JOptionPane.showInputDialog("Introducir notas:")); } public void crearArray() { for (int i = 0; i < notas.length; i++) { notas[i] = darValores(); } } public void clasificarNotas(int[] notas) { for (int i = 0; i < notas.length; i++) { notas[i] = darValores(); if (notas[i] >= 5) { // numAprobados[aprobados++] = notas[i]; (alternativa al contador)) aprobados++; } else if (notas[i] < 5) { // numSuspensos[suspensos++] = notas[i]; suspensos++; } } } public void amosarAprobadosSuspensos() { System.out.println("Número de aprobados: " + aprobados + "\n" + "Número de suspensos: " + suspensos); } public void calcularMedia(int notas[]) { int suma = 0; int nele = notas.length; for (int i = 0; i < nele; i++) { notas[i] = darValores(); suma += notas[i]; } double media = suma / (double) nele; System.out.println("Nota media: " + media); } public void notaMaisAlta(int notas[]) { int max = notas[0]; for (int i = 0; i < notas.length; i++) { notas[i] = darValores(); if (notas[i] > max) { max = notas[i]; } } System.out.println("Nota más alta: " + max); } }
package com.betatest.canalkidsbeta.alarm; import java.util.Date; import android.app.IntentService; import android.content.Intent; import android.util.Log; import com.betatest.canalkidsbeta.bean.ChannelContentsResponseParcel; import com.betatest.canalkidsbeta.interfaces.AsyncTaskInterface; import com.betatest.canalkidsbeta.tasks.PojoLoaderTask; public class SchedulerEventService extends IntentService implements AsyncTaskInterface { private static final String APP_TAG = "com.betatest.canalkidsbeta"; private String channelContentsUrl = "https://s3.amazonaws.com/nativeapps/channel_kids/videos/channelkids_ios.json"; /** * A constructor is required, and must call the super IntentService(String) * constructor with a name for the worker thread. */ public SchedulerEventService() { super("CanalKidsBetaVideoListUpdate"); } /** * The IntentService calls this method from the default worker thread with * the intent that started the service. When this method returns, * IntentService stops the service, as appropriate. */ @Override protected void onHandleIntent(Intent intent) { Log.d(APP_TAG, "SERVICE CALLED AT: " + new Date().toString()); // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. PojoLoaderTask pojoLoaderTask = new PojoLoaderTask(this); pojoLoaderTask.delegate = this; pojoLoaderTask.execute(channelContentsUrl); } @Override public void processFinish(final ChannelContentsResponseParcel output) { Log.d(APP_TAG, "LOADED VIDEOS FROM JSON"); } }
package com.theincorrectclock.bsj; class Pair<E1, E2> { private E1 first; private E2 second; static <E1, E2> Pair<E1, E2> pair(E1 first, E2 second) { return new Pair<>(first, second); } private Pair(E1 first, E2 second) { this.first = first; this.second = second; } E1 getFirst() { return first; } E2 getSecond() { return second; } }
package lesson29.Ex1; public class Bird extends Animal { private String color; private String bestFood; //thức ăn chính private float wingspan; //sải cánh public Bird() { } public Bird(String name, String species, float height, float weight) { super(name, species, height, weight); } public final String getColor() { return color; } public final void setColor(String color) { this.color = color; } public final String getBestFood() { return bestFood; } public final void setBestFood(String bestFood) { this.bestFood = bestFood; } public final float getWingspan() { return wingspan; } public final void setWingspan(float wingspan) { this.wingspan = wingspan; } @Override void eat(String food) { System.out.println("Chim đang ăn " + food); } @Override void sleep() { System.out.println("Mấy con chim đang ngủ trong tổ"); } @Override void move() { System.out.println("Chim di chuyển bằng cách bay"); } @Override void relax() { System.out.println("Chim chơi đùa bằng cách lượn quanh bầu trời"); } }
package com.clienteapp.demo.service; import com.clienteapp.demo.entity.Ciudad; import java.util.List; public interface ICiudadService { List<Ciudad> listarCiudades(); public void guardarCiudad(Ciudad ciudad); }
package com.fleet.initializr.service.impl; import com.fleet.initializr.entity.Application; import org.springframework.stereotype.Service; import java.io.File; import java.util.HashMap; import java.util.Map; /** * @author April Han */ @Service public class PomGenerator extends BaseGenerator { public void generation(Application application) throws Exception { Map<String, String> map = new HashMap<>(); map.put("groupId", application.getGroupId()); map.put("artifactId", application.getArtifactId()); map.put("name", application.getName()); map.put("description", application.getDescription()); map.put("packaging", application.getPackaging()); map.put("version", application.getVersion()); String path = application.getLocation() + File.separator + application.getArtifactId() + "/"; File file = new File(path, "pom.xml"); super.write(file, "pom.ftl", map); } }
package ec.com.yacare.y4all.asynctask.ws; import android.os.AsyncTask; import android.provider.Settings; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import java.io.IOException; import ec.com.yacare.y4all.activities.DatosAplicacion; import ec.com.yacare.y4all.activities.luces.DetalleLucesFragment; import ec.com.yacare.y4all.lib.resources.YACSmartProperties; /** * Created by yacare on 25/01/2017. */ public class EliminarProgramacionAsyncTask extends AsyncTask<String, Float, String> { private DetalleLucesFragment fragment; private String idProgramacion; public EliminarProgramacionAsyncTask(DetalleLucesFragment fragment, String idProgramacion) { super(); this.fragment = fragment; this.idProgramacion = idProgramacion; } @Override protected String doInBackground(String... arg0) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(YACSmartProperties.URL_ELIMINAR_PROGRAMACION); httppost.setHeader("content-type", "application/x-www-form-urlencoded"); String respStr = ""; DatosAplicacion datosAplicacion = (DatosAplicacion) fragment.getApplicationContext(); try { StringEntity se = new StringEntity( "{\"eliminarProgramacion\":{\"numeroSerie\":\"" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie() + "\",\"token\":\""+ datosAplicacion.getToken() + "\",\"idDispositivo\":\""+ Settings.Secure.getString(fragment.getContentResolver(),Settings.Secure.ANDROID_ID) + "\",\"idProgramacion\":\"" + idProgramacion + "\"}}"); httppost.setEntity(se); HttpResponse resp = httpclient.execute(httppost); respStr = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8); Log.d("eliminarProgramacion",respStr); return respStr; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return respStr; } protected void onPostExecute(String resultado) { fragment.verificarEliminarProgramacion(resultado); } }
package p9; /** * A Direction class to keep track of what direction the mob is facing. * @author Matthew Eugene Swanson * */ public class Direction { public static final int UP = 0; public static final int DOWN = 1; public static final int LEFT = 2; public static final int RIGHT = 3; public int direction = 0; /** * construct with a direction to look * @param i the direction to start looking ex: Direction.DOWN */ public Direction(int i){ direction = i; } /** * use to get the current direction the mob is looking * @return the current facing direction */ public int looking(){ return direction; } /** * Returns what direction the the value is. example: directionAsString(Direction.DOWN); returns "DOWN" * @param i the direction code to return. ex: Direction.DOWN * @return the direction as a string. */ public String directionAsString(int i){ switch(i){ case (0): return "UP"; case (1): return "DOWN"; case (2): return "LEFT"; case (3): return "RIGHT"; } return "Error Direction.directionAsString(" + new Integer(i).toString() + ")"; } /** * change the active direction. * @param i the direction to change to. ex: setDirection(Direction.(UP||DOWN||LEFT||RIGHT)) */ public void setDirection(int i){ direction = i; } }
/** * DistributionBar.java (DistributionBar) * * Copyright 2012 Vaadin Ltd, Sami Viitanen <alump@vaadin.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vaadin.alump.distributionbar; import java.util.ArrayList; import java.util.List; import com.vaadin.shared.MouseEventDetails; import org.vaadin.alump.distributionbar.gwt.client.shared.DistributionBarServerRpc; import org.vaadin.alump.distributionbar.gwt.client.shared.DistributionBarState; import org.vaadin.alump.distributionbar.gwt.client.shared.DistributionBarState.Part; import com.vaadin.ui.AbstractComponent; /** * Server side component for the VDistributionBar widget. Distribution Bar is * simple graphical bar that can be used to show distribution of items between * different groups. For example distribution of YES and NO votes. Bar must have * at least two values, but there is not any upper limit. Layout where bar is * used can limit the amount of parts that will fit to screen. */ @SuppressWarnings("serial") public class DistributionBar extends AbstractComponent { private List<DistributionBarClickListener> clickListeners = new ArrayList<DistributionBarClickListener>(); private final DistributionBarServerRpc serverRpc = new DistributionBarServerRpc() { @Override public void onItemClicked(int index, MouseEventDetails mouseEventDetails) { DistributionBarClickEvent event = new DistributionBarClickEvent(DistributionBar.this, index, mouseEventDetails); for (DistributionBarClickListener listener : clickListeners) { listener.onDistributionBarClicked(event); } } }; /** * Will make distribution bar with 2 parts (size value zero). */ public DistributionBar() { this(2); } /** * Generate distribution bar with given number of parts. All parts created * will get the default size value: zero. * * @param numberOfParts * Number of parts. Must be 1 or more. */ public DistributionBar(int numberOfParts) { if(numberOfParts < 1) { throw new IllegalArgumentException("Distribution bar must have at least one part: " + numberOfParts + " parts given"); } registerRpc(serverRpc); for (int i = 0; i < numberOfParts; ++i) { getState().getParts().add(new Part()); } } /** * Create new distribution bar and define sizes for all parts * * @param sizes * Part sizes in integer array. Must have at least 2 sizes. If * less two parts are made with size zero. */ public DistributionBar(final double[] sizes) { this(sizes.length); this.updatePartSizes(sizes); } @Override public DistributionBarState getState() { return (DistributionBarState) super.getState(); } @Override public DistributionBarState getState(boolean markDirty) { return (DistributionBarState) super.getState(markDirty); } /** * Update multiple sizes once. If given list is smaller than number of parts * then parts at the end will not be updated. If given list has more sizes * than there is parts, then rest of the sizes are ignored. * * @param partSizes * Sizes in integer array */ public void updatePartSizes(double[] partSizes) { for (int i = 0; i < getNumberOfParts() && i < partSizes.length; ++i) { getState().getParts().get(i).setSize(partSizes[i]); } } /** * Setup part by defining both size and tooltip with one command * * @param index * Index of part [0..N]. Only give valid indexes. * @param size * Size as integer number * @param tooltip * Tooltip content is XHTML */ public void setupPart(int index, double size, String tooltip) { setupPart(index, size, tooltip, null); } /** * Setup part by defining size, tooltip and style name with one command * * @param index * Index of part [0..N]. Only give valid indexes. * @param size * Size of part (0.0 or larger) * @param tooltip * Tooltip content is XHTML * @param styleName * Stylename added to part */ public void setupPart(int index, double size, String tooltip, String styleName) { Part part = getState().getParts().get(index); part.setSize(size); part.setTooltip(tooltip); part.setTooltip(styleName); } /** * Change size of given part * * @param index * Index of part [0..N]. Only give valid indexes. * @param size * Size of part (0.0 or larger) * @return Reference to DistributionBar to allow call chaining */ public DistributionBar setPartSize(int index, double size) { if(size < 0.0) { throw new IllegalArgumentException("Size must be zero or larger"); } getState().getParts().get(index).setSize(size); return this; } /** * Change both size and caption of part * @param index * Index of part [0..N]. Only give valid indexes. * @param size * Size of part (0.0 or larger) * @param caption * Caption of part (null to show value) * @return Reference to DistributionBar to allow call chaining */ public DistributionBar setPartSize(int index, double size, String caption) { if(size < 0.0) { throw new IllegalArgumentException("Size must be zero or larger (" + size + ")"); } Part part = getState().getParts().get(index); part.setSize(size); part.setCaption(caption); return this; } /** * Get current size of part * @param index Index of part * @return Size of part (0 or larger) * @throws IndexOutOfBoundsException If invalid index is given */ public double getPartSize(int index) throws IndexOutOfBoundsException { return getState(false).getParts().get(index).getSize(); } /** * Change title of given part. This is normal HTML title attribute. For many * use cases tooltip is better option. * * @param index * Index of part [0..N]. Only give valid indexes. * @param title * Title for part * @return Reference to DistributionBar to allow call chaining */ public DistributionBar setPartTitle(int index, String title) { getState().getParts().get(index).setTitle(title); return this; } /** * Get current caption of part. If not null, will replace number in bar element. * @param index Index of part * @return Caption of part, null if size of part is used * @throws IndexOutOfBoundsException If invalid index is given */ public String getPartCaption(int index) { return getState(false).getParts().get(index).getTitle(); } /** * Change caption of given part. * * @param index * Index of part [0..N]. Only give valid indexes. * @param caption * Caption of part (null to show value) * @return Reference to DistributionBar to allow call chaining * */ public DistributionBar setPartCaption(int index, String caption) { getState().getParts().get(index).setCaption(caption); return this; } /** * Get current title of part * @param index Index of part * @return Title of part * @throws IndexOutOfBoundsException If invalid index is given */ public String getPartTitle(int index) { return getState().getParts().get(index).getTitle(); } /** * Change tooltip of given part. * * @param index * Index of part [0..N]. Only give valid indexes. * @param tooltip * Content of tooltip (empty is do not show tooltip). Content is * given in XHTML format. * @return Reference to DistributionBar to allow call chaining */ public DistributionBar setPartTooltip(int index, String tooltip) { getState(false).getParts().get(index).setTooltip(tooltip); return this; } /** * Change stylename of given part. * * @param index * Index of part [0..N]. Only give valid indexes. * @param styleName * Style name of part * @return Reference to DistributionBar to allow call chaining */ public DistributionBar setPartStyleName(int index, String styleName) { getState().getParts().get(index).setStyleName(styleName); return this; } /** * Get number of parts in distribution bar * * @return Number of parts in distribution bar */ public int getNumberOfParts() { return getState().getParts().size(); } private void changeStatePartsSize(int newSize) { while (getState().getParts().size() < newSize) { getState().getParts().add(new Part()); } while (getState().getParts().size() > newSize) { getState().getParts().remove(newSize); } } /** * Change number of parts in distribution bar. * * @param numberOfParts * New number of parts. If this is different than earlier number * of parts then all parts will be initialized to default state * with size zero. If given value is less than 2 it will be * converted to two. */ public void setNumberOfParts(int numberOfParts) { if (numberOfParts > 1 && getNumberOfParts() != numberOfParts) { changeStatePartsSize(numberOfParts); } } /** * Add click listener * @param listener Listener added to listeners */ public void addDistributionBarClickListener( DistributionBarClickListener listener) { if (clickListeners.isEmpty()) { getState().sendClicks = true; } clickListeners.add(listener); } /** * Remove click listener * @param listener Listener removed from listeners */ public void removeDistributionBarClickListener( DistributionBarClickListener listener) { clickListeners.remove(listener); if (clickListeners.isEmpty()) { getState().sendClicks = false; } } /** * Define if parts with size 0 should still be shown in distribution bar * @param zeroVisible true if zero sized are shown, false if shrunk to invisible */ public void setZeroSizedVisible(boolean zeroVisible) { getState().zeroVisible = zeroVisible; } /** * See if zero sized parts are shown or shrunk to invisible * @return true if zero sized are shown, false if shrunk to invisible */ public boolean isZeroSizedVisible() { return getState().zeroVisible; } /** * Define minimum with of part with value. Value will be overridden if there isn't enough space. * @param pixels With in pixels. */ public void setMinPartWidth(double pixels) { getState().minWidth = pixels; } /** * Get minimum width of part with value. * @return Minimum with of part in pixels. */ public double getMinPartWidth() { return getState().minWidth; } }
package com.level01.ΊρΉΠΑφ΅΅; import java.util.Arrays; public class MTest { public static void main(String[] args) { int n = 6; int [] arr1 = {46, 33, 33 ,22, 31, 50}; int [] arr2 = {27 ,56, 19, 14, 14, 10}; Soulution solution = new Soulution(); System.out.println(Arrays.toString(solution.solution(n, arr1, arr2))); } } class Soulution { public String[] solution(int n, int[] arr1, int[] arr2) { String [] answer = new String [n]; for(int i = 0; i < n; i++) { answer[i] = Integer.toBinaryString(arr1[i] | arr2[i]); answer[i] = String.format("%"+ n +"s", answer[i]); answer[i] = answer[i].replaceAll("1", "#"); answer[i] = answer[i].replaceAll("0", " "); } return answer; } }
package sukerPkg; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.util.List; import javax.swing.ButtonGroup; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; 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.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.Text; public class AndroSuker_TabItem_LogCatCls implements AndroSuker_Definition{ private static AndroSuker_Execute mExe; private static Composite LogCat_composite; private List<String> readList; private List<String> writeList; private Button dirBtn; private Button dirOpenBtn; private Button initBtn; private Button logcatRun_btn; private Text edit_filteroption; private Text edit_filterrange; private Text edit_filtername; private Text edit_directoryname; private Text edit_filename; @SuppressWarnings("unused") private ButtonGroup radioGroup; private Button radioBtn_Kernel; private Button radioBtn_Main; private Button radioBtn_System; private Button radioBtn_Radio; private Button radioBtn_Events; private String logType = ""; private Button checkbox_SilentOtherLogs; private Button checkbox_displayLog; private String strSilentOtherLogs; private String strStdoutValue; enum eTAB_LOGCAT { LOGCAT_RUN, LOGCAT_INIT, LOGCAT_DIR_PATH, LOGCAT_OPEN_FOLDER, LOGCAT_RADIO_KERNEL, LOGCAT_RADIO_MAIN, LOGCAT_RADIO_SYSTEM, LOGCAT_RADIO_RADIO, LOGCAT_RADIO_EVENT, LOGCAT_CHECK_OTHER, LOGCAT_CHECK_DISPLAY }; public AndroSuker_TabItem_LogCatCls(TabFolder tabFolder, AndroSuker_Execute mExecute) { createPage(tabFolder); mExe = mExecute; initPage(); } public static Composite getInstance() { return LogCat_composite; } public String getCurrentClsName() { return this.getClass().getName(); } private void createPage(TabFolder tabFolder) { //--------------------------------######### LogCat Main Frame ##########-------------------------------- LogCat_composite = new Composite(tabFolder, SWT.FILL); GridLayout gl = new GridLayout(); gl.numColumns = 5; gl.verticalSpacing = 10; gl.marginHeight = 25; LogCat_composite.setLayout(gl); //------------------------------######### label 1 ##########--------------------------------- Label label_FilterOption = new Label(LogCat_composite, SWT.BOTTOM); label_FilterOption.setText("Filter Option :"); GridData gridData_label0 = new GridData(); gridData_label0.horizontalAlignment = SWT.BEGINNING; gridData_label0.horizontalSpan = 2; gridData_label0.verticalIndent = 5; gridData_label0.widthHint = LABEL_FILTER_OPTION_WIDTH; gridData_label0.heightHint = LABEL_FILTER_OPTION_HEIGHT; label_FilterOption.setLayoutData(gridData_label0); //------------------------------######### label 2 ##########--------------------------------- Label label_FilterRange = new Label(LogCat_composite, SWT.BOTTOM); label_FilterRange.setText("Filter Range : V,D,I,W,E,F,S"); GridData gridData_label1 = new GridData(); gridData_label1.horizontalAlignment = SWT.BEGINNING; gridData_label1.horizontalSpan = 1; gridData_label1.verticalIndent = 5; gridData_label1.widthHint = LABEL_FILTER_RANGE_WIDTH; gridData_label1.heightHint = LABEL_FILTER_RANGE_HEIGHT; label_FilterRange.setLayoutData(gridData_label1); //------------------------------######### label 3 ##########--------------------------------- Label label_FilterName = new Label(LogCat_composite, SWT.BOTTOM); label_FilterName.setText("Filter name : ex)LGHome, CameraApp"); GridData gridData_label2 = new GridData(); gridData_label2.horizontalAlignment = SWT.BEGINNING; gridData_label2.horizontalSpan = 2; gridData_label2.verticalIndent = 5; gridData_label2.widthHint = LABEL_FILTER_NAME_WIDTH; gridData_label2.heightHint = LABEL_FILTER_NAME_HEIGHT; label_FilterName.setLayoutData(gridData_label2); //------------------------------######### editor 1 ##########--------------------------------- edit_filteroption = new Text(LogCat_composite, SWT.TOP | SWT.SINGLE | SWT.BORDER); GridData gridData_editor0 = new GridData(); gridData_editor0.horizontalAlignment = SWT.BEGINNING; gridData_editor0.verticalAlignment = SWT.TOP; gridData_editor0.verticalIndent = -5; gridData_editor0.horizontalSpan = 2; gridData_editor0.widthHint = EDIT_FILTER_OPTION_WIDTH; gridData_editor0.heightHint = EDIT_FILTER_OPTION_HEIGHT; edit_filteroption.setLayoutData(gridData_editor0); //------------------------------######### editor 2 ##########--------------------------------- edit_filterrange = new Text(LogCat_composite, SWT.TOP | SWT.SINGLE | SWT.BORDER); GridData gridData_editor1 = new GridData(); gridData_editor1.horizontalAlignment = SWT.BEGINNING; gridData_editor1.verticalAlignment = SWT.TOP; gridData_editor1.verticalIndent = -5; gridData_editor1.horizontalSpan = 1; gridData_editor1.widthHint = EDIT_FILTER_RANGE_WIDTH; gridData_editor1.heightHint = EDIT_FILTER_RANGE_HEIGHT; edit_filterrange.setLayoutData(gridData_editor1); //------------------------------######### editor 3 ##########--------------------------------- edit_filtername = new Text(LogCat_composite, SWT.TOP | SWT.SINGLE | SWT.BORDER); GridData gridData_editor2 = new GridData(); gridData_editor2.horizontalAlignment = SWT.BEGINNING; gridData_editor2.verticalAlignment = SWT.TOP; gridData_editor2.verticalIndent = -5; gridData_editor2.horizontalSpan = 2; gridData_editor2.widthHint = EDIT_FILTER_NAME_WIDTH; gridData_editor2.heightHint = EDIT_FILTER_NAME_HEIGHT; edit_filtername.setLayoutData(gridData_editor2); edit_filtername.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { if (edit_filtername.getText().trim().matches("Your Apk Name")) { edit_filtername.setText(""); } } public void focusLost(FocusEvent e) { } @SuppressWarnings("unused") void displayMessage(String prefix, FocusEvent e) { } }); //------------------------------######### Dir path ##########--------------------------------- Label label_DirPath = new Label(LogCat_composite, SWT.NONE); label_DirPath.setText("Directory path for save the log file : (none => save to the <Current Folder>)"); GridData gridData_label3 = new GridData(); gridData_label3.horizontalAlignment = SWT.BEGINNING; gridData_label3.horizontalSpan = 5; gridData_label3.widthHint = LABEL_DIR_PATH_WIDTH; gridData_label3.heightHint = LABEL_DIR_PATH_HEIGHT; label_DirPath.setLayoutData(gridData_label3); edit_directoryname = new Text(LogCat_composite, SWT.TOP | SWT.SINGLE | SWT.BORDER); GridData gridData_editor3 = new GridData(); gridData_editor3.horizontalAlignment = SWT.BEGINNING; gridData_editor3.verticalIndent = -10; gridData_editor3.horizontalSpan = 4; gridData_editor3.widthHint = EDIT_DIR_PATH_WIDTH; gridData_editor3.heightHint = EDIT_DIR_PATH_HEIGHT; edit_directoryname.setLayoutData(gridData_editor3); dirBtn = new Button(LogCat_composite, SWT.PUSH); dirBtn.setText("..."); GridData gridData_btn0 = new GridData(GridData.HORIZONTAL_ALIGN_FILL); gridData_btn0.horizontalSpan = 1; gridData_btn0.horizontalAlignment = SWT.END; gridData_btn0.widthHint = BUTTON_FOR_DIR_PATH_WIDTH; gridData_btn0.heightHint = BUTTON_FOR_DIR_PATH_HEIGHT; dirBtn.setLayoutData(gridData_btn0); dirBtn.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent event) { _actionPerformed(eTAB_LOGCAT.LOGCAT_DIR_PATH); } public void widgetDefaultSelected(SelectionEvent event) { } }); dirOpenBtn = new Button(LogCat_composite, SWT.PUSH); dirOpenBtn.setText("open folder"); GridData gridData_btn1 = new GridData(GridData.HORIZONTAL_ALIGN_FILL); gridData_btn1.horizontalSpan = 5; gridData_btn1.horizontalAlignment = SWT.END; gridData_btn1.widthHint = BUTTON_FOR_DIR_OPEN_WIDTH; gridData_btn1.heightHint = BUTTON_FOR_DIR_OPEN_HEIGHT; dirOpenBtn.setLayoutData(gridData_btn1); dirOpenBtn.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent event) { _actionPerformed(eTAB_LOGCAT.LOGCAT_OPEN_FOLDER); } public void widgetDefaultSelected(SelectionEvent event) { } }); edit_directoryname.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { if (edit_directoryname.getText().trim().matches("none")) edit_directoryname.setText(""); } public void focusLost(FocusEvent e) { } @SuppressWarnings("unused") void displayMessage(String prefix, FocusEvent e) { } }); //------------------------------######### Log File Label & Editor ##########--------------------------------- Label label_LogFile = new Label(LogCat_composite, SWT.NONE); label_LogFile.setText("Log File name : (none => <Current Date>.txt)"); GridData gridData_label4 = new GridData(); gridData_label4.horizontalAlignment = SWT.BEGINNING; gridData_label4.verticalIndent = 5; gridData_label4.horizontalSpan = 5; gridData_label4.widthHint = LABEL_LOG_FILE_WIDTH; gridData_label4.heightHint = LABEL_LOG_FILE_HEIGHT; label_LogFile.setLayoutData(gridData_label4); edit_filename = new Text(LogCat_composite, SWT.TOP | SWT.SINGLE | SWT.BORDER); GridData gridData_editor4 = new GridData(); gridData_editor4.horizontalAlignment = SWT.BEGINNING; gridData_editor4.verticalIndent = -5; gridData_editor4.horizontalSpan = 5; gridData_editor4.widthHint = EDIT_LOG_FILE_WIDTH; gridData_editor4.heightHint = EDIT_LOG_FILE_HEIGHT; edit_filename.setLayoutData(gridData_editor4); edit_filename.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { if (edit_filename.getText().trim().matches("none")) edit_filename.setText(""); } public void focusLost(FocusEvent e) { } @SuppressWarnings("unused") void displayMessage(String prefix, FocusEvent e) { } }); //------------------------------######### Radio Group ##########--------------------------------- GridData gridData_radioBtn = new GridData(); gridData_radioBtn.horizontalAlignment = SWT.BEGINNING; gridData_radioBtn.horizontalSpan = 1; Composite radioBtn = new Composite (LogCat_composite, SWT.NO_RADIO_GROUP); radioBtn.setLayout (new RowLayout (SWT.VERTICAL)); radioBtn_Kernel = new Button (radioBtn, SWT.RADIO); radioBtn_Kernel.setText("Kernel log <Default>"); radioBtn_Kernel.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { _actionPerformed(eTAB_LOGCAT.LOGCAT_RADIO_KERNEL); } public void widgetDefaultSelected(SelectionEvent arg0) { } }); radioBtn_Main = new Button (radioBtn, SWT.RADIO); radioBtn_Main.setText("Main log"); radioBtn_Main.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { _actionPerformed(eTAB_LOGCAT.LOGCAT_RADIO_MAIN); } public void widgetDefaultSelected(SelectionEvent arg0) { } }); radioBtn_System = new Button (radioBtn, SWT.RADIO); radioBtn_System.setText("System log"); radioBtn_System.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { _actionPerformed(eTAB_LOGCAT.LOGCAT_RADIO_SYSTEM); } public void widgetDefaultSelected(SelectionEvent arg0) { } }); radioBtn_Radio = new Button(radioBtn, SWT.RADIO); radioBtn_Radio.setText("Radio log"); radioBtn_Radio.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { _actionPerformed(eTAB_LOGCAT.LOGCAT_RADIO_RADIO); } public void widgetDefaultSelected(SelectionEvent arg0) { } }); radioBtn_Events = new Button(radioBtn, SWT.RADIO); radioBtn_Events.setText("Event log"); radioBtn_Events.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { _actionPerformed(eTAB_LOGCAT.LOGCAT_RADIO_EVENT); } public void widgetDefaultSelected(SelectionEvent arg0) { } }); radioBtn.setLayoutData(gridData_radioBtn); //------------------------------######### CheckBox Group ##########--------------------------------- GridData gridData_checkBtn = new GridData(); gridData_checkBtn.horizontalAlignment = SWT.END; gridData_checkBtn.horizontalSpan = 2; Composite checkBtn = new Composite (LogCat_composite, SWT.NO_RADIO_GROUP); checkBtn.setLayout (new RowLayout (SWT.VERTICAL)); checkbox_SilentOtherLogs = new Button(checkBtn, SWT.CHECK); checkbox_SilentOtherLogs.setText("Silent other logs"); checkbox_SilentOtherLogs.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent event) { _actionPerformed(eTAB_LOGCAT.LOGCAT_CHECK_OTHER); } public void widgetDefaultSelected(SelectionEvent event) { } }); checkbox_displayLog = new Button(checkBtn, SWT.CHECK); checkbox_displayLog.setText("Simultaneously with file saveing"); checkbox_displayLog.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent event) { _actionPerformed(eTAB_LOGCAT.LOGCAT_CHECK_DISPLAY); } public void widgetDefaultSelected(SelectionEvent event) { } }); checkBtn.setLayoutData(gridData_checkBtn); //------------------------------######### Function Button Group ##########--------------------------------- GridData gridData_FnBtn = new GridData(); gridData_FnBtn.horizontalAlignment = SWT.END; gridData_FnBtn.horizontalSpan = 1; Composite FnBtn = new Composite (LogCat_composite, SWT.NO_RADIO_GROUP); FnBtn.setLayout (new RowLayout (SWT.VERTICAL)); initBtn = new Button(FnBtn, SWT.PUSH); initBtn.setText("Initialize"); initBtn.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent event) { _actionPerformed(eTAB_LOGCAT.LOGCAT_INIT); } public void widgetDefaultSelected(SelectionEvent event) { } }); logcatRun_btn = new Button(FnBtn, SWT.PUSH); logcatRun_btn.setText("Run"); logcatRun_btn.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent event) { _actionPerformed(eTAB_LOGCAT.LOGCAT_RUN); } public void widgetDefaultSelected(SelectionEvent event) { } }); FnBtn.setLayoutData(gridData_FnBtn); } public void __onFinally() { writeList = AndroSuker_Main_Layout.getWriteFileList(); if (edit_directoryname.getText().length() <= 1) edit_directoryname.setText("none"); AndroSuker_INIFile.writeIniFile("LOGCAT_DIR", edit_directoryname.getText(), writeList); if (edit_filename.getText().length() <= 1) edit_filename.setText("none"); AndroSuker_INIFile.writeIniFile("LOGCAT_FILE", edit_filename.getText(), writeList); if (edit_filteroption.getText().length() <= 1) edit_filteroption.setText("-v time"); AndroSuker_INIFile.writeIniFile("LOGCAT_FILTEROPTION", edit_filteroption.getText(), writeList); if (edit_filterrange.getText().length() <= 1) edit_filterrange.setText("I"); AndroSuker_INIFile.writeIniFile("LOGCAT_FILTERRANGE", edit_filterrange.getText(), writeList); if (edit_filtername.getText().length() <= 1) edit_filtername.setText("Your Apk Name"); AndroSuker_INIFile.writeIniFile("LOGCAT_FILTERNAME", edit_filtername.getText(), writeList); AndroSuker_INIFile.writeIniFile("LOGCAT_SILENTOTHERLOGS", strSilentOtherLogs, writeList); AndroSuker_INIFile.writeIniFile("LOGCAT_SIMIL", strStdoutValue, writeList); AndroSuker_INIFile.writeIniFile("LOGCAT_TYPE", logType, writeList); } private void initPage() { String resultStr = "none"; readList = AndroSuker_Main_Layout.getReadFileList(); if (readList != null){ resultStr = AndroSuker_INIFile.readIniFile(readList, "LOGCAT_DIR"); edit_directoryname.setText(resultStr); resultStr = AndroSuker_INIFile.readIniFile(readList, "LOGCAT_FILE"); edit_filename.setText(resultStr); resultStr = AndroSuker_INIFile.readIniFile(readList, "LOGCAT_FILTEROPTION"); edit_filteroption.setText(resultStr); resultStr = AndroSuker_INIFile.readIniFile(readList, "LOGCAT_FILTERRANGE"); edit_filterrange.setText(resultStr); resultStr = AndroSuker_INIFile.readIniFile(readList, "LOGCAT_FILTERNAME"); edit_filtername.setText(resultStr); strSilentOtherLogs = AndroSuker_INIFile.readIniFile(readList, "LOGCAT_SILENTOTHERLOGS"); if (strSilentOtherLogs.equals("true")) { checkbox_SilentOtherLogs.setSelection(true); edit_filtername.setEditable(true); } else { checkbox_SilentOtherLogs.setSelection(false); edit_filtername.setEditable(false); } strStdoutValue = AndroSuker_INIFile.readIniFile(readList, "LOGCAT_SIMIL"); if (strStdoutValue.equals("true")) checkbox_displayLog.setSelection(true); else checkbox_displayLog.setSelection(false); resultStr = AndroSuker_INIFile.readIniFile(readList, "LOGCAT_TYPE"); logType = resultStr; if (resultStr.equals("kernel")) { radioBtn_Kernel.setSelection(true); } else if (resultStr.equals("main")) { radioBtn_Main.setSelection(true); } else if (resultStr.equals("system")) { radioBtn_System.setSelection(true); } else if (resultStr.equals("-b radio")) { radioBtn_Radio.setSelection(true); } else if (resultStr.equals("-b events")) { radioBtn_Events.setSelection(true); } } else { initTabValues(); } } public void _actionPerformed(eTAB_LOGCAT action) { switch(action) { case LOGCAT_RUN : int nOptionSplitCnt = 0; String regex = "~~"; String[] tempList; String filterName = "none"; String dirPath = "none"; String fileName = "none"; String filterRange = "V"; tempList = edit_filteroption.getText().trim().split("[ ]+"); nOptionSplitCnt = tempList.length; if (checkbox_displayLog.isEnabled()) { strStdoutValue = "true"; } else { strStdoutValue = "false"; } if (edit_filename.getText().trim().length() > 0){ fileName = edit_filename.getText().trim(); } if (edit_directoryname.getText().trim().length() > 0){ dirPath = edit_directoryname.getText(); dirPath = dirPath.replace('\\','/'); } if (edit_filtername.getText().trim().length() > 0) { if (edit_filtername.getText().trim().matches("Your Apk Name")) { filterName = "none"; } else { filterName = edit_filtername.getText().trim(); } } if (logType.equals("kernel")) { try { String text = "cmd.exe~~/K~~start~~perl~~script/kernelLogUtil.pl~~" // "perl&&logcatUtil.pl&&" + dirPath + "~~" + fileName + "~~" + filterName + "~~" + strStdoutValue; String[] cmdList = text.split(regex); mExe.runProcessSimple(cmdList); //mExecute.runProcess(cmdList); } catch (IOException e1) { e1.printStackTrace(); } catch (InterruptedException e1) { e1.printStackTrace(); } } else { /*if (edit_filtername.getText().trim().length() > 0) { if (edit_filtername.getText().trim().matches("Your Apk Name")) { filterName = "none"; } else { filterName = edit_filtername.getText().trim(); } }*/ if (checkbox_SilentOtherLogs.isEnabled()) { strSilentOtherLogs = "true"; } else { strSilentOtherLogs = "false"; } if (edit_filterrange.getText().trim().length() > 0){ filterRange = edit_filterrange.getText().trim(); } try { String text = "cmd.exe~~/K~~start~~perl~~script/logcatUtil.pl~~" // "perl&&logcatUtil.pl&&" + dirPath + "~~" + fileName + "~~" + strStdoutValue + "~~"// stdout? true or false + filterName + "~~"// filter @^ALL^@ ==> all, no filter name + filterRange + "~~" + strSilentOtherLogs + "~~"// 다른 로그 출력할지 말지 + nOptionSplitCnt + "~~" + logType + "~~" + edit_filteroption.getText().trim(); String[] cmdList = text.split(regex); mExe.runProcessSimple(cmdList); //mExecute.runProcess(cmdList); } catch (IOException e1) { e1.printStackTrace(); } catch (InterruptedException e1) { e1.printStackTrace(); } } break; case LOGCAT_INIT : initTabValues(); break; case LOGCAT_DIR_PATH : String temp = null; AndroSuker_DirDialog LogCatDlg; LogCatDlg = new AndroSuker_DirDialog(AndroSuker_MainCls.getShellInstance(), MODE_DIR, FILE_TYPE_NONE); temp = LogCatDlg.getDir(); if (temp != null) edit_directoryname.setText(temp); break; case LOGCAT_OPEN_FOLDER : String dirName = edit_directoryname.getText().trim(); if (dirName.equals("none") || dirName.length() < 1) { File file = null; if (logType.equals("kernel")) { file = new File("kernellog_out"); // assuming that path is not empty } else { file = new File("logcat_out"); // assuming that path is not empty } try { Desktop.getDesktop().open(file); } catch (IOException e1) { e1.printStackTrace(); } } else { File file = new File(dirName); // assuming that path is not empty if (AndroSuker_DirDialog.existFileOrPath(file)) { try { Desktop.getDesktop().open(file); } catch (IOException e1) { e1.printStackTrace(); } } else { MessageBox mb = new MessageBox(AndroSuker_MainCls.getShellInstance(), SWT.OK); mb.setText("Warning"); mb.setMessage("no exist directory path"); mb.open(); } } break; case LOGCAT_CHECK_OTHER : if (checkbox_SilentOtherLogs.getSelection()) { strSilentOtherLogs = "true"; edit_filtername.setEditable(true); } else { edit_filtername.setEditable(false); strSilentOtherLogs = "false"; } break; case LOGCAT_CHECK_DISPLAY : if (checkbox_displayLog.getSelection()) { strStdoutValue = "true"; } else { strStdoutValue = "false"; } break; case LOGCAT_RADIO_KERNEL : logType = "kernel"; radioBtn_Kernel.setSelection(true); radioBtn_Main.setSelection(false); radioBtn_System.setSelection(false); radioBtn_Radio.setSelection(false); radioBtn_Events.setSelection(false); break; case LOGCAT_RADIO_MAIN : logType = "main"; radioBtn_Kernel.setSelection(false); radioBtn_Main.setSelection(true); radioBtn_System.setSelection(false); radioBtn_Radio.setSelection(false); radioBtn_Events.setSelection(false); break; case LOGCAT_RADIO_SYSTEM : logType = "system"; radioBtn_Kernel.setSelection(false); radioBtn_Main.setSelection(false); radioBtn_System.setSelection(true); radioBtn_Radio.setSelection(false); radioBtn_Events.setSelection(false); break; case LOGCAT_RADIO_RADIO : logType = "-b radio"; radioBtn_Kernel.setSelection(false); radioBtn_Main.setSelection(false); radioBtn_System.setSelection(false); radioBtn_Radio.setSelection(true); radioBtn_Events.setSelection(false); break; case LOGCAT_RADIO_EVENT : logType = "-b events"; radioBtn_Kernel.setSelection(false); radioBtn_Main.setSelection(false); radioBtn_System.setSelection(false); radioBtn_Radio.setSelection(false); radioBtn_Events.setSelection(true); break; } } private void initTabValues() { edit_filteroption.setText("-v time"); edit_filterrange.setText("I"); edit_filtername.setText("Your Apk Name"); edit_directoryname.setText("none"); edit_filename.setText("none"); checkbox_SilentOtherLogs.setSelection(true); checkbox_displayLog.setSelection(true); strSilentOtherLogs = "true"; strStdoutValue = "true"; radioBtn_Kernel.setSelection(true); radioBtn_Main.setSelection(false); radioBtn_System.setSelection(false); radioBtn_Radio.setSelection(false); radioBtn_Events.setSelection(false); } }
package com.FCI.SWE.Models; import java.util.ArrayList; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.search.query.QueryParser.primitive_return; public class Page { private int pageId; private String name ; private ArrayList<UserEntity> users ; private ArrayList<Post> posts ; private String pageOwnerEmail ; private String category ; /** * Default Contractor */ public Page() { pageId = 0; name = ""; users = new ArrayList<UserEntity>(); posts = new ArrayList<Post>(); pageOwnerEmail = ""; setCategory(""); } /** * * @param pageId * @param name * @param users * @param posts * @param pageOwnerEmail */ public Page(int pageId ,String name , ArrayList<UserEntity> users , ArrayList<Post> posts , String pageOwnerEmail , String category) { pageId = this.pageId; name = this.name ; users = this.users; posts = this.posts; pageOwnerEmail = this.pageOwnerEmail; this.category = category; } /** * * @return */ public int getPageId() { return pageId; } /** * * @param pageId */ public void setPageId(int pageId) { this.pageId = pageId; } /** * * @return */ public String getName() { return name; } /** * * @param name */ public void setName(String name) { this.name = name; } /** * * @return */ public ArrayList<UserEntity> getUsers() { return users; } /** * * @param users */ public void setUsers(ArrayList<UserEntity> users) { this.users = users; } /** * * @return */ public ArrayList<Post> getPosts() { return posts; } /** * * @param posts */ public void setPosts(ArrayList<Post> posts) { this.posts = posts; } /** * * @return */ public String getPageOwnerEmail() { return pageOwnerEmail; } /** * * @param pageOwnerEmail */ public void setPageOwnerEmail(String pageOwnerEmail) { this.pageOwnerEmail = pageOwnerEmail; } /** * * @return total number of users those liked this page */ public int getNumberOfusers() { return users.size(); } /** * * @return */ public String getCategory() { return category; } /** * * @param category */ public void setCategory(String category) { this.category = category; } /** * * @return */ public boolean savePage(){ DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Query gaeQuery = new Query("pages"); PreparedQuery pq = datastore.prepare(gaeQuery); pageId = DatabaseOperations.getLastId("pages", "pageId") + 1 ; Entity page = new Entity("pages", pageId); page.setProperty("pageId", this.pageId); page.setProperty("name", this.name); page.setProperty("users", this.users); page.setProperty("posts", this.posts); page.setProperty("pageOwnerEmail", this.pageOwnerEmail); page.setProperty("category", this.category); datastore.put(page); return true; } /** * * @param _pageId * @return */ public static Page getPage(int _pageId) { DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Query gaeQuery = new Query("pages"); PreparedQuery pq = datastore.prepare(gaeQuery); //Iterate over all pages for (Entity entity : pq.asIterable()) { if (entity.getProperty("pageId").toString().equals(_pageId) ){ String _name = entity.getProperty("name").toString(); ArrayList<UserEntity> _users = ( ArrayList<UserEntity> )entity.getProperty("users"); ArrayList<Post> _posts = ( ArrayList<Post> )entity.getProperty("posts"); String _pageOwnerEmail = entity.getProperty("pageOwnerEmail").toString(); String _category = entity.getProperty("category").toString(); Page page = new Page( _pageId , _name , _users , _posts , _pageOwnerEmail , _category); return page; } } return null; } }
package aboli.musicbee; import android.media.MediaPlayer; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.CheckBox; import android.widget.TextView; import android.widget.Toast; /** * Activity that shows a user what settings the game can run with and allows them to select the ones * that they wish to use within their game. * * @author Jesse Scott */ public class GameSettings extends AppCompatActivity { MediaPlayer select; private Integer timer; private String difficulty; public static final String EXTRA_TIMER = "EXTRA_TIMER_SAVE"; public static final String EXTRA_LETTERS = "EXTRA_LETTERS_SAVE"; public static final String EXTRA_DIFFICULTY = "EXTRA_DIFFICULTY_SAVE"; private TextView t; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game_settings); //default values for the base game timer = 60; difficulty = "Easy"; select = MediaPlayer.create(this, R.raw.rondo); select.start(); } protected void easyPress(View view) { difficulty = "Easy"; t = (TextView) findViewById(R.id.displayDiff); t.setText(difficulty); } protected void hardPress(View view) { Context context = getApplicationContext(); CharSequence text = "Button currently doesn't work, sorry."; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.show(); /*difficulty = "Hard"; t = (TextView) findViewById(R.id.displayDiff); t.setText(difficulty);*/ } protected void press30(View view) { timer = 30; t = (TextView) findViewById(R.id.textTime); String temp = Integer.toString(timer) + " Seconds"; t.setText(temp); } protected void press45(View view) { timer = 45; t = (TextView) findViewById(R.id.textTime); String temp = Integer.toString(timer) + " Seconds"; t.setText(temp); } protected void press60(View view) { timer = 60; t = (TextView) findViewById(R.id.textTime); String temp = Integer.toString(timer) + " Seconds"; t.setText(temp); } protected void onSubmit(View view) { select.stop(); final CheckBox instructions = (CheckBox) findViewById(R.id.showInstructions); final CheckBox letters = (CheckBox) findViewById(R.id.showLetters); Boolean lettersBool; if (!letters.isChecked() && instructions.isChecked()) { Log.d("GameSettings", "!!! Entered is not checked letters, isChecked instructions"); Intent intent = new Intent(getApplicationContext(), Instruction_Page.class); intent.putExtra(EXTRA_TIMER, timer); intent.putExtra(EXTRA_DIFFICULTY, difficulty); //the user does not want letters on their keyboard //GIVE THE POOR PERSON SOME POINTS lettersBool = letters.isChecked(); intent.putExtra(EXTRA_LETTERS, lettersBool); startActivity(intent); } // if the user doesn't want letters and wants to skip instructions move to easy/hard else if (!letters.isChecked() && !instructions.isChecked()) { Log.d("GameSettings", "!!! Entered is not checked letters, is not checked instructions"); Intent intent; if (difficulty.equals("Hard")) { intent = new Intent(getApplicationContext(), hardGame.class); } else if (difficulty.equals("Easy")) { intent = new Intent(getApplicationContext(), easyGame.class); } else { Log.e("GameSettings", "!!! Intent was not initalized"); //something's wrong, restart the activity intent = new Intent(getApplicationContext(), GameSettings.class); Toast errToast = Toast.makeText(getApplicationContext(), "Error changing screens, try again", Toast.LENGTH_LONG); errToast.show(); } intent.putExtra(EXTRA_TIMER, timer); lettersBool = letters.isChecked(); intent.putExtra(EXTRA_LETTERS, lettersBool); startActivity(intent); } else if (letters.isChecked() && instructions.isChecked()) { Log.d("GameSettings", "!!! Entered is checked letters, is checked instructions"); Intent intent = new Intent(getApplicationContext(), Instruction_Page.class); intent.putExtra(EXTRA_TIMER, timer); intent.putExtra(EXTRA_DIFFICULTY, difficulty); lettersBool = letters.isChecked(); intent.putExtra(EXTRA_LETTERS, lettersBool); startActivity(intent); } else if (letters.isChecked() && !instructions.isChecked()) { Log.d("GameSettings", "!!! Entered is checked letters, is not checked instructions"); Intent intent; if (difficulty.equals("Hard")) { intent = new Intent(getApplicationContext(), hardGame.class); } else if (difficulty.equals("Easy")) { intent = new Intent(getApplicationContext(), easyGame.class); } else { Log.e("GameSettings", "!!! Intent was not initalized"); //something's wrong, restart the activity intent = new Intent(getApplicationContext(), GameSettings.class); Toast errToast = Toast.makeText(getApplicationContext(), "Error changing screens, try again", Toast.LENGTH_LONG); errToast.show(); } intent.putExtra(EXTRA_TIMER, timer); lettersBool = letters.isChecked(); intent.putExtra(EXTRA_LETTERS, lettersBool); startActivity(intent); } else { String display = "GameSettings"; Log.w(display, "!!! Entered catchall else statement in GameSettings.Java"); Intent intent = new Intent(getApplicationContext(), Instruction_Page.class); intent.putExtra(EXTRA_TIMER, timer); intent.putExtra(EXTRA_DIFFICULTY, difficulty); //the user does not want letters on their keyboard //GIVE THE POOR PERSON SOME POINTS lettersBool = letters.isChecked(); intent.putExtra(EXTRA_LETTERS, lettersBool); startActivity(intent); } } @Override public void onBackPressed() { Intent tempInt = new Intent(getApplicationContext(), MainActivity.class); startActivity(tempInt); } }
package com.lrs.admin.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.lrs.admin.controller.base.BaseController; import com.lrs.admin.entity.Const; import com.lrs.admin.entity.ReturnModel; import com.lrs.admin.entity.User; import com.lrs.admin.service.IAppUserService; import com.lrs.admin.util.Jurisdiction; @Controller @RequestMapping("/appuser") public class AppuserController extends BaseController{ private String qxurl = "appuser/list"; @Autowired private IAppUserService appUserService; @RequestMapping("/list") public Object list(Model model){ if(!Jurisdiction.buttonJurisdiction(qxurl,"query", this.getSession())){return ReturnModel.getNotAuthModel();} model.addAttribute("users", appUserService.getUserList(this.getParameterMap())); model.addAttribute("meid", ((User)this.getSession().getAttribute(Const.SESSION_USER)).getUserId()); return "page/appuser/list"; } }
package com.kdp.wanandroidclient.ui.tree; import com.kdp.wanandroidclient.bean.Tree; import com.kdp.wanandroidclient.net.callback.RxObserver; import com.kdp.wanandroidclient.ui.core.model.impl.TreeModel; import com.kdp.wanandroidclient.ui.core.presenter.BasePresenter; import java.util.List; /** * 知识体系 * author: 康栋普 * date: 2018/2/26 */ public class TreePresenter extends BasePresenter<TreeContract.ITreeView> implements TreeContract.ITreePresenter { private TreeModel mTreeModel; private TreeContract.ITreeView mSystemView; TreePresenter() { mTreeModel = new TreeModel(); } /** * 获取知识体系下的分类 */ @Override public void loadTree() { mSystemView = getView(); RxObserver<List<Tree>> mTreeRxObserver = new RxObserver<List<Tree>>(this) { @Override protected void onSuccess(List<Tree> data) { mSystemView.setData(data); if (mSystemView.getData().size() == 0) { mSystemView.showEmpty(); } else { mSystemView.showContent(); } } @Override protected void onFail(int errorCode, String errorMsg) { mSystemView.showFail(errorMsg); } @Override public void onError(Throwable e) { super.onError(e); mSystemView.showError(); } }; mTreeModel.getTree(mTreeRxObserver); addDisposable(mTreeRxObserver); } }
package com.holmes.tree; import org.junit.Test; public class BinaryTreeTest { @Test public void createBinary() { BinaryTree<String> tree = new BinaryTree<String>(); BinaryTreeNode root = new BinaryTreeNode<String>("A"); tree.setRoot(root); BinaryTreeNode left = tree.insertChild(root, "B", true); BinaryTreeNode right = tree.insertChild(root, "C", false); BinaryTreeNode p = left; BinaryTreeNode q = right; left = tree.insertChild(p, "D", true); tree.insertChild(p, "E", false); p = left; tree.insertChild(q, "F", false); tree.insertChild(p, "G", true); tree.preOrderTraverse(); System.out.println(); tree.inOrderTraverse(); System.out.println(); tree.postOrderTraverse(); System.out.println(); tree.levelOrderTraverse(); System.out.println(); System.out.println(); tree.removeChild(q, false); tree.removeChild(p, true); tree.preOrderTraverse(); System.out.println(); tree.inOrderTraverse(); System.out.println(); tree.postOrderTraverse(); System.out.println(); tree.levelOrderTraverse(); System.out.println(); } }
package uns.ac.rs.hostplatserver.constant; import lombok.experimental.UtilityClass; import java.time.ZoneId; @UtilityClass public class DateTimeConstant { public final ZoneId SYSTEM_TIMEZONE = ZoneId.of("Europe/Belgrade"); }
package edu.cecar.controlador; import edu.cecar.modelo.Dato; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import javax.swing.JOptionPane; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFChart; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openxmlformats.schemas.drawingml.x2006.chart.CTAxDataSource; import org.openxmlformats.schemas.drawingml.x2006.chart.CTBar3DChart; import org.openxmlformats.schemas.drawingml.x2006.chart.CTBarSer; import org.openxmlformats.schemas.drawingml.x2006.chart.CTBoolean; import org.openxmlformats.schemas.drawingml.x2006.chart.CTCatAx; import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart; import org.openxmlformats.schemas.drawingml.x2006.chart.CTLegend; import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumDataSource; import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumRef; import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea; import org.openxmlformats.schemas.drawingml.x2006.chart.CTScaling; import org.openxmlformats.schemas.drawingml.x2006.chart.CTSerTx; import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrRef; import org.openxmlformats.schemas.drawingml.x2006.chart.CTValAx; import org.openxmlformats.schemas.drawingml.x2006.chart.STAxPos; import org.openxmlformats.schemas.drawingml.x2006.chart.STBarDir; import org.openxmlformats.schemas.drawingml.x2006.chart.STLegendPos; import org.openxmlformats.schemas.drawingml.x2006.chart.STOrientation; import org.openxmlformats.schemas.drawingml.x2006.chart.STTickLblPos; /** *Clase que controla la creacion del documento de EXCEL * */ public class ControladorApachePoi { public void crearGraficaExcel(List<Dato> lista1,List<Dato> lista2,List<Dato> lista3,List<Dato> lista4) throws FileNotFoundException, IOException{ Workbook wb = new XSSFWorkbook(); for (int i = 0; i < lista1.size(); i++) { Sheet sheet = wb.createSheet(lista2.get(i).getNombrePais()); Row row; Cell cell; row = sheet.createRow(0); row.createCell(0); row.createCell(1).setCellValue("Total confirmed cases "); row.createCell(2).setCellValue("Total confirmed* new cases"); row.createCell(3).setCellValue("Total deaths"); row.createCell(4).setCellValue("Total new deaths"); //Fila1 row = sheet.createRow(1); cell = row.createCell(0); cell.setCellValue(lista1.get(i).getFecha()); cell = row.createCell(1); cell.setCellValue(lista1.get(i).getCasosConfirmados()); cell = row.createCell(2); cell.setCellValue(lista1.get(i).getCasosConfirmadosNuevos()); cell = row.createCell(3); cell.setCellValue(lista1.get(i).getTotalMuertes()); cell = row.createCell(4); cell.setCellValue(lista1.get(i).getTotalNuevasMuertes()); //Fila2 row = sheet.createRow(2); cell = row.createCell(0); cell.setCellValue(lista2.get(i).getFecha()); cell = row.createCell(1); cell.setCellValue(lista2.get(i).getCasosConfirmados()); cell = row.createCell(2); cell.setCellValue(lista2.get(i).getCasosConfirmadosNuevos()); cell = row.createCell(3); cell.setCellValue(lista2.get(i).getTotalMuertes()); cell = row.createCell(4); cell.setCellValue(lista2.get(i).getTotalNuevasMuertes()); //Fila3 row = sheet.createRow(3); cell = row.createCell(0); cell.setCellValue(lista3.get(i).getFecha()); cell = row.createCell(1); cell.setCellValue(lista3.get(i).getCasosConfirmados()); cell = row.createCell(2); cell.setCellValue(lista3.get(i).getCasosConfirmadosNuevos()); cell = row.createCell(3); cell.setCellValue(lista3.get(i).getTotalMuertes()); cell = row.createCell(4); cell.setCellValue(lista3.get(i).getTotalNuevasMuertes()); //Fila4 row = sheet.createRow(4); cell = row.createCell(0); cell.setCellValue(lista4.get(i).getFecha()); cell = row.createCell(1); cell.setCellValue(lista4.get(i).getCasosConfirmados()); cell = row.createCell(2); cell.setCellValue(lista4.get(i).getCasosConfirmadosNuevos()); cell = row.createCell(3); cell.setCellValue(lista4.get(i).getTotalMuertes()); cell = row.createCell(4); cell.setCellValue(lista4.get(i).getTotalNuevasMuertes()); XSSFDrawing drawing = (XSSFDrawing) sheet.createDrawingPatriarch(); ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 8, 20); XSSFChart chart = drawing.createChart(anchor); CTChart ctChart = ((XSSFChart) chart).getCTChart(); CTPlotArea ctPlotArea = ctChart.getPlotArea(); CTBar3DChart ctBarChart = ctPlotArea.addNewBar3DChart(); CTBoolean ctBoolean = ctBarChart.addNewVaryColors(); ctBoolean.setVal(true); ctBarChart.addNewBarDir().setVal(STBarDir.COL); for (int r = 2; r < 6; r++) { CTBarSer ctBarSer = ctBarChart.addNewSer(); CTSerTx ctSerTx = ctBarSer.addNewTx(); CTStrRef ctStrRef = ctSerTx.addNewStrRef(); ctStrRef.setF(lista2.get(i).getNombrePais()+"!$A$" + r); ctBarSer.addNewIdx().setVal(r - 2); CTAxDataSource cttAxDataSource = ctBarSer.addNewCat(); ctStrRef = cttAxDataSource.addNewStrRef(); ctStrRef.setF(lista2.get(i).getNombrePais()+"!$B$1:$E$1"); CTNumDataSource ctNumDataSource = ctBarSer.addNewVal(); CTNumRef ctNumRef = ctNumDataSource.addNewNumRef(); ctNumRef.setF(lista2.get(i).getNombrePais()+"!$B$" + r + ":$E$" + r); //at least the border lines in Libreoffice Calc ;-) ctBarSer.addNewSpPr().addNewLn().addNewSolidFill().addNewSrgbClr().setVal(new byte[]{0, 0, 0}); } //telling the BarChart that it has axes and giving them Ids ctBarChart.addNewAxId().setVal(123456); ctBarChart.addNewAxId().setVal(123457); //cat axis CTCatAx ctCatAx = ctPlotArea.addNewCatAx(); ctCatAx.addNewAxId().setVal(123456); //id of the cat axis CTScaling ctScaling = ctCatAx.addNewScaling(); ctScaling.addNewOrientation().setVal(STOrientation.MIN_MAX); ctCatAx.addNewDelete().setVal(false); ctCatAx.addNewAxPos().setVal(STAxPos.B); ctCatAx.addNewCrossAx().setVal(123457); //id of the val axis ctCatAx.addNewTickLblPos().setVal(STTickLblPos.NEXT_TO); //val axis CTValAx ctValAx = ctPlotArea.addNewValAx(); ctValAx.addNewAxId().setVal(123457); //id of the val axis ctScaling = ctValAx.addNewScaling(); ctScaling.addNewOrientation().setVal(STOrientation.MIN_MAX); ctValAx.addNewDelete().setVal(false); ctValAx.addNewAxPos().setVal(STAxPos.L); ctValAx.addNewCrossAx().setVal(123456); //id of the cat axis ctValAx.addNewTickLblPos().setVal(STTickLblPos.NEXT_TO); //legend CTLegend ctLegend = ctChart.addNewLegend(); ctLegend.addNewLegendPos().setVal(STLegendPos.B); ctLegend.addNewOverlay().setVal(false); //System.out.println(ctChart); } FileOutputStream fileOut = new FileOutputStream("archivos/EstadisticasCovid.xlsx"); wb.write(fileOut); fileOut.close(); JOptionPane.showMessageDialog(null, "Documento Generado con exito"); } }
package com.tdd.sis.model; import java.io.IOException; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author teyyub */ public class StudentDirectoryTest { private StudentDirectory dir; public StudentDirectoryTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { dir = new StudentDirectory(); } @After public void tearDown() { } /** * Test of add method, of class StudentDirectory. */ @Test public void testAdd() { } @Test public void testStoreAndRetrieve() throws IOException { final int numberOfStudents = 10; for (int i = 0; i < numberOfStudents; i++) { addStudent(dir, i); } for (int i = 0; i < numberOfStudents; i++) { verifyStudentLookup(dir, i); } } void addStudent(StudentDirectory directory, int i) throws IOException { String id = "" + i; Student student = new Student(id); student.setId(id); // student.addCredits(i); directory.add(student); } void verifyStudentLookup(StudentDirectory directory, int i) throws IOException { String id = "" + i; Student student = dir.findById(id); assertEquals(id, student.getLastName()); assertEquals(id, student.getId()); // assertEquals(i, student.getCredits()); } }
package chapter4; /** * @author Fulai Zhang * @since 2018/2/1. */ public class TestVertxCluster { }
package com.beiyelin.account.security; import java.lang.annotation.*; /** * @Description: AccessRight的容器类,使用java8的重复注解 * @Author: newmann * @Date: Created in 9:42 2018-01-20 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface AccessPermissions { AccessPermission[] value(); }
//package support.yz.data.mvc.service.inter; // //import java.io.File; //import java.util.List; // //import com.yaoqianshu.data.model.domain.busi.AccInfoModel; //import com.yaoqianshu.developer.model.TextDataPreview; // //public interface ITextDataSourceService { // // /** // * 文件上传到项目本地 // * @param file // * @return // * @throws Exception // */ // public TextDataPreview upload(File file, String suffixName) throws Exception; // // /** // * 删除本地指定文件 // * @param path // * @param operation // * @return // * @throws Exception // */ // public String delete(String path, int operation, String accId) throws Exception; // // /** // * 将文本数据上传到数据库中 // * @param fileIds // * @param columns // * @param row // */ // public void save(List<String[]> columns, String[] paths, AccInfoModel.DetailAccount accInfo, int[] row, String fileType, List<String[]> comments) throws Exception; // //}
/* * 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 br.cwi.crescer.repositorio; import br.cwi.crescer.entity.Pessoa; import java.util.List; /** * * @author Érico de Souza Loewe */ public class PessoaRepositorio extends RepositorioBase<Pessoa> implements Repositorio<Pessoa> { public void adicionar(Pessoa pessoa) { super.adicionar(pessoa); } public void atualizar(Pessoa pessoa) { super.atualizar(pessoa); } public void deletar(Long pessoa) { super.deletar(pessoa); } public List<Pessoa> listar() { return super.listar("Pessoa"); } }
package com.itranswarp.jxrest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Route by regular express. * * @author Michael Liao */ class Route { static final Log log = LogFactory.getLog(Route.class); static final Pattern RE_ROUTE_VAR = Pattern.compile("\\:([A-Za-z\\_][A-Za-z0-9]*)"); final String[] parameters; final Pattern regexPath; Route(String path) { PatternAndNames pan = compile(path); this.regexPath = pan.pattern; this.parameters = pan.names; } static PatternAndNames compile(String path) { StringBuilder sb = new StringBuilder(path.length() + 32); sb.append("^"); int start = 0; List<String> names = new ArrayList<String>(); for (;;) { Matcher m = RE_ROUTE_VAR.matcher(path); boolean found = m.find(start); if (found) { if (start == m.start()) { log.warn("URL pattern has possible error: \"" + path + "\", at " + start); } else { appendStatic(sb, path.substring(start, m.start())); } String name = m.group(1); start = m.end(); appendVar(sb, name); names.add(name); } else { appendStatic(sb, path.substring(start)); break; } } if (names.isEmpty()) { throw new IllegalArgumentException("Cannot compile path to a valid regular expression: " + path); } sb.append("$"); return new PatternAndNames(Pattern.compile(sb.toString()), names.toArray(new String[names.size()])); } static void appendVar(StringBuilder sb, String name) { sb.append("(?<").append(name).append(">[^\\/]+)"); } static void appendStatic(StringBuilder sb, String s) { for (int i=0; i<s.length(); i++) { char c = s.charAt(i); if (c >= 'A' && c <= 'Z') { sb.append(c); } else if (c >= 'a' && c <= 'z') { sb.append(c); } else if (c >= '0' && c <= '9') { sb.append(c); } else { sb.append('\\').append(c); } } } boolean hasParameter(String param) { for (String s : this.parameters) { if (s.equals(param)) { return true; } } return false; } Map<String, String> matches(String path) { Matcher m = regexPath.matcher(path); if (m.matches()) { Map<String, String> map = new HashMap<String, String>(); for (String param : this.parameters) { map.put(param, m.group(param)); } return map; } return null; } } class PatternAndNames { final Pattern pattern; final String[] names; PatternAndNames(Pattern pattern, String[] names) { this.pattern = pattern; this.names = names; } }
package io.fab.connector.configurations; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.fab.connector.ifood.IFoodApiAccessTokenStorage; /** * Configuração do armazenamento, em memória, do token de acesso à API do iFood. * * @author fabio.tasco * @see IFoodApiAccessTokenStorage */ @Configuration public class IFoodApiAccessTokenStorageConfiguration { @Bean public IFoodApiAccessTokenStorage iFoodApiAccessTokenStorage() { return new IFoodApiAccessTokenStorage(); } }
package com.example.ComicToon.Models.RequestResponseModels; import java.util.ArrayList; import com.example.ComicToon.Models.ComicSeriesModel; public class ViewSubscriptionsResult { private ArrayList<ComicSeriesModel> series; /** * @return the series */ public ArrayList<ComicSeriesModel> getSeries() { return series; } /** * @param series the series to set */ public void setSeries(ArrayList<ComicSeriesModel> series) { this.series = series; } }
package com.vaescode.di.autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class Square implements Figure { /*También es posible declarar una propiedad con un valor por default en caso de que el valor no * sea declarado en el archivo de configuración*/ @Value("${square.side:5}") private double side; @Override public double calculadoraArea() { return side * side; } }
/****************************************************** Cours: LOG121 Projet: Framework.TP3 Nom du fichier: Joueur.java Date créé: 2016-03-07 ******************************************************* Historique des modifications ******************************************************* *@author Vincent Leclerc(LECV07069406) *@author Gabriel Déry(DERG30049401) 2016-03-07 Version initiale *******************************************************/ package Test; import static org.junit.Assert.*; import org.junit.Test; import Framework.Des.De; import Framework.Des.Joueur; /** * Classe qui permet de tester les méthode de la classe joueur * @author pc * */ public class JoueurTest { private Joueur j1 = new Joueur(0,0); private Joueur j2 = new Joueur(0,0); @Test public void ScoreSuperieurTest() { j1.setScoreJoueur(2); j2.setScoreJoueur(3); assertTrue(j1.compareTo(j2)==1); } @Test public void ScoreInferieurTest() { j1.setScoreJoueur(3); j2.setScoreJoueur(2); assertTrue(j1.compareTo(j2)==-1); } @Test public void memeScoreTest() { j1.setScoreJoueur(3); j2.setScoreJoueur(3); assertTrue(j1.compareTo(j2)==0); } @Test public void getScoreTest() { j1.setScoreJoueur(3); int score = j1.getScoreJoueur(); assertTrue(score == 3); } @Test public void setScoreTest() { j1.setScoreJoueur(3); assertTrue(j1.getScoreJoueur() == 3); } @Test public void getNumeroJoueurTest() { j1 = new Joueur(1,1); assertTrue(j1.getNumeroJoueur() == 1); } }
package com.cimcssc.chaojilanling.entity.enterprise; /** * Created by cimcitech on 2017/4/25. */ /** * 企业性质 */ public class EnterpriseNatureVo { private String daAdd; private String daUpdate; private int dictionaryId; private String dictionaryText; private String dictionaryType; private String dictionaryValue; private String isDelete; public String getDaAdd() { return daAdd; } public void setDaAdd(String daAdd) { this.daAdd = daAdd; } public String getDaUpdate() { return daUpdate; } public void setDaUpdate(String daUpdate) { this.daUpdate = daUpdate; } public int getDictionaryId() { return dictionaryId; } public void setDictionaryId(int dictionaryId) { this.dictionaryId = dictionaryId; } public String getDictionaryText() { return dictionaryText; } public void setDictionaryText(String dictionaryText) { this.dictionaryText = dictionaryText; } public String getDictionaryType() { return dictionaryType; } public void setDictionaryType(String dictionaryType) { this.dictionaryType = dictionaryType; } public String getDictionaryValue() { return dictionaryValue; } public void setDictionaryValue(String dictionaryValue) { this.dictionaryValue = dictionaryValue; } public String getIsDelete() { return isDelete; } public void setIsDelete(String isDelete) { this.isDelete = isDelete; } }
package com.zhouyi.business.core.model; import java.io.Serializable; import java.util.Date; /** * 文章内容 * * */ public class ArticleInfo implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private Long id; private String title; private Date updateTime; private Date createTime; private Long createBy; private Long updateBy; private String summary; private String content; private Integer isPutaway; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateBy() { return createBy; } public void setCreateBy(Long createBy) { this.createBy = createBy; } public Long getUpdateBy() { return updateBy; } public void setUpdateBy(Long updateBy) { this.updateBy = updateBy; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Integer getIsPutaway() { return isPutaway; } public void setIsPutaway(Integer isPutaway) { this.isPutaway = isPutaway; } }
package com.tencent.mm.plugin.h.a.b; import com.tencent.mm.plugin.exdevice.j.b; import com.tencent.mm.sdk.platformtools.x; class f$2 implements Runnable { final /* synthetic */ f hgG; f$2(f fVar) { this.hgG = fVar; } public final void run() { x.e("MicroMsg.exdevice.BluetoothLESimpleSession", "Write data timeout, mac=%s, name=%s", new Object[]{b.cY(f.g(this.hgG)), f.h(this.hgG).getName()}); if (f.i(this.hgG) != null) { f.i(this.hgG).j(f.g(this.hgG), false); } f.j(this.hgG); } }
package fr.eseo.poo.projet.artiste.modele; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class CoordonneesTestDistanceVers { private static final double EPSILON = 0.01; private Coordonnees coordonnees, autreCoordonnees; private double distance; public CoordonneesTestDistanceVers(Coordonnees coordonnees, Coordonnees autreCoordonnees, double distance) { this.coordonnees = coordonnees; this.autreCoordonnees = autreCoordonnees; this.distance = distance; } @Parameters(name = "dt[{index}] : {0}, {1}, {2}") public static Collection<Object[]> dt() { Object[][] data = new Object[][] { // Test d'une distance en haut à droite {new Coordonnees(), new Coordonnees(0.8, 2.4), 2.52}, // Test d'une distance en haut à gauche {new Coordonnees(), new Coordonnees(-1.7, 1.2), 2.08}, // Test d'une distance en bas à droite {new Coordonnees(), new Coordonnees(2.9, -1.2), 3.14}, // Test d'une distance en bas à gauche {new Coordonnees(), new Coordonnees(-3.0, -3.2), 4.39} }; return Arrays.asList(data); } // Converture des instructions pour la méthode distanceVers() : 100% (17/17) @Test public void testDistanceVers() { assertEquals("Distance incorrect : ", this.distance, this.coordonnees.distanceVers(this.autreCoordonnees), EPSILON); } }