code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
package io.abnd.rvep.user.model; import java.io.Serializable; import javax.persistence.*; import io.abnd.rvep.event.model.RvepEventInvite; import io.abnd.rvep.event.model.RvepEventTodoList; import io.abnd.rvep.event.model.RvepUserEventRollingVote; import io.abnd.rvep.event.model.TodoListItemAssignment; import io.abnd.rvep.security.model.RvepUserAuthProvider; import io.abnd.rvep.security.model.RvepUserEventRole; import io.abnd.rvep.security.model.RvepUserRole; import java.util.Date; import java.util.List; /** * The persistent class for the rvep_user database table. * */ @Entity @Table(name="rvep_user") @NamedQuery(name="RvepUser.findAll", query="SELECT r FROM RvepUser r") public class RvepUser implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @Temporal(TemporalType.TIMESTAMP) @Column(name="created_on") private Date createdOn; private byte enabled; //bi-directional many-to-one association to RvepEventInvite @OneToMany(mappedBy="rvepUser") private List<RvepEventInvite> rvepEventInvites; //bi-directional many-to-one association to RvepEventTodoList @OneToMany(mappedBy="rvepUser") private List<RvepEventTodoList> rvepEventTodoLists; //bi-directional many-to-one association to RvepUserAuthProvider @OneToMany(mappedBy="rvepUser") private List<RvepUserAuthProvider> rvepUserAuthProviders; //bi-directional many-to-one association to RvepUserContact @OneToMany(mappedBy="rvepUser") private List<RvepUserContact> rvepUserContacts; //bi-directional many-to-one association to RvepUserContactInvite @OneToMany(mappedBy="rvepUser") private List<RvepUserContactInvite> rvepUserContactInvites; //bi-directional many-to-one association to RvepUserEventRole @OneToMany(mappedBy="rvepUser") private List<RvepUserEventRole> rvepUserEventRoles; //bi-directional many-to-one association to RvepUserEventRollingVote @OneToMany(mappedBy="rvepUser") private List<RvepUserEventRollingVote> rvepUserEventRollingVotes; //bi-directional many-to-one association to RvepUserProfile @OneToMany(mappedBy="rvepUser") private List<RvepUserProfile> rvepUserProfiles; //bi-directional many-to-one association to RvepUserRole @OneToMany(mappedBy="rvepUser") private List<RvepUserRole> rvepUserRoles; //bi-directional many-to-one association to TodoListItemAssignment @OneToMany(mappedBy="rvepUser") private List<TodoListItemAssignment> todoListItemAssignments; public RvepUser() { } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public Date getCreatedOn() { return this.createdOn; } public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } public byte getEnabled() { return this.enabled; } public void setEnabled(byte enabled) { this.enabled = enabled; } public List<RvepEventInvite> getRvepEventInvites() { return this.rvepEventInvites; } public void setRvepEventInvites(List<RvepEventInvite> rvepEventInvites) { this.rvepEventInvites = rvepEventInvites; } public RvepEventInvite addRvepEventInvite(RvepEventInvite rvepEventInvite) { getRvepEventInvites().add(rvepEventInvite); rvepEventInvite.setRvepUser(this); return rvepEventInvite; } public RvepEventInvite removeRvepEventInvite(RvepEventInvite rvepEventInvite) { getRvepEventInvites().remove(rvepEventInvite); rvepEventInvite.setRvepUser(null); return rvepEventInvite; } public List<RvepEventTodoList> getRvepEventTodoLists() { return this.rvepEventTodoLists; } public void setRvepEventTodoLists(List<RvepEventTodoList> rvepEventTodoLists) { this.rvepEventTodoLists = rvepEventTodoLists; } public RvepEventTodoList addRvepEventTodoList(RvepEventTodoList rvepEventTodoList) { getRvepEventTodoLists().add(rvepEventTodoList); rvepEventTodoList.setRvepUser(this); return rvepEventTodoList; } public RvepEventTodoList removeRvepEventTodoList(RvepEventTodoList rvepEventTodoList) { getRvepEventTodoLists().remove(rvepEventTodoList); rvepEventTodoList.setRvepUser(null); return rvepEventTodoList; } public List<RvepUserAuthProvider> getRvepUserAuthProviders() { return this.rvepUserAuthProviders; } public void setRvepUserAuthProviders(List<RvepUserAuthProvider> rvepUserAuthProviders) { this.rvepUserAuthProviders = rvepUserAuthProviders; } public RvepUserAuthProvider addRvepUserAuthProvider(RvepUserAuthProvider rvepUserAuthProvider) { getRvepUserAuthProviders().add(rvepUserAuthProvider); rvepUserAuthProvider.setRvepUser(this); return rvepUserAuthProvider; } public RvepUserAuthProvider removeRvepUserAuthProvider(RvepUserAuthProvider rvepUserAuthProvider) { getRvepUserAuthProviders().remove(rvepUserAuthProvider); rvepUserAuthProvider.setRvepUser(null); return rvepUserAuthProvider; } public List<RvepUserContact> getRvepUserContacts() { return this.rvepUserContacts; } public void setRvepUserContacts(List<RvepUserContact> rvepUserContacts) { this.rvepUserContacts = rvepUserContacts; } public RvepUserContact addRvepUserContact(RvepUserContact rvepUserContact) { getRvepUserContacts().add(rvepUserContact); rvepUserContact.setRvepUser(this); return rvepUserContact; } public RvepUserContact removeRvepUserContact(RvepUserContact rvepUserContact) { getRvepUserContacts().remove(rvepUserContact); rvepUserContact.setRvepUser(null); return rvepUserContact; } public List<RvepUserContactInvite> getRvepUserContactInvites() { return this.rvepUserContactInvites; } public void setRvepUserContactInvites(List<RvepUserContactInvite> rvepUserContactInvites) { this.rvepUserContactInvites = rvepUserContactInvites; } public RvepUserContactInvite addRvepUserContactInvite(RvepUserContactInvite rvepUserContactInvite) { getRvepUserContactInvites().add(rvepUserContactInvite); rvepUserContactInvite.setRvepUser(this); return rvepUserContactInvite; } public RvepUserContactInvite removeRvepUserContactInvite(RvepUserContactInvite rvepUserContactInvite) { getRvepUserContactInvites().remove(rvepUserContactInvite); rvepUserContactInvite.setRvepUser(null); return rvepUserContactInvite; } public List<RvepUserEventRole> getRvepUserEventRoles() { return this.rvepUserEventRoles; } public void setRvepUserEventRoles(List<RvepUserEventRole> rvepUserEventRoles) { this.rvepUserEventRoles = rvepUserEventRoles; } public RvepUserEventRole addRvepUserEventRole(RvepUserEventRole rvepUserEventRole) { getRvepUserEventRoles().add(rvepUserEventRole); rvepUserEventRole.setRvepUser(this); return rvepUserEventRole; } public RvepUserEventRole removeRvepUserEventRole(RvepUserEventRole rvepUserEventRole) { getRvepUserEventRoles().remove(rvepUserEventRole); rvepUserEventRole.setRvepUser(null); return rvepUserEventRole; } public List<RvepUserEventRollingVote> getRvepUserEventRollingVotes() { return this.rvepUserEventRollingVotes; } public void setRvepUserEventRollingVotes(List<RvepUserEventRollingVote> rvepUserEventRollingVotes) { this.rvepUserEventRollingVotes = rvepUserEventRollingVotes; } public RvepUserEventRollingVote addRvepUserEventRollingVote(RvepUserEventRollingVote rvepUserEventRollingVote) { getRvepUserEventRollingVotes().add(rvepUserEventRollingVote); rvepUserEventRollingVote.setRvepUser(this); return rvepUserEventRollingVote; } public RvepUserEventRollingVote removeRvepUserEventRollingVote(RvepUserEventRollingVote rvepUserEventRollingVote) { getRvepUserEventRollingVotes().remove(rvepUserEventRollingVote); rvepUserEventRollingVote.setRvepUser(null); return rvepUserEventRollingVote; } public List<RvepUserProfile> getRvepUserProfiles() { return this.rvepUserProfiles; } public void setRvepUserProfiles(List<RvepUserProfile> rvepUserProfiles) { this.rvepUserProfiles = rvepUserProfiles; } public RvepUserProfile addRvepUserProfile(RvepUserProfile rvepUserProfile) { getRvepUserProfiles().add(rvepUserProfile); rvepUserProfile.setRvepUser(this); return rvepUserProfile; } public RvepUserProfile removeRvepUserProfile(RvepUserProfile rvepUserProfile) { getRvepUserProfiles().remove(rvepUserProfile); rvepUserProfile.setRvepUser(null); return rvepUserProfile; } public List<RvepUserRole> getRvepUserRoles() { return this.rvepUserRoles; } public void setRvepUserRoles(List<RvepUserRole> rvepUserRoles) { this.rvepUserRoles = rvepUserRoles; } public RvepUserRole addRvepUserRole(RvepUserRole rvepUserRole) { getRvepUserRoles().add(rvepUserRole); rvepUserRole.setRvepUser(this); return rvepUserRole; } public RvepUserRole removeRvepUserRole(RvepUserRole rvepUserRole) { getRvepUserRoles().remove(rvepUserRole); rvepUserRole.setRvepUser(null); return rvepUserRole; } public List<TodoListItemAssignment> getTodoListItemAssignments() { return this.todoListItemAssignments; } public void setTodoListItemAssignments(List<TodoListItemAssignment> todoListItemAssignments) { this.todoListItemAssignments = todoListItemAssignments; } public TodoListItemAssignment addTodoListItemAssignment(TodoListItemAssignment todoListItemAssignment) { getTodoListItemAssignments().add(todoListItemAssignment); todoListItemAssignment.setRvepUser(this); return todoListItemAssignment; } public TodoListItemAssignment removeTodoListItemAssignment(TodoListItemAssignment todoListItemAssignment) { getTodoListItemAssignments().remove(todoListItemAssignment); todoListItemAssignment.setRvepUser(null); return todoListItemAssignment; } }
rvep/dev_backend
src/main/java/io/abnd/rvep/user/model/RvepUser.java
Java
mit
9,578
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.Deque; public class lab01_MatchingBrackets { public static void main(String[] args) throws IOException { BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in)); String input = bfr.readLine(); bfr.close(); Deque<Integer> indexes = new ArrayDeque<>(); for (int i = 0; i < input.length(); i++) { if (input.charAt(i) == '(') { indexes.push(i); } else if (input.charAt(i) == ')') { System.out.println(input.substring(indexes.pop(), i + 1)); } } } }
akkirilov/SoftUniProject
05_JAVA_Advanced/09_ObjectsClassesCollections_lab/src/lab01_MatchingBrackets.java
Java
mit
653
package edu.fmi.ai.reversi.move; import edu.fmi.ai.reversi.Game; import edu.fmi.ai.reversi.model.Board; public class MainDiagonalMoveChecker extends BaseDiagonalMoveChecker { public MainDiagonalMoveChecker(Board board) { super(board); } /** * {@inheritDoc} */ @Override protected boolean isDiagonalEnd(final int cellIndex) { return (cellIndex % 8 == 0 || cellIndex / 8 == 0 || cellIndex % 8 == 7 || cellIndex / 8 == 7) && cellIndex != 56 && cellIndex != 7; } /** * {@inheritDoc} */ @Override protected boolean canMoveBottom(final int cellIndex) { return !(cellIndex / 8 == 7 || cellIndex % 8 == 7); } /** * {@inheritDoc} */ @Override protected boolean canMoveTop(final int cellIndex) { return !(cellIndex / 8 == 0 || cellIndex % 8 == 0); } /** * {@inheritDoc} */ @Override protected int incrementIndex(final int cellIndex, final boolean isNegativeDirection) { return isNegativeDirection ? getMainTop(cellIndex) : getMainBottom(cellIndex); } private int getMainBottom(final int cellIndex) { return cellIndex + Game.BOARD_COLUMN_COUNT + 1; } private int getMainTop(final int cellIndex) { return cellIndex - Game.BOARD_COLUMN_COUNT - 1; } }
asenovm/Reversi
src/edu/fmi/ai/reversi/move/MainDiagonalMoveChecker.java
Java
mit
1,257
/******************************************************************************* * Copyright (c) 2019 Infostretch Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package com.qmetry.qaf.automation.ui.api; import com.qmetry.qaf.automation.core.MessageTypes; /** * com.qmetry.qaf.automation.core.ui.api.TestBase.java * * @author chirag */ public interface UiTestBase<D> { /** * @return driver */ D getDriver(); void tearDown(); void prepareForShutDown(); boolean isPreparedForShutDown(); void addTestStepLog(String msg); void addAssertionsLog(String msg); void addAssertionsLog(String msg, MessageTypes type); /** * Get BaseUrl for current test base * * @return */ String getBaseUrl(); /** * Get current running browser string i.e. *firefox, firefoxDriver, * firefoxRemoteDriver ... * * @return browser string */ String getBrowser(); }
qmetry/qaf
src/com/qmetry/qaf/automation/ui/api/UiTestBase.java
Java
mit
2,073
package mopedp2pserver; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class P2PServer { //List of all mopeds //Mopeds can connect to this to get listed //Mopeds can timeout //App can call this server to recieve the moped list with all IPs final int port; List<MopedConnection> connections = Collections.synchronizedList(new ArrayList<>()); public P2PServer(int port) throws Exception { //Starts a new welcomer thread. this.port = port; new Thread(new Welcomer(port)).start(); } /** * Returns the ip of the first occurrence of a client with the same name as * the parameter. Returns "" if there is no occurrence. * * @param name * @return */ private String getClientIPByName(String name) { name = name.toLowerCase(); for (int i = 0; i < connections.size(); i++) { System.out.println("getIP: " + i + " " + connections.get(i).name); if (connections.get(i).name.equals(name)) { return connections.get(i).socket.getRemoteSocketAddress().toString() .split(":")[0]; } } return ""; } private class Welcomer implements Runnable { ServerSocket welcomeSocket; public Welcomer(int port) throws IOException { welcomeSocket = new ServerSocket(port); } @Override public void run() { System.out.println("Running Welcomer"); try { while (true) { System.out.println("Server: waiting"); Socket newSocket = welcomeSocket.accept(); //Prevents duplicate IPs from connecting, preventing terrible things like endless threads and connections. boolean duplicateConnection = false; for (int i = 0; i < connections.size(); i++) { if (newSocket.getInetAddress() .equals(connections.get(i).socket.getInetAddress())) { System.out.println("Server: duplicate connection, rejected"); newSocket.close(); duplicateConnection = true; break; } } if (duplicateConnection) { continue; } //Add new connection if it was allowed. MopedConnection newConnection = new MopedConnection(newSocket); connections.add(newConnection); new Thread(newConnection).start(); System.out.println("Server: new connection"); } } catch (Exception e) { e.printStackTrace(); } } } private class MopedConnection implements Runnable { //TODO: Timeout timer Socket socket; DataOutputStream out; BufferedReader reader; String name = ""; String slaveName = ""; public MopedConnection(Socket socket) throws IOException { this.socket = socket; out = new DataOutputStream(socket.getOutputStream()); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); } private void sendNewSlave(String ip) throws UnknownHostException, IOException { if (ip.equals("")) out.writeBytes("ms\n"); else out.writeBytes("cs§" + ip + "\n"); } private void readMopedPacket() throws IOException { String inString = reader.readLine(); System.out.println("In: " + inString); parseMopedPacket(inString); } private void parseMopedPacket(String inString) { String[] strings = inString.split("§"); if (strings[0].equals("ms") && strings.length == 3) { parseNameString(strings[1]); parseSlaveNameString(strings[2]); } else System.out.println("Server: Unknown packet"); } private void parseNameString(String name) { name = name.toLowerCase(); this.name = name; } private void parseSlaveNameString(String slaveName) { this.slaveName = slaveName; } @Override public void run() { try { while (true) { System.out.println("connection loop"); //Move out of loop? Might only be needed on new connections? readMopedPacket(); sendNewSlave(getClientIPByName(slaveName)); } } catch (Exception e) { e.printStackTrace(); } finally { try { socket.close(); connections.remove(this); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
Aoldo/MopedNetwork
src/mopedp2pserver/P2PServer.java
Java
mit
4,426
package org.yield4j.tests.whileloop; import static org.yield4j.YieldSupport.*; //>> [0, 1, 2, 3, 4] public class YieldReturnInWhile { @org.yield4j.Generator public Iterable<Integer> method() { int i = 0; while (i < 5) { yield_return(i++); } } }
provegard/yield4j
src/test/resources/org/yield4j/tests/whileloop/YieldReturnInWhile.java
Java
mit
260
/* * Copyright (c) 2007-2018 Siemens AG * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.siemens.ct.exi.main.data; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.math.BigInteger; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.Inflater; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import junit.framework.AssertionFailedError; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.siemens.ct.exi.core.CodingMode; import com.siemens.ct.exi.core.DecodingOptions; import com.siemens.ct.exi.core.EXIFactory; import com.siemens.ct.exi.core.EncodingOptions; import com.siemens.ct.exi.core.FidelityOptions; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.helpers.DefaultEXIFactory; import com.siemens.ct.exi.core.io.compression.EXIInflaterInputStream; import com.siemens.ct.exi.main.api.sax.EXIResult; import com.siemens.ct.exi.main.api.sax.SAXFactory; public class MultipleStreamTest extends AbstractTestCase { public static String XML_NOTEBOOK = "<notebook date=\"2007-09-12\"><note date=\"2007-07-23\" category=\"EXI\"><subject>EXI</subject><body>Do not forget it!</body></note><note date=\"2007-09-12\"><subject>shopping list</subject><body>milk, honey</body></note></notebook>"; public MultipleStreamTest(String s) { super(s); } protected void _testEncode(EXIFactory exiFactory, byte[] isBytes, int numberOfEXIDocuments, ByteArrayOutputStream osEXI) throws AssertionFailedError, Exception { // encode exi document multiple times for (int i = 0; i < numberOfEXIDocuments; i++) { EXIResult exiResult = new EXIResult(exiFactory); exiResult.setOutputStream(osEXI); XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setContentHandler(exiResult.getHandler()); // set LexicalHandler xmlReader.setProperty( "http://xml.org/sax/properties/lexical-handler", exiResult.getLexicalHandler()); xmlReader.parse(new InputSource(new ByteArrayInputStream(isBytes))); } // System.out.println("OutputSize: " + os.size()); } protected void _testDecode(EXIFactory exiFactory, byte[] isBytes, int numberOfEXIDocuments, InputStream isEXI) throws EXIException, TransformerException, AssertionFailedError, IOException, ParserConfigurationException, SAXException { // decode EXI TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); for (int i = 0; i < numberOfEXIDocuments; i++) { // InputSource is = new InputSource(isEXI); InputSource is = new InputSource(isEXI); SAXSource exiSource = new SAXSource(is); XMLReader exiReader = new SAXFactory(exiFactory).createEXIReader(); exiSource.setXMLReader(exiReader); ByteArrayOutputStream xmlOutput = new ByteArrayOutputStream(); Result result = new StreamResult(xmlOutput); transformer.transform(exiSource, result); byte[] xmlDec = xmlOutput.toByteArray(); // System.out.println("Decode #" + (i+1) + new String(xmlDec)); ByteArrayInputStream baisControl = new ByteArrayInputStream(isBytes); // testing // only checkXMLEquality(exiFactory, baisControl, new ByteArrayInputStream( xmlDec)); // checkXMLValidity(exiFactory, new ByteArrayInputStream(xmlDec)); } } protected void _test(EXIFactory exiFactory, byte[] isBytes, int numberOfEXIDocuments) throws AssertionFailedError, Exception { // output stream ByteArrayOutputStream osEXI = new ByteArrayOutputStream(); _testEncode(exiFactory, isBytes, numberOfEXIDocuments, osEXI); InputStream isEXI = new ByteArrayInputStream(osEXI.toByteArray()); _testDecode(exiFactory, isBytes, numberOfEXIDocuments, new PushbackInputStream(isEXI, DecodingOptions.PUSHBACK_BUFFER_SIZE)); } public void testXMLNotebook4() throws Exception { // exi factory EXIFactory exiFactory = DefaultEXIFactory.newInstance(); exiFactory.setCodingMode(CodingMode.COMPRESSION); EncodingOptions encOption = EncodingOptions.createDefault(); encOption.setOption(EncodingOptions.INCLUDE_COOKIE); encOption.setOption(EncodingOptions.INCLUDE_OPTIONS); exiFactory.setEncodingOptions(encOption); _test(exiFactory, XML_NOTEBOOK.getBytes(), 4); } public void testXMLNotebook6Block3() throws Exception { // exi factory EXIFactory exiFactory = DefaultEXIFactory.newInstance(); exiFactory.setBlockSize(3); exiFactory.setCodingMode(CodingMode.COMPRESSION); exiFactory.setFidelityOptions(FidelityOptions.createAll()); _test(exiFactory, XML_NOTEBOOK.getBytes(), 6); } public void testXMLRandj3() throws Exception { // exi factory EXIFactory exiFactory = DefaultEXIFactory.newInstance(); exiFactory.setCodingMode(CodingMode.COMPRESSION); exiFactory.setFidelityOptions(FidelityOptions.createAll()); EncodingOptions encOption = EncodingOptions.createDefault(); encOption.setOption(EncodingOptions.INCLUDE_COOKIE); encOption.setOption(EncodingOptions.INCLUDE_XSI_SCHEMALOCATION); encOption.setOption(EncodingOptions.INCLUDE_INSIGNIFICANT_XSI_NIL); exiFactory.setEncodingOptions(encOption); // String sXML = "./data/general/randj.xml"; InputStream is = new FileInputStream(sXML); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = is.read()) != -1) { baos.write(b); } is.close(); _test(exiFactory, baos.toByteArray(), 3); } public void testXMLRandj3Add() throws Exception { // exi factory EXIFactory exiFactory = DefaultEXIFactory.newInstance(); exiFactory.setCodingMode(CodingMode.COMPRESSION); exiFactory.setFidelityOptions(FidelityOptions.createAll()); EncodingOptions encOption = EncodingOptions.createDefault(); encOption.setOption(EncodingOptions.INCLUDE_COOKIE); encOption.setOption(EncodingOptions.INCLUDE_XSI_SCHEMALOCATION); encOption.setOption(EncodingOptions.INCLUDE_INSIGNIFICANT_XSI_NIL); exiFactory.setEncodingOptions(encOption); // String sXML = "./data/general/randj.xml"; InputStream is = new FileInputStream(sXML); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = is.read()) != -1) { baos.write(b); } is.close(); ByteArrayOutputStream osEXI = new ByteArrayOutputStream(); _testEncode(exiFactory, baos.toByteArray(), 3, osEXI); // add some bytes after EXI osEXI.write(31); osEXI.write(2); osEXI.write(99); osEXI.write(200); InputStream isEXI = new ByteArrayInputStream(osEXI.toByteArray()); isEXI = new BufferedInputStream(isEXI); isEXI = new PushbackInputStream(isEXI, DecodingOptions.PUSHBACK_BUFFER_SIZE); _testDecode(exiFactory, baos.toByteArray(), 3, isEXI); // System.out.println(isEXI.read()); assertTrue(isEXI.read() == 31); assertTrue(isEXI.read() == 2); assertTrue(isEXI.read() == 99); assertTrue(isEXI.read() == 200); assertTrue(isEXI.read() == -1); } // /////////////////////////////////////////////////// // TEST // ////////////////////////////////////////////////// public static final boolean nowrap = true; // EXI requires no wrap final static int NUMBER_OF_EXI_FILES = 20; final static int NUMBER_OF_HEADER_BYTES = 10; final static byte HEADER_BYTE = 123; final static int NUMBER_OF_CHANNELS = 2; final static int NUMBER_OF_BYTES = 5; final static boolean RANDOM_BYTES = true; final static int BYTES_LENGTH = 26; public static void printJVMInfos() { System.out.println("java.class.path : " + System.getProperty("java.class.path")); System.out.println("java.vendor : " + System.getProperty("java.vendor")); System.out.println("java.vendor.url : " + System.getProperty("java.vendor.url")); System.out.println("java.version : " + System.getProperty("java.version")); System.out.println("sun.arch.data.model: " + System.getProperty("sun.arch.data.model")); } public static void main(String[] args) throws IOException { printJVMInfos(); List<byte[]> encodeBytes = new ArrayList<byte[]>(); /* * ENCODING */ System.out.println(">> Start encoding..."); ByteArrayOutputStream os = new ByteArrayOutputStream(); for (int f = 0; f < NUMBER_OF_EXI_FILES; f++) { System.out.println("File " + f); // encode for (int j = 0; j < NUMBER_OF_HEADER_BYTES; j++) { // os.write(random.nextInt()); // EXI header os.write(HEADER_BYTE); } Deflater deflater = null; for (int k = 0; k < NUMBER_OF_CHANNELS; k++) { System.out.println(" Channel " + k); if (deflater == null) { deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, nowrap); } else { deflater.reset(); } DeflaterOutputStream deflaterOS = new DeflaterOutputStream(os, deflater); // some EXI data for (int i = 0; i < NUMBER_OF_BYTES; i++) { byte[] bs = getBytes(BYTES_LENGTH); encodeBytes.add(bs); System.out.println("\t" + new String(bs)); deflaterOS.write(bs); } // finalize deflate stream deflaterOS.finish(); // deflaterOS.close(); System.out.println("\t\tLastByte of deflater " + os.toByteArray()[os.toByteArray().length - 1]); } os.flush(); } byte[] bytesEXI = os.toByteArray(); os.close(); /* * DECODING */ System.out.println("<< Start decoding..."); InputStream is = new ByteArrayInputStream(bytesEXI); is = new BufferedInputStream(is); // mark supported for other not // "markable" streams e.g., file // stream // is.mark(Integer.MAX_VALUE); is = new PushbackInputStream(is, DecodingOptions.PUSHBACK_BUFFER_SIZE); List<byte[]> decodeBytes = new ArrayList<byte[]>(); for (int f = 0; f < NUMBER_OF_EXI_FILES; f++) { System.out.println("File " + f); System.out.println("Available Bytes before header: " + is.available()); // decode header for (int j = 0; j < NUMBER_OF_HEADER_BYTES; j++) { int h = is.read();// EXI header if (h != HEADER_BYTE) { // '€' throw new RuntimeException( "EXI Header Error BYTES MISMATCH"); } } Inflater inflater = new Inflater(nowrap); System.out.println("Available Bytes after header: " + is.available()); // decode channels for (int k = 0; k < NUMBER_OF_CHANNELS; k++) { System.out.println("Remaining: " + inflater.getRemaining()); // System.out.println("Available: " + is.available()); // is.mark(inputBufferSize); // mark position for possible // rewind, // max size according inflater // buffer // if ( inflater.getRemaining() == 0) { // // no skipping needed // } else { // // skip // int av = is.available() + inflater.getRemaining(); // is.reset(); // int toskip = is.available() - av; // is.skip(toskip); // } // inflater.reset(); @SuppressWarnings("resource") EXIInflaterInputStream inflaterInputStream = new EXIInflaterInputStream( (PushbackInputStream) is, inflater, DecodingOptions.PUSHBACK_BUFFER_SIZE); for (int i = 0; i < NUMBER_OF_BYTES; i++) { byte[] bs = new byte[BYTES_LENGTH]; for (int l = 0; l < BYTES_LENGTH; l++) { bs[l] = (byte) inflaterInputStream.read(); } decodeBytes.add(bs); System.out.println("\t" + new String(bs)); } System.out.println("Available Bytes after channel " + k + ": " + is.available() + " and inflater still contains " + inflater.getRemaining() + " in buffer and " + inflater.getBytesRead() + " bytes read so far"); if (inflater.getRemaining() > 0) { // inflater read beyond deflate stream, reset position // is.reset(); // is.skip(inflater.getBytesRead()); System.out.println("--> Rewind " + inflater.getRemaining() + " bytes"); inflaterInputStream.pushbackAndReset(); } } // // Note: in many cases not needed (e.g., if no buffered stream // passed) // // fix input stream so that another process can read data at the // right position... // if ( inflater.getRemaining() != 0) { // int av = inflater.getRemaining() + is.available(); // is.reset(); // int toskip = is.available() - av; // is.skip(toskip); // } } /* * CONSISTENCY CHECK */ // compare strings if (encodeBytes.size() != decodeBytes.size()) { throw new RuntimeException("Bytes SIZE MISMATCH"); } for (int i = 0; i < encodeBytes.size(); i++) { byte[] e = encodeBytes.get(i); byte[] d = decodeBytes.get(i); if (!Arrays.equals(e, d)) { throw new RuntimeException("Bytes MISMATCH"); } } } private static SecureRandom random = new SecureRandom(); public static byte[] getBytes(int len) { String s; if (RANDOM_BYTES) { s = new BigInteger(130, random).toString(32); if (s.length() > len) { s = s.substring(0, len); } else { while (s.length() < len) { s += "X"; } } } else { StringBuffer sb = new StringBuffer(); for (int i = 0; i < len; i++) { sb.append((char) (i + 'A')); } s = sb.toString(); } byte[] bs = s.getBytes(); if (bs.length != len) { throw new RuntimeException("BYTES MISMATCH!!!"); } return bs; } }
EXIficient/exificient
src/test/java/com/siemens/ct/exi/main/data/MultipleStreamTest.java
Java
mit
15,265
package multithreading.lowlevelsynchronization; import java.util.LinkedList; import java.util.Random; import java.util.Scanner; /** * Created by Andromed.Codes on 27/06/2017. * This class demonstrates how to implement a low-level synchronizations on objects. * the main goal of this class is to manage read/write access to an object by multiple threads */ public class App { private final Object mLock = new Object(); private LinkedList<Integer> mList = new LinkedList<>(); private boolean stopRequest = false; private Thread t1 = new Thread(this::append); private Thread t2 = new Thread(() -> { try { shrink(); } catch (InterruptedException e) { e.printStackTrace(); } }); public void execute() { t1.start(); t2.start(); Scanner scanner = new Scanner(System.in); if (scanner.nextLine().equals("")) stopRequest = true; try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } } private void append() { Random random = new Random(); while (!stopRequest) synchronized (mLock) { mList.add(random.nextInt(1000)); mLock.notify(); } } private void shrink() throws InterruptedException { while (!stopRequest) { synchronized (mLock) { while (mList.size() == 0) try { mLock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } int value = mList.removeFirst(); System.out.println(value + " was removed from the list."); mLock.notify(); } Thread.sleep(1000); } } }
andromedcodes/JavaMultiThreading
src/multithreading/lowlevelsynchronization/App.java
Java
mit
1,905
package me.minidigger.voxelgameslib.api.timings; import java.time.Duration; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import lombok.extern.java.Log; /** * Small class that helps with timing stuff */ @Log public class Timings { /** * Times a task, will print the result with log level finer * * @param name the name of the task * @param executor the task to be timed */ public static void time(String name, TimingsExecutor executor) { LocalDateTime start = LocalDateTime.now(); executor.execute(); LocalDateTime end = LocalDateTime.now(); Duration duration = Duration.between(start, end); String time = LocalTime.MIDNIGHT.plus(duration).format(DateTimeFormatter.ofPattern("HH:mm:ss:SSS")); log.finer("Timings: " + name + " took " + time); } }
MiniDigger/VoxelGamesLib
api/src/main/java/me/minidigger/voxelgameslib/api/timings/Timings.java
Java
mit
899
package fr.eseo.game.command; import java.util.ArrayList; import java.util.List; /** * Command class. * * @author Axel Gendillard */ public class Command { /* ATTRIBUTES */ /** * CommandEnum attribute. */ private CommandEnum commandEnum; /** * List of the values. */ private List<Integer> values; /* CONSTRUCTORS */ /** * Constructor Command. Create an object command from a String * (ex. "/D -1 0" or "/C 2 2 1-0-1-1"). * @param command Command string. * @throws NullPointerException NullPointerException. * @throws NumberFormatException NumberFormatException. */ public Command(String command) throws NullPointerException, NumberFormatException { String[] list = command.replace("-", " ").split(" "); this.commandEnum = CommandEnum.fromString(list[0]); this.values = new ArrayList<>(); if (this.commandEnum.equals(CommandEnum.MOVE_PIRATE_CLIENT)) { list = command.split(" "); } // Remove command (ex. "/D") from list. list[0] = null; this.fillValues(list); } /* METHODS */ /** * Parse the string array to an integer list. * @param list Array of string. */ private void fillValues(String[] list) { for (String s : list) { // All array except first element (it's not a number) if (s != null) { try { this.values.add(Integer.valueOf(s)); } catch (NumberFormatException e) { throw new NumberFormatException("It's not an integer : " + s); } } } } /* ACCESSORS */ /** * Getter of commandEnum. * @return commandEnum */ public CommandEnum getCommandEnum() { return this.commandEnum; } /** * Getter of values. * @return list */ public List<Integer> getValues() { return this.values; } }
percenuage/Monkeys
src/fr/eseo/game/command/Command.java
Java
mit
2,008
package io.zhpooer.store.web.filter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Map; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * 解决get和post请求 全部乱码 * * @author seawind * */ public class GenericEncodingFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 转型为与协议相关对象 HttpServletRequest httpServletRequest = (HttpServletRequest) request; // 对request包装增强 HttpServletRequest myrequest = new MyRequest(httpServletRequest); chain.doFilter(myrequest, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } } // 自定义request对象 class MyRequest extends HttpServletRequestWrapper { private HttpServletRequest request; private boolean hasEncode; public MyRequest(HttpServletRequest request) { super(request);// super必须写 this.request = request; } // 对需要增强方法 进行覆盖 @SuppressWarnings("rawtypes") @Override public Map getParameterMap() { // 先获得请求方式 String method = request.getMethod(); if (method.equalsIgnoreCase("post")) { // post请求 try { // 处理post乱码 request.setCharacterEncoding("utf-8"); return request.getParameterMap(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else if (method.equalsIgnoreCase("get")) { // get请求 @SuppressWarnings("unchecked") Map<String, String[]> parameterMap = request.getParameterMap(); if (!hasEncode) { // 确保get手动编码逻辑只运行一次 for (String parameterName : parameterMap.keySet()) { String[] values = parameterMap.get(parameterName); if (values != null) { for (int i = 0; i < values.length; i++) { try { // 处理get乱码 values[i] = new String( values[i].getBytes("ISO-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } hasEncode = true; } return parameterMap; } return super.getParameterMap(); } @Override public String getParameter(String name) { @SuppressWarnings("unchecked") Map<String, String[]> parameterMap = getParameterMap(); String[] values = parameterMap.get(name); if (values == null) { return null; } return values[0]; // 取回参数的第一个值 } @Override public String[] getParameterValues(String name) { @SuppressWarnings("unchecked") Map<String, String[]> parameterMap = getParameterMap(); String[] values = parameterMap.get(name); return values; } }
zhpooer/itcast-store-manager
src/java/io/zhpooer/store/web/filter/GenericEncodingFilter.java
Java
mit
3,726
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.appservice.fluent; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import com.azure.resourcemanager.appservice.fluent.models.CertificateInner; import com.azure.resourcemanager.appservice.models.CertificatePatchResource; import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsDelete; import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsGet; import com.azure.resourcemanager.resources.fluentcore.collection.InnerSupportsListing; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in CertificatesClient. */ public interface CertificatesClient extends InnerSupportsGet<CertificateInner>, InnerSupportsListing<CertificateInner>, InnerSupportsDelete<Void> { /** * Get all certificates for a subscription. * * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all certificates for a subscription. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<CertificateInner> listAsync(); /** * Get all certificates for a subscription. * * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all certificates for a subscription. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<CertificateInner> list(); /** * Get all certificates for a subscription. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all certificates for a subscription. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<CertificateInner> list(Context context); /** * Get all certificates in a resource group. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all certificates in a resource group. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<CertificateInner> listByResourceGroupAsync(String resourceGroupName); /** * Get all certificates in a resource group. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all certificates in a resource group. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<CertificateInner> listByResourceGroup(String resourceGroupName); /** * Get all certificates in a resource group. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all certificates in a resource group. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<CertificateInner> listByResourceGroup(String resourceGroupName, Context context); /** * Get a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a certificate. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<CertificateInner>> getByResourceGroupWithResponseAsync(String resourceGroupName, String name); /** * Get a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a certificate. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<CertificateInner> getByResourceGroupAsync(String resourceGroupName, String name); /** * Get a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a certificate. */ @ServiceMethod(returns = ReturnType.SINGLE) CertificateInner getByResourceGroup(String resourceGroupName, String name); /** * Get a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a certificate. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<CertificateInner> getByResourceGroupWithResponse(String resourceGroupName, String name, Context context); /** * Create or update a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @param certificateEnvelope Details of certificate, if it exists already. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return sSL certificate for an app. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<CertificateInner>> createOrUpdateWithResponseAsync( String resourceGroupName, String name, CertificateInner certificateEnvelope); /** * Create or update a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @param certificateEnvelope Details of certificate, if it exists already. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return sSL certificate for an app. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<CertificateInner> createOrUpdateAsync( String resourceGroupName, String name, CertificateInner certificateEnvelope); /** * Create or update a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @param certificateEnvelope Details of certificate, if it exists already. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return sSL certificate for an app. */ @ServiceMethod(returns = ReturnType.SINGLE) CertificateInner createOrUpdate(String resourceGroupName, String name, CertificateInner certificateEnvelope); /** * Create or update a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @param certificateEnvelope Details of certificate, if it exists already. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return sSL certificate for an app. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<CertificateInner> createOrUpdateWithResponse( String resourceGroupName, String name, CertificateInner certificateEnvelope, Context context); /** * Delete a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<Void>> deleteWithResponseAsync(String resourceGroupName, String name); /** * Delete a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Void> deleteAsync(String resourceGroupName, String name); /** * Delete a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceGroupName, String name); /** * Delete a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<Void> deleteWithResponse(String resourceGroupName, String name, Context context); /** * Create or update a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @param certificateEnvelope Details of certificate, if it exists already. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return sSL certificate for an app. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<CertificateInner>> updateWithResponseAsync( String resourceGroupName, String name, CertificatePatchResource certificateEnvelope); /** * Create or update a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @param certificateEnvelope Details of certificate, if it exists already. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return sSL certificate for an app. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<CertificateInner> updateAsync( String resourceGroupName, String name, CertificatePatchResource certificateEnvelope); /** * Create or update a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @param certificateEnvelope Details of certificate, if it exists already. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return sSL certificate for an app. */ @ServiceMethod(returns = ReturnType.SINGLE) CertificateInner update(String resourceGroupName, String name, CertificatePatchResource certificateEnvelope); /** * Create or update a certificate. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the certificate. * @param certificateEnvelope Details of certificate, if it exists already. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.resourcemanager.appservice.models.DefaultErrorResponseErrorException thrown if the request is * rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return sSL certificate for an app. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<CertificateInner> updateWithResponse( String resourceGroupName, String name, CertificatePatchResource certificateEnvelope, Context context); }
Azure/azure-sdk-for-java
sdk/resourcemanagerhybrid/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/fluent/CertificatesClient.java
Java
mit
17,241
package com.codepath.apps.restclienttemplate.models; import com.codepath.apps.restclienttemplate.MyDatabase; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.PrimaryKey; import com.raizlabs.android.dbflow.annotation.Table; import com.raizlabs.android.dbflow.sql.language.Select; import com.raizlabs.android.dbflow.structure.BaseModel; import org.json.JSONException; import org.json.JSONObject; import java.util.List; /* * This is a temporary, sample model that demonstrates the basic structure * of a SQLite persisted Model object. Check out the DBFlow wiki for more details: * https://github.com/codepath/android_guides/wiki/DBFlow-Guide * * Note: All models **must extend from** `BaseModel` as shown below. * */ @Table(database = MyDatabase.class) public class SampleModel extends BaseModel { @PrimaryKey @Column Long id; // Define table fields @Column private String name; public SampleModel() { super(); } // Parse model from JSON public SampleModel(JSONObject object){ super(); try { this.name = object.getString("title"); } catch (JSONException e) { e.printStackTrace(); } } // Getters public String getName() { return name; } // Setters public void setName(String name) { this.name = name; } /* The where class in this code below will be marked red until you first compile the project, since the code * for the SampleModel_Table class is generated at compile-time. */ // Record Finders public static SampleModel byId(long id) { return new Select().from(SampleModel.class).where(SampleModel_Table.id.eq(id)).querySingle(); } public static List<SampleModel> recentItems() { return new Select().from(SampleModel.class).orderBy(SampleModel_Table.id, false).limit(300).queryList(); } }
ghilbing/Twitter
app/src/main/java/com/codepath/apps/restclienttemplate/models/SampleModel.java
Java
mit
1,846
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package fixtures.paging; import com.microsoft.azure.CloudException; import com.microsoft.azure.ListOperationCallback; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceResponse; import fixtures.paging.models.PageImpl; import fixtures.paging.models.PagingGetMultiplePagesOptions; import fixtures.paging.models.PagingGetMultiplePagesWithOffsetNextOptions; import fixtures.paging.models.PagingGetMultiplePagesWithOffsetOptions; import fixtures.paging.models.Product; import java.io.IOException; import java.util.List; /** * An instance of this class provides access to all the operations defined * in PagingOperations. */ public interface PagingOperations { /** * A paging operation that finishes on the first call without a nextlink. * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<List<Product>> getSinglePages() throws CloudException, IOException; /** * A paging operation that finishes on the first call without a nextlink. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getSinglePagesAsync(final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages. * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<List<Product>> getMultiplePages() throws CloudException, IOException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesAsync(final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param clientRequestId the String value * @param pagingGetMultiplePagesOptions Additional parameters for the operation * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<List<Product>> getMultiplePages(final String clientRequestId, final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions) throws CloudException, IOException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param clientRequestId the String value * @param pagingGetMultiplePagesOptions Additional parameters for the operation * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesAsync(final String clientRequestId, final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions, final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param pagingGetMultiplePagesWithOffsetOptions Additional parameters for the operation * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<List<Product>> getMultiplePagesWithOffset(final PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions) throws CloudException, IOException, IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param pagingGetMultiplePagesWithOffsetOptions Additional parameters for the operation * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesWithOffsetAsync(final PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param pagingGetMultiplePagesWithOffsetOptions Additional parameters for the operation * @param clientRequestId the String value * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<List<Product>> getMultiplePagesWithOffset(final PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, final String clientRequestId) throws CloudException, IOException, IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param pagingGetMultiplePagesWithOffsetOptions Additional parameters for the operation * @param clientRequestId the String value * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesWithOffsetAsync(final PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, final String clientRequestId, final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that fails on the first call with 500 and then retries and then get a response including a nextLink that has 10 pages. * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<List<Product>> getMultiplePagesRetryFirst() throws CloudException, IOException; /** * A paging operation that fails on the first call with 500 and then retries and then get a response including a nextLink that has 10 pages. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesRetryFirstAsync(final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages, of which the 2nd call fails first with 500. The client should retry and finish all 10 pages eventually. * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<List<Product>> getMultiplePagesRetrySecond() throws CloudException, IOException; /** * A paging operation that includes a nextLink that has 10 pages, of which the 2nd call fails first with 500. The client should retry and finish all 10 pages eventually. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesRetrySecondAsync(final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that receives a 400 on the first call. * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<List<Product>> getSinglePagesFailure() throws CloudException, IOException; /** * A paging operation that receives a 400 on the first call. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getSinglePagesFailureAsync(final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that receives a 400 on the second call. * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<List<Product>> getMultiplePagesFailure() throws CloudException, IOException; /** * A paging operation that receives a 400 on the second call. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesFailureAsync(final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that receives an invalid nextLink. * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<List<Product>> getMultiplePagesFailureUri() throws CloudException, IOException; /** * A paging operation that receives an invalid nextLink. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesFailureUriAsync(final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that finishes on the first call without a nextlink. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<PageImpl<Product>> getSinglePagesNext(final String nextPageLink) throws CloudException, IOException, IllegalArgumentException; /** * A paging operation that finishes on the first call without a nextlink. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getSinglePagesNextAsync(final String nextPageLink, final ServiceCall serviceCall, final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<PageImpl<Product>> getMultiplePagesNext(final String nextPageLink) throws CloudException, IOException, IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesNextAsync(final String nextPageLink, final ServiceCall serviceCall, final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param clientRequestId the String value * @param pagingGetMultiplePagesOptions Additional parameters for the operation * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<PageImpl<Product>> getMultiplePagesNext(final String nextPageLink, final String clientRequestId, final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions) throws CloudException, IOException, IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param clientRequestId the String value * @param pagingGetMultiplePagesOptions Additional parameters for the operation * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesNextAsync(final String nextPageLink, final String clientRequestId, final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions, final ServiceCall serviceCall, final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<PageImpl<Product>> getMultiplePagesWithOffsetNext(final String nextPageLink) throws CloudException, IOException, IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesWithOffsetNextAsync(final String nextPageLink, final ServiceCall serviceCall, final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param clientRequestId the String value * @param pagingGetMultiplePagesWithOffsetNextOptions Additional parameters for the operation * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<PageImpl<Product>> getMultiplePagesWithOffsetNext(final String nextPageLink, final String clientRequestId, final PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions) throws CloudException, IOException, IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param clientRequestId the String value * @param pagingGetMultiplePagesWithOffsetNextOptions Additional parameters for the operation * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesWithOffsetNextAsync(final String nextPageLink, final String clientRequestId, final PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions, final ServiceCall serviceCall, final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that fails on the first call with 500 and then retries and then get a response including a nextLink that has 10 pages. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<PageImpl<Product>> getMultiplePagesRetryFirstNext(final String nextPageLink) throws CloudException, IOException, IllegalArgumentException; /** * A paging operation that fails on the first call with 500 and then retries and then get a response including a nextLink that has 10 pages. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesRetryFirstNextAsync(final String nextPageLink, final ServiceCall serviceCall, final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages, of which the 2nd call fails first with 500. The client should retry and finish all 10 pages eventually. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<PageImpl<Product>> getMultiplePagesRetrySecondNext(final String nextPageLink) throws CloudException, IOException, IllegalArgumentException; /** * A paging operation that includes a nextLink that has 10 pages, of which the 2nd call fails first with 500. The client should retry and finish all 10 pages eventually. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesRetrySecondNextAsync(final String nextPageLink, final ServiceCall serviceCall, final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that receives a 400 on the first call. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<PageImpl<Product>> getSinglePagesFailureNext(final String nextPageLink) throws CloudException, IOException, IllegalArgumentException; /** * A paging operation that receives a 400 on the first call. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getSinglePagesFailureNextAsync(final String nextPageLink, final ServiceCall serviceCall, final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that receives a 400 on the second call. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<PageImpl<Product>> getMultiplePagesFailureNext(final String nextPageLink) throws CloudException, IOException, IllegalArgumentException; /** * A paging operation that receives a 400 on the second call. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesFailureNextAsync(final String nextPageLink, final ServiceCall serviceCall, final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; /** * A paging operation that receives an invalid nextLink. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the List&lt;Product&gt; object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse<PageImpl<Product>> getMultiplePagesFailureUriNext(final String nextPageLink) throws CloudException, IOException, IllegalArgumentException; /** * A paging operation that receives an invalid nextLink. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ ServiceCall getMultiplePagesFailureUriNextAsync(final String nextPageLink, final ServiceCall serviceCall, final ListOperationCallback<Product> serviceCallback) throws IllegalArgumentException; }
stankovski/AutoRest
AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/paging/PagingOperations.java
Java
mit
26,148
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.concurrent.atomic.AtomicInteger; import javax.swing.*; import javax.swing.plaf.basic.BasicInternalFrameUI; public final class MainPanel extends JPanel { private static final int OFFSET = 30; private static final AtomicInteger OPEN_COUNTER = new AtomicInteger(); private MainPanel() { super(new BorderLayout()); System.out.println(UIManager.get("Desktop.minOnScreenInsets")); JInternalFrame f = createInternalFrame(); Dimension d = ((BasicInternalFrameUI) f.getUI()).getNorthPane().getPreferredSize(); UIManager.put("Desktop.minOnScreenInsets", new Insets(d.height, 16, 3, 16)); UIManager.put("Desktop.background", Color.LIGHT_GRAY); JDesktopPane desktop = new JDesktopPane(); desktop.add(f); JMenu menu = new JMenu("Window"); menu.setMnemonic(KeyEvent.VK_W); JMenuItem menuItem = menu.add("New"); menuItem.setMnemonic(KeyEvent.VK_N); menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.ALT_DOWN_MASK)); menuItem.setActionCommand("new"); menuItem.addActionListener(e -> desktop.add(createInternalFrame())); JMenuBar menuBar = new JMenuBar(); menuBar.add(menu); EventQueue.invokeLater(() -> getRootPane().setJMenuBar(menuBar)); add(desktop); setPreferredSize(new Dimension(320, 240)); } private static JInternalFrame createInternalFrame() { String title = String.format("Document #%s", OPEN_COUNTER.getAndIncrement()); JInternalFrame f = new JInternalFrame(title, true, true, true, true); f.getContentPane().add(new JScrollPane(new JTree())); f.setSize(160, 100); f.setLocation(OFFSET * OPEN_COUNTER.intValue(), OFFSET * OPEN_COUNTER.intValue()); EventQueue.invokeLater(() -> f.setVisible(true)); return f; } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
aterai/java-swing-tips
DesktopMinOnScreenInsets/src/java/example/MainPanel.java
Java
mit
2,644
package cs2ts6.client; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import cs2ts6.packets.ChatPacket; /** * @author Ian, Vincent, Stephen * This panel is accessible to the teacher in order to * start the embedded server on request. */ public class AdminPanel extends JPanel implements ActionListener{ /** * Automatically generated serial version ID. */ private static final long serialVersionUID = -5253910251343064918L; private JButton startServer, freezeSession; private ChatPanel cht; public AdminPanel (Image bimg, ChatPanel chatPanel){ //This button starts the server startServer = new JButton("Start Server"); freezeSession = new JButton ("Freeze Session"); cht = chatPanel; add(startServer); add(freezeSession); freezeSession.setEnabled(false); startServer.setEnabled(false); startServer.addActionListener(this); freezeSession.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { int status; // If the button is the startServer button if(e.getSource() == startServer){ System.out.println("HERE"); status = cht.runServerCode(); if(status != -1) { freezeSession.setEnabled(true); } startServer.setEnabled(false); } // If the button is the freezeSession button if(e.getSource() == freezeSession){ if(MainWindow.frozen == false) { ChatPacket chtpkt = new ChatPacket("ADMIN", "Session Frozen"); cht.client.sendMessage(chtpkt); freezeSession.setText("Un-Freeze Session"); } else { ChatPacket chtpkt = new ChatPacket("ADMIN", "Session Unfrozen"); cht.client.sendMessage(chtpkt); cht.client.clearCanvas(); freezeSession.setText("Freeze Session"); } } }; public void setAdmin() { startServer.setEnabled(true); } }
IanField90/DrawAndTalk
DrawTalk/src/cs2ts6/client/AdminPanel.java
Java
mit
1,938
package jaybur.euler; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class Challenge005Test { @Test public void testIsDivisableByRange() { boolean result = Challenge005.isDivisableByRange(2520, 10); assertTrue( "Failed to confirm the input is divisable by numbers in the range 1..10", result); } @Test public void testIsDivisableByRange_false() { boolean result = Challenge005.isDivisableByRange(2500, 10); assertFalse( "Failed to confirm the input is not divisable by numbers in the range 1..10", result); } @Test public void testMaxAnswerResult() { int maxRange = 10; long expected = 2520; long maxValue = Challenge005.calculateMaxDivisableInRange(maxRange); long result = Challenge005.calculateMinDivisableInRange_BruteForce( maxRange, maxValue); assertEquals( "calculated divisable number does not equal the minimal divisable number", expected, result); } }
JayBur/euler
test/jaybur/euler/Challenge005Test.java
Java
mit
1,044
package org.lxp.redis.util; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import org.junit.Before; import org.junit.Test; import ai.grakn.redismock.RedisServer; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; /** * https://dzone.com/articles/java-redis-mock */ public class JedisUtilsTest { private RedisServer redisServer; private JedisPool jedisPool; @Before public void setUp() throws Exception { redisServer = RedisServer.newRedisServer(); redisServer.start(); jedisPool = new JedisPool(redisServer.getHost(), redisServer.getBindPort()); } /** * Unit test via redis-mock */ @Test public void testSetAndGetViaRedisMock() throws Exception { final String key = "11"; JedisUtils jedisUtils = new JedisUtils(jedisPool); assertEquals("OK", jedisUtils.set(key, "1")); assertEquals("1", jedisUtils.get(key)); } /** * Unit test via Mockito */ @Test public void testSetAndGetViaMockito() throws Exception { final String key = "11"; // given jedisPool = mock(JedisPool.class); Jedis jedis = mock(Jedis.class); doReturn(jedis).when(jedisPool).getResource(); doReturn("OK").when(jedis).set(eq(key), eq("1")); doReturn("1").when(jedis).get(eq(key)); // execute and verify JedisUtils jedisUtils = new JedisUtils(jedisPool); assertEquals("OK", jedisUtils.set(key, "1")); assertEquals("1", jedisUtils.get(key)); } }
hivsuper/study
study-parent/study-redis/src/test/java/org/lxp/redis/util/JedisUtilsTest.java
Java
mit
1,682
package com.unalsoft.elitefle.vo; /** * * @author Edward */ public class StudentVo extends UserVo implements IValueObject { private Integer idStudent; public Integer getIdStudent() { return idStudent; } public void setIdStudent(Integer idStudent) { this.idStudent = idStudent; } }
UnalSoft/elite-fle
src/main/java/com/unalsoft/elitefle/vo/StudentVo.java
Java
mit
341
package jpl.ch14.ex02; import java.awt.PrintJob; import java.util.Queue; public class PrintQueue { private Queue<PrintJob> queue; public void add(PrintJob job) { queue.add(job); } public PrintJob remove() { return queue.remove(); } }
ryoa912/java_training
src/jpl/ch14/ex02/PrintQueue.java
Java
mit
247
/* * 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 controle.DAO; import Dominio.Perfil; import java.io.Serializable; import javax.persistence.Query; import javax.persistence.EntityNotFoundException; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import Dominio.Pessoa; import controle.DAO.exceptions.NonexistentEntityException; import controle.DAO.exceptions.PreexistingEntityException; import controle.DAO.exceptions.RollbackFailureException; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; /** * * @author allan */ public class PerfilJpaController implements Serializable { public PerfilJpaController(EntityManagerFactory emf) { this.emf = emf; } private EntityManagerFactory emf = null; public EntityManager getEntityManager() { return emf.createEntityManager(); } public void create(Perfil perfil) throws RollbackFailureException, PreexistingEntityException{ EntityManager em = null; EntityTransaction utx = null; try { em = getEntityManager(); utx = em.getTransaction(); utx.begin(); em.persist(perfil); utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch (Exception re) { throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re); } if (findPerfil(perfil.getId()) != null) { throw new PreexistingEntityException("Perfil " + perfil + " already exists.", ex); } //throw ex; } finally { if (em != null) { em.close(); } } } public void edit(Perfil perfil) throws RollbackFailureException{ EntityManager em = null; EntityTransaction utx = null; try { em = getEntityManager(); utx = em.getTransaction(); utx.begin(); perfil = em.merge(perfil); utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch (Exception re) { throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re); } //throw ex; } finally { if (em != null) { em.close(); } } } public void destroy(Long id) throws RollbackFailureException{ EntityManager em = null; EntityTransaction utx = null; try { em = getEntityManager(); utx = em.getTransaction(); utx.begin(); Perfil perfil = em.getReference(Perfil.class, id); em.remove(perfil); utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch (Exception re) { throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re); } //throw ex; } finally { if (em != null) { em.close(); } } } public List<Perfil> findPerfilEntities() { return findPerfilEntities(true, -1, -1); } public List<Perfil> findPerfilEntities(int maxResults, int firstResult) { return findPerfilEntities(false, maxResults, firstResult); } private List<Perfil> findPerfilEntities(boolean all, int maxResults, int firstResult) { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(Perfil.class)); Query q = em.createQuery(cq); if (!all) { q.setMaxResults(maxResults); q.setFirstResult(firstResult); } return q.getResultList(); } finally { em.close(); } } public Perfil findPerfil(Long id) { EntityManager em = getEntityManager(); try { return em.find(Perfil.class, id); } finally { em.close(); } } public int getPerfilCount() { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); Root<Perfil> rt = cq.from(Perfil.class); cq.select(em.getCriteriaBuilder().count(rt)); Query q = em.createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } finally { em.close(); } } }
megallanpp/EcommerceAllanUbiraci
EcommerceAllan_Ubiraci/src/java/controle/DAO/PerfilJpaController.java
Java
mit
4,938
package guitests.guihandles; import guitests.GuiRobot; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.stage.Stage; import javafx.stage.Window; import seedu.address.TestApp; import seedu.address.commons.core.LogsCenter; import java.util.Optional; import java.util.logging.Logger; /** * Base class for all GUI Handles used in testing. */ public class GuiHandle { protected final GuiRobot guiRobot; protected final Stage primaryStage; /** * An optional stage that exists in the App other than the primaryStage, could be a alert dialog, popup window, etc. */ protected Optional<Stage> intermediateStage = Optional.empty(); protected final String stageTitle; private final Logger logger = LogsCenter.getLogger(this.getClass()); public GuiHandle(GuiRobot guiRobot, Stage primaryStage, String stageTitle) { this.guiRobot = guiRobot; this.primaryStage = primaryStage; this.stageTitle = stageTitle; focusOnSelf(); } public void focusOnWindow(String stageTitle) { logger.info("Focusing " + stageTitle); Optional<Window> window = guiRobot.listTargetWindows() .stream() .filter(w -> w instanceof Stage && ((Stage) w).getTitle().equals(stageTitle)).findAny(); if (!window.isPresent()) { logger.warning("Can't find stage " + stageTitle + ", Therefore, aborting focusing"); return; } intermediateStage = Optional.ofNullable((Stage) window.get()); guiRobot.targetWindow(window.get()); guiRobot.interact(() -> window.get().requestFocus()); logger.info("Finishing focus " + stageTitle); } protected <T extends Node> T getNode(String query) { return guiRobot.lookup(query).query(); } protected String getTextFieldText(String filedName) { TextField textField = getNode(filedName); return textField.getText(); } protected void setTextField(String textFieldId, String newText) { guiRobot.clickOn(textFieldId); TextField textField = getNode(textFieldId); textField.setText(newText); guiRobot.sleep(500); // so that the texts stays visible on the GUI for a short period } public void pressEnter() { guiRobot.type(KeyCode.ENTER).sleep(500); } protected String getTextFromLabel(String fieldId, Node parentNode) { return ((Label) guiRobot.from(parentNode).lookup(fieldId).tryQuery().get()).getText(); } public void focusOnSelf() { if (stageTitle != null) { focusOnWindow(stageTitle); } } public void focusOnMainApp() { this.focusOnWindow(TestApp.APP_TITLE); } public void closeWindow() { Optional<Window> window = guiRobot.listTargetWindows() .stream() .filter(w -> w instanceof Stage && ((Stage) w).getTitle().equals(stageTitle)).findAny(); if (!window.isPresent()) { return; } guiRobot.targetWindow(window.get()); guiRobot.interact(() -> ((Stage) window.get()).close()); focusOnMainApp(); } }
edmundmok/addressbook-level4
src/test/java/guitests/guihandles/GuiHandle.java
Java
mit
3,255
package nk.hiroshi.plusle.script.cmd; /* This file is part of Plusle Scripting Language * * Copyright (C) 2014-2015 Ryan Kerr * * Please refer to the MIT license */ /** * Contains methods that are required for getting information from "Command Type" objects * In all honesty, it's not really used for anything * @author Ryan Kerr * @since 06 January, 2015 */ interface Commander { /** @return The Object's Parent (for Functions) */ public Script getParent(); /** @return The given value */ public String getValue(); /** @return The set name */ public String getName(); /** @return Any commands from the script that are stored in that object */ public String[] getRunnable(); /** * Sets the value of a function * @param value new value of a function */ public void setValue(String value); }
shiro-nk/Plusle-Scripting-Language
Plusle_Scripting_Language/Root/nk/hiroshi/plusle/script/cmd/Commander.java
Java
mit
851
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.batchai.fluent; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.batchai.fluent.models.ClusterInner; import com.azure.resourcemanager.batchai.fluent.models.RemoteLoginInformationInner; import com.azure.resourcemanager.batchai.models.ClusterCreateParameters; import com.azure.resourcemanager.batchai.models.ClusterUpdateParameters; /** An instance of this class provides access to all the operations defined in ClustersClient. */ public interface ClustersClient { /** * Creates a Cluster in the given Workspace. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param parameters The parameters to provide for the Cluster creation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about a Cluster. */ @ServiceMethod(returns = ReturnType.SINGLE) SyncPoller<PollResult<ClusterInner>, ClusterInner> beginCreate( String resourceGroupName, String workspaceName, String clusterName, ClusterCreateParameters parameters); /** * Creates a Cluster in the given Workspace. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param parameters The parameters to provide for the Cluster creation. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about a Cluster. */ @ServiceMethod(returns = ReturnType.SINGLE) SyncPoller<PollResult<ClusterInner>, ClusterInner> beginCreate( String resourceGroupName, String workspaceName, String clusterName, ClusterCreateParameters parameters, Context context); /** * Creates a Cluster in the given Workspace. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param parameters The parameters to provide for the Cluster creation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about a Cluster. */ @ServiceMethod(returns = ReturnType.SINGLE) ClusterInner create( String resourceGroupName, String workspaceName, String clusterName, ClusterCreateParameters parameters); /** * Creates a Cluster in the given Workspace. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param parameters The parameters to provide for the Cluster creation. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about a Cluster. */ @ServiceMethod(returns = ReturnType.SINGLE) ClusterInner create( String resourceGroupName, String workspaceName, String clusterName, ClusterCreateParameters parameters, Context context); /** * Updates properties of a Cluster. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param parameters Additional parameters for cluster update. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about a Cluster. */ @ServiceMethod(returns = ReturnType.SINGLE) ClusterInner update( String resourceGroupName, String workspaceName, String clusterName, ClusterUpdateParameters parameters); /** * Updates properties of a Cluster. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param parameters Additional parameters for cluster update. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about a Cluster. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<ClusterInner> updateWithResponse( String resourceGroupName, String workspaceName, String clusterName, ClusterUpdateParameters parameters, Context context); /** * Deletes a Cluster. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) SyncPoller<PollResult<Void>, Void> beginDelete(String resourceGroupName, String workspaceName, String clusterName); /** * Deletes a Cluster. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) SyncPoller<PollResult<Void>, Void> beginDelete( String resourceGroupName, String workspaceName, String clusterName, Context context); /** * Deletes a Cluster. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceGroupName, String workspaceName, String clusterName); /** * Deletes a Cluster. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceGroupName, String workspaceName, String clusterName, Context context); /** * Gets information about a Cluster. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about a Cluster. */ @ServiceMethod(returns = ReturnType.SINGLE) ClusterInner get(String resourceGroupName, String workspaceName, String clusterName); /** * Gets information about a Cluster. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about a Cluster. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<ClusterInner> getWithResponse( String resourceGroupName, String workspaceName, String clusterName, Context context); /** * Get the IP address, port of all the compute nodes in the Cluster. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the IP address, port of all the compute nodes in the Cluster. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<RemoteLoginInformationInner> listRemoteLoginInformation( String resourceGroupName, String workspaceName, String clusterName); /** * Get the IP address, port of all the compute nodes in the Cluster. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param clusterName The name of the cluster within the specified resource group. Cluster names can only contain a * combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 * through 64 characters long. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the IP address, port of all the compute nodes in the Cluster. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<RemoteLoginInformationInner> listRemoteLoginInformation( String resourceGroupName, String workspaceName, String clusterName, Context context); /** * Gets information about Clusters associated with the given Workspace. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about Clusters associated with the given Workspace. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<ClusterInner> listByWorkspace(String resourceGroupName, String workspaceName); /** * Gets information about Clusters associated with the given Workspace. * * @param resourceGroupName Name of the resource group to which the resource belongs. * @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric * characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. * @param maxResults The maximum number of items to return in the response. A maximum of 1000 files can be returned. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about Clusters associated with the given Workspace. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<ClusterInner> listByWorkspace( String resourceGroupName, String workspaceName, Integer maxResults, Context context); }
Azure/azure-sdk-for-java
sdk/batchai/azure-resourcemanager-batchai/src/main/java/com/azure/resourcemanager/batchai/fluent/ClustersClient.java
Java
mit
20,819
/** * Copyright (c) 2015 Mark S. Kolich * http://mark.koli.ch * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package com.kolich.havalo.exceptions.authentication; import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED; import com.kolich.havalo.exceptions.HavaloException; public class AuthenticationException extends HavaloException { private static final long serialVersionUID = -3112819251217503077L; public AuthenticationException(String message, Exception cause) { super(SC_UNAUTHORIZED, message, cause); } public AuthenticationException(String message) { super(SC_UNAUTHORIZED, message); } public AuthenticationException(Exception cause) { super(SC_UNAUTHORIZED, cause); } }
markkolich/havalo-kvs
src/main/java/com/kolich/havalo/exceptions/authentication/AuthenticationException.java
Java
mit
1,760
package ae_fluids.proxy; public class ClientProxy extends CommonProxy { @Override public void registerRenderers() { } }
mhahn1976/AE-Fluids
source/ae_fluids/proxy/ClientProxy.java
Java
mit
128
package opencup.xiv.round3; import java.io.*; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class C { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); C() throws IOException { reader = new BufferedReader(new FileReader("input.txt")); writer = new PrintWriter(new FileWriter("output.txt")); } long[] readLongs() throws IOException { String[] s = reader.readLine().split(" "); long[] longs = new long[s.length]; for (int i = 0; i < longs.length; i++) { longs[i] = Long.parseLong(s[i]); } return longs; } int[] readInts() throws IOException { String[] s = reader.readLine().split(" "); int[] ints = new int[s.length]; for (int i = 0; i < ints.length; i++) { ints[i] = Integer.parseInt(s[i]); } return ints; } int[] tt; int tx = 0; int readInt() throws IOException { if (tt == null || tx >= tt.length) { tt = readInts(); tx = 0; } return tt[tx++]; } void solve() throws IOException { int w = readInt(); class Node { String name; List<Node> children = null; Node(String name, List<Node> children) { this.name = name; this.children = children; } } LinkedList<Node> path = new LinkedList<>(); Node root = null; while(true) { String s = reader.readLine(); if(s == null || "!".equals(s)) { break; } String name = s.contains(".") ? s.substring(s.indexOf('.') + 1) : s.substring(s.indexOf('-') + 1); boolean isDirectory = s.contains("-"); Node node = new Node(name, isDirectory ? new ArrayList<Node>() : null); if(path.isEmpty()) { root = node; } int level = 0; for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == '|') { level++; } } while(level != path.size()) { path.pollLast(); } path.peekLast().children.add(node); path.offerLast(node); } writer.close(); reader.close(); } public static void main(String[] args) throws IOException { new C().solve(); } }
MysterionRise/gd-team-dangerzone
src/main/java/opencup/xiv/round3/C.java
Java
mit
2,557
/** * */ package com.ctgi.google.problems; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; /** * @author Dany * */ /** *ALGORITHM :(list) *1. Declare a hashmap of string, list<String> *2. Iterate through the list. * *3. Foreach string str * sortedstring =sort(str) * if hmap contains(sortedstring) * hmap.get(sortedstring).add(str) * else * alist = new ArrayList<String> * alist.add(str) * hmap.put(sortedstring, alist) * */ public class GroupStringsByAnagrams { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ArrayList<String> strings = new ArrayList<String>(); strings.add("star"); strings.add("astr"); strings.add("car"); strings.add("rac"); strings.add("st"); new GroupStringsByAnagrams().groupStringsByAnagrams(strings); } public void groupStringsByAnagrams(ArrayList<String> list) { if(list == null) return; HashMap<String, ArrayList<String>> hMap = new HashMap<String, ArrayList<String>>(); String sortedString=""; ArrayList<String> aList; for(String str : list) { sortedString = sortString(str); //System.out.println("Orig: "+str+" Sorted : "+sortedString); if(hMap.containsKey(sortedString)) { hMap.get(sortedString).add(str); }else { aList = new ArrayList<String>(); aList.add(str); hMap.put(sortedString, aList); } } System.out.print("[ "); for(String s : hMap.keySet()) { aList = hMap.get(s); System.out.print("[ "); for(String st : aList) { System.out.print(st+" "); } System.out.print("]"); } System.out.print(" ]"); } public String sortString(String str) { if(str == null) return null; char[] cArr = new char[str.length()]; cArr = str.toCharArray(); Arrays.sort(cArr); return new String(cArr); } }
dineshappavoo/ctgi
src/com/ctgi/google/problems/GroupStringsByAnagrams.java
Java
mit
1,894
package net.violet.platform.api.actions.people; import java.util.Date; import java.util.HashMap; import java.util.Map; import net.violet.platform.api.actions.Action; import net.violet.platform.api.actions.ActionParam; import net.violet.platform.api.actions.ApiActionTestBase; import net.violet.platform.api.callers.APICaller; import net.violet.platform.api.callers.ApplicationAPICaller; import net.violet.platform.api.exceptions.APIException; import net.violet.platform.datamodel.Application; import net.violet.platform.datamodel.ApplicationCredentials; import net.violet.platform.datamodel.mock.ApplicationCredentialsMock; import net.violet.platform.datamodel.mock.ApplicationMock; import net.violet.platform.dataobjects.ApplicationCredentialsData; import net.violet.platform.dataobjects.UserData; import org.junit.Assert; import org.junit.Test; public class ManageTokenTest extends ApiActionTestBase { @Test public void getTokenTest() throws APIException { final UserData theUser = UserData.getData(getKowalskyUser()); theUser.generateToken(); final Application theApplication = new ApplicationMock(42, "My first application", theUser.getReference(), new Date()); final ApplicationCredentials cred = new ApplicationCredentialsMock("6992873d28d86925325dc52d15d6feec30bb2da5", "59e6060a53ab1be5", theApplication); final APICaller caller = new ApplicationAPICaller(ApplicationCredentialsData.getData(cred)); final Action theAction = new ManageToken(); final Map<String, Object> theParams = new HashMap<String, Object>(); theParams.put(ActionParam.SESSION_PARAM_KEY, generateSession(theUser, caller)); final ActionParam theActionParam = new ActionParam(caller, theParams); final Object theResult = theAction.processRequest(theActionParam); Assert.assertNotNull(theResult); Assert.assertEquals(String.valueOf(theUser.getToken()), theResult); } @Test public void getNonExistingTokenTest() throws APIException { final UserData theUser = UserData.getData(getKowalskyUser()); theUser.clearToken(); final Application theApplication = new ApplicationMock(42, "My first application", theUser.getReference(), new Date()); final ApplicationCredentials cred = new ApplicationCredentialsMock("6992873d28d86925325dc52d15d6feec30bb2da5", "59e6060a53ab1be5", theApplication); final APICaller caller = new ApplicationAPICaller(ApplicationCredentialsData.getData(cred)); final Action theAction = new ManageToken(); final Map<String, Object> theParams = new HashMap<String, Object>(); theParams.put(ActionParam.SESSION_PARAM_KEY, generateSession(theUser, caller)); final ActionParam theActionParam = new ActionParam(caller, theParams); final Object theResult = theAction.processRequest(theActionParam); Assert.assertNull(theResult); } @Test public void activateTokenTest() throws APIException { final UserData theUser = UserData.getData(getKowalskyUser()); theUser.clearToken(); final Application theApplication = new ApplicationMock(42, "My first application", theUser.getReference(), new Date()); final ApplicationCredentials cred = new ApplicationCredentialsMock("6992873d28d86925325dc52d15d6feec30bb2da5", "59e6060a53ab1be5", theApplication); final APICaller caller = new ApplicationAPICaller(ApplicationCredentialsData.getData(cred)); final Action theAction = new ManageToken(); final Map<String, Object> theParams = new HashMap<String, Object>(); theParams.put(ActionParam.SESSION_PARAM_KEY, generateSession(theUser, caller)); theParams.put("activate", true); final ActionParam theActionParam = new ActionParam(caller, theParams); final Object theResult = theAction.processRequest(theActionParam); Assert.assertNotNull(theResult); Assert.assertEquals(String.valueOf(theUser.getToken()), theResult); } @Test public void deactivateTokenTest() throws APIException { final UserData theUser = UserData.getData(getKowalskyUser()); theUser.generateToken(); final Application theApplication = new ApplicationMock(42, "My first application", theUser.getReference(), new Date()); final ApplicationCredentials cred = new ApplicationCredentialsMock("6992873d28d86925325dc52d15d6feec30bb2da5", "59e6060a53ab1be5", theApplication); final APICaller caller = new ApplicationAPICaller(ApplicationCredentialsData.getData(cred)); final Action theAction = new ManageToken(); final Map<String, Object> theParams = new HashMap<String, Object>(); theParams.put(ActionParam.SESSION_PARAM_KEY, generateSession(theUser, caller)); theParams.put("activate", false); final ActionParam theActionParam = new ActionParam(caller, theParams); final Object theResult = theAction.processRequest(theActionParam); Assert.assertNull(theResult); } }
sebastienhouzet/nabaztag-source-code
server/OS/test/net/violet/platform/api/actions/people/ManageTokenTest.java
Java
mit
4,733
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.conn; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.params.HttpParams; /** * A factory for creating new {@link ClientConnectionManager} instances. * * @since 4.0 * * @deprecated (4.3) replaced by {@link HttpClientConnectionManager}. */ @Deprecated public interface ClientConnectionManagerFactory { ClientConnectionManager newInstance( HttpParams params, SchemeRegistry schemeRegistry); }
byronka/xenos
lib/lib_src/httpcomponents_source/httpcomponents-client-4.4/httpclient/src/main/java-deprecated/org/apache/http/conn/ClientConnectionManagerFactory.java
Java
mit
1,663
package io.github.syncmc.murdersleuth; import io.github.syncmc.murdersleuth.listeners.ClientChatReceivedListener; import io.github.syncmc.murdersleuth.listeners.ClientTickListener; import io.github.syncmc.murdersleuth.listeners.GamePlayerListener; import io.github.syncmc.murdersleuth.listeners.KeyInputListener; import io.github.syncmc.murdersleuth.listeners.PreRenderPlayerListener; import io.github.syncmc.murdersleuth.render.GoldRenderFactory; import io.github.syncmc.murdersleuth.util.GameHelper; import io.github.syncmc.murdersleuth.util.KeybindHandler; import net.minecraft.entity.item.EntityItem; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; @Mod(modid = MurderSleuth.MODID, useMetadata = true, clientSideOnly = true) public class MurderSleuth { public static final String MODID = "murdersleuth"; @EventHandler public void preInit(final FMLPreInitializationEvent event) { GameHelper.init(); KeybindHandler.init(); RenderingRegistry.registerEntityRenderingHandler(EntityItem.class, new GoldRenderFactory()); } @EventHandler public void init(final FMLInitializationEvent event) { MinecraftForge.EVENT_BUS.register(new ClientChatReceivedListener()); MinecraftForge.EVENT_BUS.register(new ClientTickListener()); MinecraftForge.EVENT_BUS.register(new GamePlayerListener()); MinecraftForge.EVENT_BUS.register(new KeyInputListener()); MinecraftForge.EVENT_BUS.register(new PreRenderPlayerListener()); } }
SyncMC/MurderSleuth
src/main/java/io/github/syncmc/murdersleuth/MurderSleuth.java
Java
mit
1,813
package vendingmachine.money; /** * Created by bollsal on 2016. 11. 24.. */ public class Money1000 implements Money { public static final int WON = 1000; }
bollsal/pikicast-java-study
src/main/java/vendingmachine/money/Money1000.java
Java
mit
163
public class Sqrtx { public int mySqrt(int x){ if(x < 0) return -1; int left = 0, right = x, mid = 0; double multiple; //binary seach while(left <= right){ mid = left + (right - left) / 2; multiple = Math.pow(1.0 * mid, 2.0); if(multiple == x) return mid; else if(multiple > x) right = mid - 1; else left = mid + 1; } return right; } }
Winbobob/LeetCode
Sqrtx.java
Java
mit
380
package tranquvis.simplesmsremote; import android.content.Context; import java.io.IOException; import java.util.ArrayList; import java.util.List; import tranquvis.simplesmsremote.CommandManagement.Modules.Instances; import tranquvis.simplesmsremote.CommandManagement.Modules.Module; import tranquvis.simplesmsremote.Data.DataManager; import tranquvis.simplesmsremote.Data.LogEntry; import tranquvis.simplesmsremote.Data.ModuleSettingsData; import tranquvis.simplesmsremote.Data.ModuleUserData; import tranquvis.simplesmsremote.Data.PhoneAllowlistModuleUserData; import tranquvis.simplesmsremote.Data.UserData; import tranquvis.simplesmsremote.Data.UserSettings; public class TestDataManager implements DataManager { private final UserData userData = new UserData(new ArrayList<>(), new UserSettings()); private final List<LogEntry> log = new ArrayList<>(); @Override public UserData getUserData() { return userData; } @Override public List<LogEntry> getLog() { return log; } @Override public void addLogEntry(LogEntry logEntry, Context context) throws IOException { log.add(logEntry); } public void enableModule(Module module) { enableModule(module, null); } public void enableModule(Module module, ModuleSettingsData settings) { if(module.equals(Instances.GRANT_PHONE_REMOTELY)) { userData.addModule(new ModuleUserData(module.getId(), settings)); } else { userData.addModule(new PhoneAllowlistModuleUserData(module.getId(), null, settings)); } } public boolean isPhoneGranted(Module module, String phone) { PhoneAllowlistModuleUserData moduleUserData = (PhoneAllowlistModuleUserData) getModuleUserData(module); return moduleUserData.isPhoneGranted(phone); } @Override public void LoadUserData(Context context) throws IOException { } @Override public void SaveUserData(Context context) throws IOException { } @Override public void LoadLog(Context context) throws IOException { } }
tranquvis/SimpleSmsRemote
app/src/androidTest/java/tranquvis/simplesmsremote/TestDataManager.java
Java
mit
2,133
package br.ufmg.dcc.labsoft.java.jmove.methods; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.ForStatement; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SwitchCase; import org.eclipse.jdt.core.dom.SwitchStatement; import org.eclipse.jdt.core.dom.TryStatement; import br.ufmg.dcc.labsoft.java.jmove.ast.DeepDependencyVisitor; import br.ufmg.dcc.labsoft.java.jmove.basic.AllEntitiesMapping; import br.ufmg.dcc.labsoft.java.jmove.dependencies.AccessFieldDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.AccessMethodDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.AnnotateMethodDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.CreateMethodDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.DeclareLocalVariableDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.DeclareParameterDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.DeclareReturnDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.Dependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.SimpleNameDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.ThrowDependency; import br.ufmg.dcc.labsoft.java.jmove.util.DCLUtil; import br.ufmg.dcc.labsoft.java.jmove.utils.ClazzUtil; import br.ufmg.dcc.labsoft.java.jmove.utils.MoveMethod; import br.ufmg.dcc.labsoft.java.jmove.utils.PrintOutput; import br.ufmg.dcc.labsoft.java.jmove.utils.JMoveSignatures; public class AllMethods { private List<MethodJMove> allMethodsList; private int numberOfExcluded; private Map<Integer, IMethod> iMethodMapping; private Set<Integer> moveIspossible; private IProgressMonitor monitor; public AllMethods(List<DeepDependencyVisitor> allDeepDependency, IProgressMonitor monitor) throws JavaModelException { // TODO Auto-generated method stub this.numberOfExcluded = 0; this.allMethodsList = new ArrayList<MethodJMove>(); this.iMethodMapping = new HashMap<Integer, IMethod>(); this.moveIspossible = new HashSet<Integer>(); this.monitor = monitor; createMethodsDependeciesList(allDeepDependency); } private void createMethodsDependeciesList( List<DeepDependencyVisitor> allDeepDependency) throws JavaModelException { float i = 0; monitor.beginTask( "Creating Dependencies for selected Java Project (2/4)", (allDeepDependency.size())); for (DeepDependencyVisitor deep : allDeepDependency) { System.out.printf("Criando metodo %2.2" + "f %c \n", (100) * (++i / allDeepDependency.size()), '%'); // for (IMethod m : deep.getUnit().findPrimaryType().getMethods()) { // System.out.println("element " + m.getElementName() + " " // + m.getDeclaringType().getFullyQualifiedName()); // } // System.out.println(); monitor.worked(1); for (Dependency dep : deep.getDependencies()) { if (dep instanceof AccessMethodDependency) { AccessMethodDependency acDependency = (AccessMethodDependency) dep; // String method = dep.getClassNameA() + "." // + ((AccessMethodDependency) dep).getMethodNameA() // + "()"; String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), acDependency.getImethodA()); String methodB = JMoveSignatures.getMethodSignature( dep.getClassNameB(), acDependency.getImethodB()); // String methodB = dep.getClassNameB() + "." // + ((AccessMethodDependency) dep).getMethodNameB() // + "()"; List<String> dependeciesList = new ArrayList<String>(); if (!recursive(sourceClass, methodA, dependecyClass, methodB)) { dependeciesList.add(dependecyClass); dependeciesList.add(methodB); } // System.out.println(sourceClass + " " + methodA // + " classe que depednde e metodo " + dependecyClass // + " " + methodB); putIMethodInMapping(methodA, acDependency.getImethodA()); putIMethodInMapping(methodB, acDependency.getImethodB()); createMethod(methodA, sourceClass, dependeciesList, acDependency.getImethodA()); } else if (dep instanceof AccessFieldDependency) { AccessFieldDependency acFieldDependency = (AccessFieldDependency) dep; String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), acFieldDependency.getImethodA()); String field = JMoveSignatures.getFieldSignature( dep.getClassNameB(), acFieldDependency.getiVariableBinding()); // String method = dep.getClassNameA() + "." // + ((AccessFieldDependency) dep).getMethodName() // + "()"; String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); // String field = dep.getClassNameB() + "." // + ((AccessFieldDependency) dep).getFieldName(); List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); dependeciesList.add(field); putIMethodInMapping(methodA, acFieldDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, acFieldDependency.getImethodA()); } else if (dep instanceof SimpleNameDependency) { SimpleNameDependency snDependency = (SimpleNameDependency) dep; // String method = dep.getClassNameA() + "." // + ((SimpleNameDependency) dep).getMethodName() // + "()"; String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); // String field = dep.getClassNameB() + "." // + ((SimpleNameDependency) dep).getVariableName(); String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), snDependency.getImethodA()); String field = JMoveSignatures.getFieldSignature( dep.getClassNameB(), snDependency.getiVariableBinding()); List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); dependeciesList.add(field); putIMethodInMapping(methodA, snDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, snDependency.getImethodA()); } else if (dep instanceof AnnotateMethodDependency) { AnnotateMethodDependency anDependency = (AnnotateMethodDependency) dep; String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); // String method = dep.getClassNameA() + "." // + ((AnnotateMethodDependency) dep).getMethodName() // + "()"; String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), anDependency.getImethodA()); List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); putIMethodInMapping(methodA, anDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, anDependency.getImethodA()); } else if (dep instanceof CreateMethodDependency) { CreateMethodDependency cmDependency = (CreateMethodDependency) dep; String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), cmDependency.getImethodA()); // String method = dep.getClassNameA() + "." // + ((CreateMethodDependency) dep).getMethodNameA() // + "()"; List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); putIMethodInMapping(methodA, cmDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, cmDependency.getImethodA()); } else if (dep instanceof DeclareParameterDependency) { DeclareParameterDependency dpDependency = (DeclareParameterDependency) dep; // String method = dep.getClassNameA() // + "." // + ((DeclareParameterDependency) dep) // .getMethodName() + "()"; String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), dpDependency.getImethodA()); String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); // String field = dep.getClassNameB() + "." // + ((DeclareParameterDependency) dep).getFieldName(); List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); // dependeciesList.add(field); putIMethodInMapping(methodA, dpDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, dpDependency.getImethodA()); } else if (dep instanceof DeclareReturnDependency) { DeclareReturnDependency drDependency = (DeclareReturnDependency) dep; String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), drDependency.getImethodA()); String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); // String method = dep.getClassNameA() + "." // + ((DeclareReturnDependency) dep).getMethodName() // + "()"; List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); putIMethodInMapping(methodA, drDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, drDependency.getImethodA()); } else if (dep instanceof DeclareLocalVariableDependency) { DeclareLocalVariableDependency dlvDependency = (DeclareLocalVariableDependency) dep; String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), dlvDependency.getImethodA()); // String method = dep.getClassNameA() // + "." // + ((DeclareLocalVariableDependency) dep) // .getMethodName() + "()"; String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); // String field = dep.getClassNameB() // + "." // + ((DeclareLocalVariableDependency) dep) // .getFieldName(); List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); // System.out.println("DeclareLocalVariableDependency"); // System.out.println(dependecyClass); // System.out.println(method); // System.out.println(field); // dependeciesList.add(field); putIMethodInMapping(methodA, dlvDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, dlvDependency.getImethodA()); } else if (dep instanceof ThrowDependency) { ThrowDependency throwDependency = (ThrowDependency) dep; String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), throwDependency.getImethodA()); String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); // String method = dep.getClassNameA() + "." // + ((ThrowDependency) dep).getMethodName() + "()"; List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); putIMethodInMapping(methodA, throwDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, throwDependency.getImethodA()); } } if (monitor != null && monitor.isCanceled()) { if (monitor != null) monitor.done(); throw new OperationCanceledException(); } } // // #............ Imprime dependencias Iterator<MethodJMove> it = allMethodsList.iterator(); while (it.hasNext()) { MethodJMove m = it.next(); PrintOutput.write( AllEntitiesMapping.getInstance().getByID(m.getNameID()) + "\n", "conjuntos"); for (Integer chaves : m.getMethodsDependencies()) { PrintOutput .write(AllEntitiesMapping.getInstance().getByID(chaves) + "\n", "conjuntos"); } PrintOutput.write("\n \n", "conjuntos"); } // #............ } private boolean recursive(String sourceClass, String methodA, String dependecyClass, String methodB) { // TODO Auto-generated method stub if (sourceClass.equals(dependecyClass) && methodA.equals(methodB)) { return true; } return false; } private void createMethod(String methodName, String sourceClass, List<String> dependeciesList, IMethod iMethod) { // TODO Auto-generated method stub int methodId = AllEntitiesMapping.getInstance().createEntityID( methodName); int sourceClassID = AllEntitiesMapping.getInstance().createEntityID( sourceClass); // System.out.println("Aki primeiro "+ sourceClass); MethodJMove method2 = new MethodJMove(methodId, sourceClassID); if (allMethodsList.contains(method2)) { method2 = allMethodsList.get(allMethodsList.indexOf(method2)); method2.setNewMethodsDependencies(dependeciesList); } else { // List<String> moveReachable = MoveMethod // .getpossibleRefactoring(getIMethod(method2)); if (this.getIMethod(method2) != null && MoveMethod.IsRefactoringPossible(this .getIMethod(method2))) { moveIspossible.add(methodId); } allMethodsList.add(method2); method2.setNewMethodsDependencies(dependeciesList); } } private void putIMethodInMapping(String methodName, IMethod iMethod) { // TODO Auto-generated method stub int methodId; methodId = AllEntitiesMapping.getInstance().createEntityID(methodName); iMethodMapping.put(methodId, iMethod); } public IMethod getIMethod(MethodJMove method) { // TODO Auto-generated method stub return iMethodMapping.get(method.getNameID()); } public List<MethodJMove> getAllMethodsList() { return allMethodsList; } public MethodJMove getMethodByID(int methodID) { for (MethodJMove method : allMethodsList) { if (methodID == method.getNameID()) return method; } return null; } public int getNumberOfExcluded() { return numberOfExcluded; } private void setNumberOfExcluded(int numberOfExcluded) { this.numberOfExcluded = numberOfExcluded; } public Set<Integer> getMoveIspossible() { return moveIspossible; } public void excludeDependeciesLessThan(int Numdepedencies) { List<MethodJMove> smallMethod = new ArrayList<MethodJMove>(); if (Numdepedencies > getNumberOfExcluded()) { setNumberOfExcluded(Numdepedencies); for (MethodJMove method : allMethodsList) { if (method.getMethodsDependencies().size() < Numdepedencies) { smallMethod.add(method); } } allMethodsList.removeAll(smallMethod); } } public void excludeConstructors() { Iterator<Entry<Integer, IMethod>> it = iMethodMapping.entrySet() .iterator(); while (it.hasNext()) { Entry<Integer, IMethod> entry = it.next(); IMethod method = entry.getValue(); try { if (method != null && method.isConstructor()) { MethodJMove methodTemp = getMethodByID(entry.getKey()); int index = allMethodsList.indexOf(methodTemp); allMethodsList.remove(index); } } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
aserg-ufmg/jmove
src/src/br/ufmg/dcc/labsoft/java/jmove/methods/AllMethods.java
Java
mit
16,018
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.synapse.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.synapse.models.IntegrationRuntimeAutoUpdate; import com.azure.resourcemanager.synapse.models.IntegrationRuntimeInternalChannelEncryptionMode; import com.azure.resourcemanager.synapse.models.LinkedIntegrationRuntime; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; import java.util.List; import java.util.Map; /** Self-hosted integration runtime status type properties. */ @Fluent public final class SelfHostedIntegrationRuntimeStatusTypeProperties { @JsonIgnore private final ClientLogger logger = new ClientLogger(SelfHostedIntegrationRuntimeStatusTypeProperties.class); /* * The time at which the integration runtime was created, in ISO8601 * format. */ @JsonProperty(value = "createTime", access = JsonProperty.Access.WRITE_ONLY) private OffsetDateTime createTime; /* * The task queue id of the integration runtime. */ @JsonProperty(value = "taskQueueId", access = JsonProperty.Access.WRITE_ONLY) private String taskQueueId; /* * The node communication Channel encryption mode */ @JsonProperty(value = "nodeCommunicationChannelEncryptionMode", access = JsonProperty.Access.WRITE_ONLY) private String nodeCommunicationChannelEncryptionMode; /* * It is used to set the encryption mode for node-node communication * channel (when more than 2 self-hosted integration runtime nodes exist). */ @JsonProperty(value = "internalChannelEncryption", access = JsonProperty.Access.WRITE_ONLY) private IntegrationRuntimeInternalChannelEncryptionMode internalChannelEncryption; /* * Version of the integration runtime. */ @JsonProperty(value = "version", access = JsonProperty.Access.WRITE_ONLY) private String version; /* * The list of nodes for this integration runtime. */ @JsonProperty(value = "nodes") private List<SelfHostedIntegrationRuntimeNodeInner> nodes; /* * The date at which the integration runtime will be scheduled to update, * in ISO8601 format. */ @JsonProperty(value = "scheduledUpdateDate", access = JsonProperty.Access.WRITE_ONLY) private OffsetDateTime scheduledUpdateDate; /* * The time in the date scheduled by service to update the integration * runtime, e.g., PT03H is 3 hours */ @JsonProperty(value = "updateDelayOffset", access = JsonProperty.Access.WRITE_ONLY) private String updateDelayOffset; /* * The local time zone offset in hours. */ @JsonProperty(value = "localTimeZoneOffset", access = JsonProperty.Access.WRITE_ONLY) private String localTimeZoneOffset; /* * Object with additional information about integration runtime * capabilities. */ @JsonProperty(value = "capabilities", access = JsonProperty.Access.WRITE_ONLY) @JsonInclude(value = JsonInclude.Include.NON_NULL, content = JsonInclude.Include.ALWAYS) private Map<String, String> capabilities; /* * The URLs for the services used in integration runtime backend service. */ @JsonProperty(value = "serviceUrls", access = JsonProperty.Access.WRITE_ONLY) private List<String> serviceUrls; /* * Whether Self-hosted integration runtime auto update has been turned on. */ @JsonProperty(value = "autoUpdate", access = JsonProperty.Access.WRITE_ONLY) private IntegrationRuntimeAutoUpdate autoUpdate; /* * Status of the integration runtime version. */ @JsonProperty(value = "versionStatus", access = JsonProperty.Access.WRITE_ONLY) private String versionStatus; /* * The list of linked integration runtimes that are created to share with * this integration runtime. */ @JsonProperty(value = "links") private List<LinkedIntegrationRuntime> links; /* * The version that the integration runtime is going to update to. */ @JsonProperty(value = "pushedVersion", access = JsonProperty.Access.WRITE_ONLY) private String pushedVersion; /* * The latest version on download center. */ @JsonProperty(value = "latestVersion", access = JsonProperty.Access.WRITE_ONLY) private String latestVersion; /* * The estimated time when the self-hosted integration runtime will be * updated. */ @JsonProperty(value = "autoUpdateETA", access = JsonProperty.Access.WRITE_ONLY) private OffsetDateTime autoUpdateEta; /* * The service region of the integration runtime */ @JsonProperty(value = "serviceRegion") private String serviceRegion; /* * The newer versions on download center. */ @JsonProperty(value = "newerVersions") private List<String> newerVersions; /** * Get the createTime property: The time at which the integration runtime was created, in ISO8601 format. * * @return the createTime value. */ public OffsetDateTime createTime() { return this.createTime; } /** * Get the taskQueueId property: The task queue id of the integration runtime. * * @return the taskQueueId value. */ public String taskQueueId() { return this.taskQueueId; } /** * Get the nodeCommunicationChannelEncryptionMode property: The node communication Channel encryption mode. * * @return the nodeCommunicationChannelEncryptionMode value. */ public String nodeCommunicationChannelEncryptionMode() { return this.nodeCommunicationChannelEncryptionMode; } /** * Get the internalChannelEncryption property: It is used to set the encryption mode for node-node communication * channel (when more than 2 self-hosted integration runtime nodes exist). * * @return the internalChannelEncryption value. */ public IntegrationRuntimeInternalChannelEncryptionMode internalChannelEncryption() { return this.internalChannelEncryption; } /** * Get the version property: Version of the integration runtime. * * @return the version value. */ public String version() { return this.version; } /** * Get the nodes property: The list of nodes for this integration runtime. * * @return the nodes value. */ public List<SelfHostedIntegrationRuntimeNodeInner> nodes() { return this.nodes; } /** * Set the nodes property: The list of nodes for this integration runtime. * * @param nodes the nodes value to set. * @return the SelfHostedIntegrationRuntimeStatusTypeProperties object itself. */ public SelfHostedIntegrationRuntimeStatusTypeProperties withNodes( List<SelfHostedIntegrationRuntimeNodeInner> nodes) { this.nodes = nodes; return this; } /** * Get the scheduledUpdateDate property: The date at which the integration runtime will be scheduled to update, in * ISO8601 format. * * @return the scheduledUpdateDate value. */ public OffsetDateTime scheduledUpdateDate() { return this.scheduledUpdateDate; } /** * Get the updateDelayOffset property: The time in the date scheduled by service to update the integration runtime, * e.g., PT03H is 3 hours. * * @return the updateDelayOffset value. */ public String updateDelayOffset() { return this.updateDelayOffset; } /** * Get the localTimeZoneOffset property: The local time zone offset in hours. * * @return the localTimeZoneOffset value. */ public String localTimeZoneOffset() { return this.localTimeZoneOffset; } /** * Get the capabilities property: Object with additional information about integration runtime capabilities. * * @return the capabilities value. */ public Map<String, String> capabilities() { return this.capabilities; } /** * Get the serviceUrls property: The URLs for the services used in integration runtime backend service. * * @return the serviceUrls value. */ public List<String> serviceUrls() { return this.serviceUrls; } /** * Get the autoUpdate property: Whether Self-hosted integration runtime auto update has been turned on. * * @return the autoUpdate value. */ public IntegrationRuntimeAutoUpdate autoUpdate() { return this.autoUpdate; } /** * Get the versionStatus property: Status of the integration runtime version. * * @return the versionStatus value. */ public String versionStatus() { return this.versionStatus; } /** * Get the links property: The list of linked integration runtimes that are created to share with this integration * runtime. * * @return the links value. */ public List<LinkedIntegrationRuntime> links() { return this.links; } /** * Set the links property: The list of linked integration runtimes that are created to share with this integration * runtime. * * @param links the links value to set. * @return the SelfHostedIntegrationRuntimeStatusTypeProperties object itself. */ public SelfHostedIntegrationRuntimeStatusTypeProperties withLinks(List<LinkedIntegrationRuntime> links) { this.links = links; return this; } /** * Get the pushedVersion property: The version that the integration runtime is going to update to. * * @return the pushedVersion value. */ public String pushedVersion() { return this.pushedVersion; } /** * Get the latestVersion property: The latest version on download center. * * @return the latestVersion value. */ public String latestVersion() { return this.latestVersion; } /** * Get the autoUpdateEta property: The estimated time when the self-hosted integration runtime will be updated. * * @return the autoUpdateEta value. */ public OffsetDateTime autoUpdateEta() { return this.autoUpdateEta; } /** * Get the serviceRegion property: The service region of the integration runtime. * * @return the serviceRegion value. */ public String serviceRegion() { return this.serviceRegion; } /** * Set the serviceRegion property: The service region of the integration runtime. * * @param serviceRegion the serviceRegion value to set. * @return the SelfHostedIntegrationRuntimeStatusTypeProperties object itself. */ public SelfHostedIntegrationRuntimeStatusTypeProperties withServiceRegion(String serviceRegion) { this.serviceRegion = serviceRegion; return this; } /** * Get the newerVersions property: The newer versions on download center. * * @return the newerVersions value. */ public List<String> newerVersions() { return this.newerVersions; } /** * Set the newerVersions property: The newer versions on download center. * * @param newerVersions the newerVersions value to set. * @return the SelfHostedIntegrationRuntimeStatusTypeProperties object itself. */ public SelfHostedIntegrationRuntimeStatusTypeProperties withNewerVersions(List<String> newerVersions) { this.newerVersions = newerVersions; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (nodes() != null) { nodes().forEach(e -> e.validate()); } if (links() != null) { links().forEach(e -> e.validate()); } } }
Azure/azure-sdk-for-java
sdk/synapse/azure-resourcemanager-synapse/src/main/java/com/azure/resourcemanager/synapse/fluent/models/SelfHostedIntegrationRuntimeStatusTypeProperties.java
Java
mit
12,180
package com.ernestomancebo.ds_algorightms.datastructures.linkedlist; import com.ernestomancebo.ds_algorightms.datastructures.linkedlist.node.Node; public class DoublyEndedLinkedList { private Node headNode; private Node tailNode; public Node getHead() { return headNode; } public Node deleteFromHead() { Node returnNode = headNode; if (headNode != null) { headNode = headNode.getNextNode(); } return returnNode; } public void insertAtTail(Node newNode) { // If there's no head, the new node is the head if (headNode == null) { headNode = newNode; } // If there's a tail already, then make it a regular node if (tailNode != null) { tailNode.setNextNode(newNode); } // Either there's a tail or not, the new node is the new tail tailNode = newNode; } public int length() { int length = 0; Node currentNode = headNode; while (currentNode != null) { length++; currentNode = currentNode.getNextNode(); } return length; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("{ "); Node currentNode = headNode; while (currentNode != null) { stringBuilder.append("data: "); stringBuilder.append(currentNode.getData()); currentNode = currentNode.getNextNode(); if (currentNode != null) { stringBuilder.append(", "); } } stringBuilder.append(" }"); return stringBuilder.toString(); } }
ernestomancebo/datastructure_alrogithms
src/main/java/com/ernestomancebo/ds_algorightms/datastructures/linkedlist/DoublyEndedLinkedList.java
Java
mit
1,451
package com.example.yetti.toneplayer.database; import android.provider.BaseColumns; import com.example.yetti.toneplayer.model.Artist; import static com.example.yetti.toneplayer.database.DBToneContract.Database.COMMA_SEP; import static com.example.yetti.toneplayer.database.DBToneContract.Database.INTEGER_TYPE; import static com.example.yetti.toneplayer.database.DBToneContract.Database.TEXT_TYPE; public final class DBToneContract { public interface Database { int DATABASE_VERSION = 1; String DATABASE_NAME = "tone.db"; String TEXT_TYPE = " TEXT"; String INTEGER_TYPE = " INTEGER"; String COMMA_SEP = ","; } private DBToneContract() { } public interface ArtistEntry extends BaseColumns{ String TABLE_NAME ="artists"; String COLUMN_NAME_ARTIST_NAME="artist_name"; String COLUMN_NAME_ARTIST_SONG_COUNT="artist_song_count"; String COLUMN_NAME_ARTIST_GENRE="artist_genre"; String COLUMN_NAME_ARTIST_ARTWORKURL="artist_artwork_url"; String SQL_CREATE_ENTRIES = "CREATE TABLE " + ArtistEntry.TABLE_NAME + " (" + ArtistEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + ArtistEntry.COLUMN_NAME_ARTIST_NAME + TEXT_TYPE + COMMA_SEP + ArtistEntry.COLUMN_NAME_ARTIST_SONG_COUNT + INTEGER_TYPE + COMMA_SEP + ArtistEntry.COLUMN_NAME_ARTIST_GENRE + TEXT_TYPE + COMMA_SEP + ArtistEntry.COLUMN_NAME_ARTIST_ARTWORKURL + TEXT_TYPE + " )"; String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + SongEntry.TABLE_NAME; } public interface SongEntry extends BaseColumns { String TABLE_NAME = "songs"; String COLUMN_NAME_ENTRY_ID = "song_id"; String COLUMN_NAME_SONG_TITLE = "song_title"; String COLUMN_NAME_SONG_ARTIST = "song_artist"; String COLUMN_NAME_SONG_ALBUM = "song_album"; String COLUMN_NAME_SONG_ALBUM_ID = "song_album_id"; String COLUMN_NAME_SONG_WEIGHT = "song_weight"; String COLUMN_NAME_SONG_PLAYLIST = "song_playlist"; String COLUMN_NAME_SONG_FAVOURITE = "song_favourite"; String COLUMN_NAME_SONG_DURATION = "song_duration"; String SQL_CREATE_ENTRIES = "CREATE TABLE " + SongEntry.TABLE_NAME + " (" + SongEntry._ID + " INTEGER PRIMARY KEY," + SongEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP + SongEntry.COLUMN_NAME_SONG_TITLE + TEXT_TYPE + COMMA_SEP + SongEntry.COLUMN_NAME_SONG_ARTIST + TEXT_TYPE + COMMA_SEP + SongEntry.COLUMN_NAME_SONG_ALBUM + TEXT_TYPE + COMMA_SEP + SongEntry.COLUMN_NAME_SONG_ALBUM_ID + INTEGER_TYPE + COMMA_SEP + SongEntry.COLUMN_NAME_SONG_WEIGHT + INTEGER_TYPE + COMMA_SEP + SongEntry.COLUMN_NAME_SONG_PLAYLIST + INTEGER_TYPE + COMMA_SEP + SongEntry.COLUMN_NAME_SONG_FAVOURITE + INTEGER_TYPE + COMMA_SEP + SongEntry.COLUMN_NAME_SONG_DURATION + INTEGER_TYPE + " )"; String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + SongEntry.TABLE_NAME; } public interface PlaylistEntry extends BaseColumns { String TABLE_NAME = "playlist"; String COLUMN_NAME_ENTRY_ID = "playlist_id"; String COLUMN_NAME_PLAYLIST_NAME = "playlist_name"; String SQL_CREATE_ENTRIES = "CREATE TABLE " + PlaylistEntry.TABLE_NAME + " (" + PlaylistEntry._ID + " INTEGER PRIMARY KEY," + PlaylistEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP + PlaylistEntry.COLUMN_NAME_PLAYLIST_NAME + TEXT_TYPE + " )"; String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + PlaylistEntry.TABLE_NAME; } public interface SQLTemplates { String SQL_SELECT_WHERE = "SELECT %s FROM %s WHERE %s" + "='" + "%s" + "'"; ; String SQL_DISTINCT = "SELECT DISTINCT %s FROM %s"; } }
kitaisreal/ToneApp
app/src/main/java/com/example/yetti/toneplayer/database/DBToneContract.java
Java
mit
4,198
package graphql.relay; import graphql.PublicApi; /** * Represents an edge in Relay which is essentially a node of data T and the cursor for that node. * * See <a href="https://facebook.github.io/relay/graphql/connections.htm#sec-Edge-Types">https://facebook.github.io/relay/graphql/connections.htm#sec-Edge-Types</a> */ @PublicApi public interface Edge<T> { /** * @return the node of data that this edge represents */ T getNode(); /** * @return the cursor for this edge node */ ConnectionCursor getCursor(); }
graphql-java/graphql-java
src/main/java/graphql/relay/Edge.java
Java
mit
555
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.datalakestore.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.JsonFlatten; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** The parameters used to create a new firewall rule. */ @JsonFlatten @Fluent public class CreateOrUpdateFirewallRuleParameters { @JsonIgnore private final ClientLogger logger = new ClientLogger(CreateOrUpdateFirewallRuleParameters.class); /* * The start IP address for the firewall rule. This can be either ipv4 or * ipv6. Start and End should be in the same protocol. */ @JsonProperty(value = "properties.startIpAddress", required = true) private String startIpAddress; /* * The end IP address for the firewall rule. This can be either ipv4 or * ipv6. Start and End should be in the same protocol. */ @JsonProperty(value = "properties.endIpAddress", required = true) private String endIpAddress; /** * Get the startIpAddress property: The start IP address for the firewall rule. This can be either ipv4 or ipv6. * Start and End should be in the same protocol. * * @return the startIpAddress value. */ public String startIpAddress() { return this.startIpAddress; } /** * Set the startIpAddress property: The start IP address for the firewall rule. This can be either ipv4 or ipv6. * Start and End should be in the same protocol. * * @param startIpAddress the startIpAddress value to set. * @return the CreateOrUpdateFirewallRuleParameters object itself. */ public CreateOrUpdateFirewallRuleParameters withStartIpAddress(String startIpAddress) { this.startIpAddress = startIpAddress; return this; } /** * Get the endIpAddress property: The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start * and End should be in the same protocol. * * @return the endIpAddress value. */ public String endIpAddress() { return this.endIpAddress; } /** * Set the endIpAddress property: The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start * and End should be in the same protocol. * * @param endIpAddress the endIpAddress value to set. * @return the CreateOrUpdateFirewallRuleParameters object itself. */ public CreateOrUpdateFirewallRuleParameters withEndIpAddress(String endIpAddress) { this.endIpAddress = endIpAddress; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (startIpAddress() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property startIpAddress in model CreateOrUpdateFirewallRuleParameters")); } if (endIpAddress() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property endIpAddress in model CreateOrUpdateFirewallRuleParameters")); } } }
Azure/azure-sdk-for-java
sdk/datalakestore/azure-resourcemanager-datalakestore/src/main/java/com/azure/resourcemanager/datalakestore/models/CreateOrUpdateFirewallRuleParameters.java
Java
mit
3,525
package net.danielmaly.scheme.builtin.io; import com.oracle.truffle.api.dsl.GenerateNodeFactory; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.NodeInfo; import net.danielmaly.scheme.builtin.BuiltinExpression; @NodeInfo(shortName = "display") @GenerateNodeFactory public abstract class Display extends BuiltinExpression { @Specialization public long display(long value) { System.out.print(value); return value; } @Specialization public double display(double value) { System.out.print(value); return value; } @Specialization public boolean display(boolean value) { System.out.print(value); return value; } @Specialization public Object display(Object value) { System.out.print(value); return value; } }
DanielMaly/scheme-truffle
src/main/java/net/danielmaly/scheme/builtin/io/Display.java
Java
mit
859
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.analytics.synapse.artifacts.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.JsonFlatten; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** The MongoDB database dataset. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonTypeName("MongoDbCollection") @JsonFlatten @Fluent public class MongoDbCollectionDataset extends Dataset { /* * The table name of the MongoDB database. Type: string (or Expression with * resultType string). */ @JsonProperty(value = "typeProperties.collectionName", required = true) private Object collectionName; /** * Get the collectionName property: The table name of the MongoDB database. Type: string (or Expression with * resultType string). * * @return the collectionName value. */ public Object getCollectionName() { return this.collectionName; } /** * Set the collectionName property: The table name of the MongoDB database. Type: string (or Expression with * resultType string). * * @param collectionName the collectionName value to set. * @return the MongoDbCollectionDataset object itself. */ public MongoDbCollectionDataset setCollectionName(Object collectionName) { this.collectionName = collectionName; return this; } }
Azure/azure-sdk-for-java
sdk/synapse/azure-analytics-synapse-artifacts/src/main/java/com/azure/analytics/synapse/artifacts/models/MongoDbCollectionDataset.java
Java
mit
1,667
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.ai.textanalytics.lro; import com.azure.ai.textanalytics.TextAnalyticsAsyncClient; import com.azure.ai.textanalytics.TextAnalyticsClientBuilder; import com.azure.ai.textanalytics.models.AnalyzeActionsOperationDetail; import com.azure.ai.textanalytics.models.AnalyzeActionsOptions; import com.azure.ai.textanalytics.models.AnalyzeActionsResult; import com.azure.ai.textanalytics.models.ExtractSummaryAction; import com.azure.ai.textanalytics.models.ExtractSummaryActionResult; import com.azure.ai.textanalytics.models.ExtractSummaryResult; import com.azure.ai.textanalytics.models.SummarySentence; import com.azure.ai.textanalytics.models.SummarySentencesOrder; import com.azure.ai.textanalytics.models.TextAnalyticsActions; import com.azure.core.credential.AzureKeyCredential; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; /** * Sample demonstrates how to asynchronously execute an "Extractive Summarization" action in a batch of documents, */ public class AnalyzeExtractiveSummarizationAsync { /** * Main method to invoke this demo about how to analyze an "Extractive Summarization" action. * * @param args Unused arguments to the program. */ public static void main(String[] args) { TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildAsyncClient(); List<String> documents = new ArrayList<>(); documents.add( "At Microsoft, we have been on a quest to advance AI beyond existing techniques, by taking a more holistic," + " human-centric approach to learning and understanding. As Chief Technology Officer of Azure AI" + " Cognitive Services, I have been working with a team of amazing scientists and engineers to turn " + "this quest into a reality. In my role, I enjoy a unique perspective in viewing the relationship" + " among three attributes of human cognition: monolingual text (X), audio or visual sensory signals," + " (Y) and multilingual (Z). At the intersection of all three, there’s magic—what we call XYZ-code" + " as illustrated in Figure 1—a joint representation to create more powerful AI that can speak, hear," + " see, and understand humans better. We believe XYZ-code will enable us to fulfill our long-term" + " vision: cross-domain transfer learning, spanning modalities and languages. The goal is to have" + " pretrained models that can jointly learn representations to support a broad range of downstream" + " AI tasks, much in the way humans do today. Over the past five years, we have achieved human" + " performance on benchmarks in conversational speech recognition, machine translation, " + "conversational question answering, machine reading comprehension, and image captioning. These" + " five breakthroughs provided us with strong signals toward our more ambitious aspiration to" + " produce a leap in AI capabilities, achieving multisensory and multilingual learning that " + "is closer in line with how humans learn and understand. I believe the joint XYZ-code is a " + "foundational component of this aspiration, if grounded with external knowledge sources in " + "the downstream AI tasks."); client.beginAnalyzeActions(documents, new TextAnalyticsActions() .setDisplayName("{tasks_display_name}") .setExtractSummaryActions( new ExtractSummaryAction() .setMaxSentenceCount(4) .setOrderBy(SummarySentencesOrder.RANK)), "en", new AnalyzeActionsOptions()) .flatMap(result -> { AnalyzeActionsOperationDetail operationDetail = result.getValue(); System.out.printf("Action display name: %s, Successfully completed actions: %d, in-process actions: %d," + " failed actions: %d, total actions: %d%n", operationDetail.getDisplayName(), operationDetail.getSucceededCount(), operationDetail.getInProgressCount(), operationDetail.getFailedCount(), operationDetail.getTotalCount()); return result.getFinalResult(); }) .flatMap(pagedFlux -> pagedFlux) // this unwrap the Mono<> of Mono<PagedFlux<T>> to return PagedFlux<T> .subscribe( actionsResult -> processAnalyzeActionsResult(actionsResult), ex -> System.out.println("Error listing pages: " + ex.getMessage()), () -> System.out.println("Successfully listed all pages")); // The .subscribe() creation and assignment is not a blocking call. For the purpose of this example, we sleep // the thread so the program does not end before the send operation is complete. Using .block() instead of // .subscribe() will turn this into a synchronous call. try { TimeUnit.MINUTES.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } private static void processAnalyzeActionsResult(AnalyzeActionsResult actionsResult) { System.out.println("Extractive Summarization action results:"); for (ExtractSummaryActionResult actionResult : actionsResult.getExtractSummaryResults()) { if (!actionResult.isError()) { for (ExtractSummaryResult documentResult : actionResult.getDocumentsResults()) { if (!documentResult.isError()) { System.out.println("\tExtracted summary sentences:"); for (SummarySentence summarySentence : documentResult.getSentences()) { System.out.printf( "\t\t Sentence text: %s, length: %d, offset: %d, rank score: %f.%n", summarySentence.getText(), summarySentence.getLength(), summarySentence.getOffset(), summarySentence.getRankScore()); } } else { System.out.printf("\tCannot extract summary sentences. Error: %s%n", documentResult.getError().getMessage()); } } } else { System.out.printf("\tCannot execute Extractive Summarization action. Error: %s%n", actionResult.getError().getMessage()); } } } }
Azure/azure-sdk-for-java
sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/lro/AnalyzeExtractiveSummarizationAsync.java
Java
mit
7,036
package util.IntArray2DToImageConverter.src; /** * Util for determining array width and height. Assumes a rectangular array. Performs null checks. * * @author Ruslan * */ public class Int2DArraySizes { /** * Performs null checks, returns 0 if null * * @param 2D (int[][]) intArray * @return (int) width */ public static int width2DIntArray(int[][] intArray) { if (intArray != null) { int[] firstRow = intArray[0]; return firstRow.length; } return 0; } /** * Performs null checks, returns 0 if null * * @param 2D (int[][]) intArray * @return (int) height */ public static int height2DIntArray(int[][] intArray) { if (intArray != null) { return intArray.length; } return 0; } }
calliem/voogasalad_ProtectedTower
src/util/IntArray2DToImageConverter/src/Int2DArraySizes.java
Java
mit
1,081
/* * The MIT License (MIT) * Copyright © 2013 Englishtown <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the “Software”), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.englishtown.vertx.metrics.integration; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.englishtown.vertx.metrics.Utils; import io.vertx.core.AbstractVerticle; import io.vertx.core.Verticle; import io.vertx.test.core.VertxTestBase; import org.junit.Test; import java.util.Map; import java.util.SortedMap; /** * Metrics integration tests */ public class BasicIntegrationTest extends VertxTestBase { @Test public void testVertxEventLoopGauges() throws Exception { MetricRegistry registry = new MetricRegistry(); Verticle verticle = new AbstractVerticle() { }; verticle.init(vertx, vertx.context()); Utils.create(verticle, registry, false); SortedMap<String, Gauge> results = registry.getGauges((name, metric) -> name.contains("VertxEventLoopGauges")); assertTrue(results.size() > 0); for (Map.Entry<String, Gauge> entry : results.entrySet()) { assertEquals(0, entry.getValue().getValue()); } testComplete(); } }
englishtown/vertx-metrics
ext-metrics/src/test/java/com/englishtown/vertx/metrics/integration/BasicIntegrationTest.java
Java
mit
2,257
package eu.securibox.cloudagents.api.banks.beans; /** * The Enum SynchronizationState. */ public enum SynchronizationState { /** New account. */ NewAccount, /** Created. */ Created, /** Running. */ Running, /** Login failed. */ LoginFailed, /** Completed. */ Completed, /** Completed with errors. */ CompletedWithErrors, /** Check account. */ CheckAccount, /** Service unavailable. */ ServiceUnavailable, /** Logging in. */ LoggingIn, /** Running but login failed. */ RunningButLoginFailed, /** Delivery failed. */ DeliveryFailed, /** The web site in maintenance */ WebsiteInMaintenance, /** A reset password warning is being displayed. */ ResetPasswordWarning, /** The user must reset the password. */ ResetPasswordRequired, /** There's s personal notification requiring an action by the user. */ UserActionNeeded }
Securibox/sca-docs-sdk-for-java
src/main/java/eu/securibox/cloudagents/api/banks/beans/SynchronizationState.java
Java
mit
880
package com.complexitylabs.gando.supersummon.commands; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import com.complexitylabs.gando.supersummon.SuperSummon; public class SummonDelete implements CommandExecutor { private SuperSummon plugin; public SummonDelete(SuperSummon instance) { this.plugin = instance; } @Override public boolean onCommand(CommandSender sender, Command command, String commandName, String[] args) { if(args.length == 1) { plugin.getConfig().set("config.summonlocations." + args[0], null); sender.sendMessage("SuperSummon location " + ChatColor.DARK_RED + args[0] + ChatColor.RESET + " + has been deleted successfully!"); return true; } // TODO Auto-generated method stub return false; } }
skyhighwings/SuperSummon
SuperSummon/src/com/complexitylabs/gando/supersummon/commands/SummonDelete.java
Java
mit
884
//- Copyright © 2008-2011 8th Light, Inc. All Rights Reserved. //- Limelight and all included source files are distributed under terms of the MIT License. package limelight.ui.events.panel; import limelight.ui.MockPanel; import org.junit.Test; import static junit.framework.Assert.assertEquals; public class ButtonPushedEventTest { @Test public void isNotInheritable() throws Exception { final ButtonPushedEvent event = new ButtonPushedEvent(); assertEquals(false, event.isInheritable()); } }
slagyr/limelight
test/limelight/ui/events/panel/ButtonPushedEventTest.java
Java
mit
514
package org.oauthsimple.builder.api; import org.oauthsimple.model.OAuthToken; public class VimeoApi extends DefaultApi10a { private static final String AUTHORIZATION_URL = "http://vimeo.com/oauth/authorize?oauth_token=%s"; @Override public String getAccessTokenEndpoint() { return "http://vimeo.com/oauth/access_token"; } @Override public String getRequestTokenEndpoint() { return "http://vimeo.com/oauth/request_token"; } @Override public String getAuthorizationUrl(OAuthToken requestToken) { return String.format(AUTHORIZATION_URL, requestToken.getToken()); } }
mcxiaoke/oauth-simple
src/main/java/org/oauthsimple/builder/api/VimeoApi.java
Java
mit
585
package edu.asu.scrapbook.digital.api; import org.glassfish.jersey.server.ResourceConfig; public class AppConfig extends ResourceConfig { public AppConfig() { register(UserResource.class); register(ImageResource.class); } }
mcmathews/CSE-360-Digital-Scrapbook
src/edu/asu/scrapbook/digital/api/AppConfig.java
Java
mit
248
/* * Xero oAuth 2 identity service * This specifing endpoints related to managing authentication tokens and identity for Xero API * * The version of the OpenAPI document: 2.2.4 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.xero.models.identity; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; import com.xero.api.StringUtil; /** RefreshToken */ public class RefreshToken { StringUtil util = new StringUtil(); @JsonProperty("grant_type") private String grantType; @JsonProperty("refresh_token") private String refreshToken; @JsonProperty("client_id") private String clientId; @JsonProperty("client_secret") private String clientSecret; public RefreshToken grantType(String grantType) { this.grantType = grantType; return this; } /** * Xero grant type * * @return grantType */ @ApiModelProperty(value = "Xero grant type") public String getGrantType() { return grantType; } public void setGrantType(String grantType) { this.grantType = grantType; } public RefreshToken refreshToken(String refreshToken) { this.refreshToken = refreshToken; return this; } /** * refresh token provided during authentication flow * * @return refreshToken */ @ApiModelProperty(value = "refresh token provided during authentication flow") public String getRefreshToken() { return refreshToken; } public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } public RefreshToken clientId(String clientId) { this.clientId = clientId; return this; } /** * client id for Xero app * * @return clientId */ @ApiModelProperty(value = "client id for Xero app") public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public RefreshToken clientSecret(String clientSecret) { this.clientSecret = clientSecret; return this; } /** * client secret for Xero app 2 * * @return clientSecret */ @ApiModelProperty(value = "client secret for Xero app 2") public String getClientSecret() { return clientSecret; } public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RefreshToken refreshToken = (RefreshToken) o; return Objects.equals(this.grantType, refreshToken.grantType) && Objects.equals(this.refreshToken, refreshToken.refreshToken) && Objects.equals(this.clientId, refreshToken.clientId) && Objects.equals(this.clientSecret, refreshToken.clientSecret); } @Override public int hashCode() { return Objects.hash(grantType, refreshToken, clientId, clientSecret); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class RefreshToken {\n"); sb.append(" grantType: ").append(toIndentedString(grantType)).append("\n"); sb.append(" refreshToken: ").append(toIndentedString(refreshToken)).append("\n"); sb.append(" clientId: ").append(toIndentedString(clientId)).append("\n"); sb.append(" clientSecret: ").append(toIndentedString(clientSecret)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
SidneyAllen/Xero-Java
src/main/java/com/xero/models/identity/RefreshToken.java
Java
mit
3,920
package xlet.android.libraries.network.apirxwrapper; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.CompositeException; import io.reactivex.exceptions.Exceptions; import io.reactivex.plugins.RxJavaPlugins; import retrofit2.Call; import retrofit2.HttpException; import retrofit2.Response; /** * Synchronously send the request by {@link Call#execute()} and return its response * * @see Call * @see retrofit2.adapter.rxjava2.CallExecuteObservable * @see retrofit2.adapter.rxjava2.BodyObservable */ final class ExecuteCallObservable<T> extends Observable<T> { private final Call<T> originalCall; ExecuteCallObservable(Call<T> originalCall) { this.originalCall = originalCall; } @Override protected void subscribeActual(Observer<? super T> observer) { // Since Call is a one-shot type, clone it for each new observer. Call<T> call = originalCall.clone(); observer.onSubscribe(new CallDisposable(call)); boolean terminated = false; try { Response<T> response = call.execute(); if (!call.isCanceled()) { if (response.isSuccessful()) { observer.onNext(response.body()); } else { terminated = true; Throwable t = new HttpException(response); try { observer.onError(t); } catch (Throwable inner) { Exceptions.throwIfFatal(inner); RxJavaPlugins.onError(new CompositeException(t, inner)); } } } if (!call.isCanceled()) { terminated = true; observer.onComplete(); } } catch (Throwable t) { Exceptions.throwIfFatal(t); if (terminated) { RxJavaPlugins.onError(t); } else if (!call.isCanceled()) { try { observer.onError(t); } catch (Throwable inner) { Exceptions.throwIfFatal(inner); RxJavaPlugins.onError(new CompositeException(t, inner)); } } } } private static final class CallDisposable implements Disposable { private final Call<?> call; CallDisposable(Call<?> call) { this.call = call; } @Override public void dispose() { call.cancel(); } @Override public boolean isDisposed() { return call.isCanceled(); } } }
cwhsiaoo/ApiRxWrapper
src/main/java/xlet/android/libraries/network/apirxwrapper/ExecuteCallObservable.java
Java
mit
2,715
package com.openatk.field_work.trello; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.preference.PreferenceManager; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.util.SparseArray; import com.openatk.field_work.MainActivity; import com.openatk.field_work.db.DatabaseHelper; import com.openatk.field_work.db.TableFields; import com.openatk.field_work.db.TableJobs; import com.openatk.field_work.db.TableOperations; import com.openatk.field_work.db.TableWorkers; import com.openatk.field_work.models.Field; import com.openatk.field_work.models.Job; import com.openatk.field_work.models.Operation; import com.openatk.field_work.models.Worker; import com.openatk.libtrello.TrelloBoard; import com.openatk.libtrello.TrelloCard; import com.openatk.libtrello.TrelloContentProvider; import com.openatk.libtrello.TrelloList; public class MyTrelloContentProvider extends TrelloContentProvider { private DatabaseHelper dbHelper; private TrelloHelper trelloHelper; public MyTrelloContentProvider(){ } //Custom implemented in every app @Override public List<TrelloCard> getCards(String boardTrelloId){ dbHelper = new DatabaseHelper(getContext()); trelloHelper = new TrelloHelper(getContext()); Log.d("MyTrelloContentProvider", "getCards()"); //Return all custom data as cards List<TrelloCard> cards = new ArrayList<TrelloCard>(); //Get all operators, set list id equal to "Settings - Operator List" trello id List<Worker> workers = DatabaseHelper.readWorkers(dbHelper); for(int i=0; i<workers.size(); i++){ cards.add(trelloHelper.toTrelloCard(workers.get(i))); } Log.d("MyTrelloContentProvider - getCards", "# Workers:" + Integer.toString(workers.size())); //Get all fields, set list id equal to "Settings - Field List" trello id List<Field> fields = DatabaseHelper.readFields(dbHelper); for(int i=0; i<fields.size(); i++){ cards.add(trelloHelper.toTrelloCard(fields.get(i))); } Log.d("MyTrelloContentProvider - getCards", "# Fields:" + Integer.toString(fields.size())); //Get all jobs, set list id equal to operation trello id List<Operation> operations = DatabaseHelper.readOperations(dbHelper); //Create hashmap SparseArray<String> map = new SparseArray<String>(operations.size()); for(int i=0; i<operations.size(); i++){ map.put(operations.get(i).getId(), operations.get(i).getRemote_id()); } List<Job> jobs = DatabaseHelper.readJobs(dbHelper); for(int i=0; i<jobs.size(); i++){ cards.add(trelloHelper.toTrelloCard(jobs.get(i), map.get(jobs.get(i).getOperationId()))); } Log.d("MyTrelloContentProvider - getCards", "# Jobs:" + Integer.toString(jobs.size())); Log.d("MyTrelloContentProvider - getCards", "# Cards:" + Integer.toString(cards.size())); dbHelper.close(); return cards; } @Override public TrelloCard getCard(String id){ //TODO I think this is unused by current version of Trello return null; } //Custom implemented in every app @Override public List<TrelloList> getLists(String boardTrelloId){ dbHelper = new DatabaseHelper(getContext()); trelloHelper = new TrelloHelper(getContext()); Log.d("MyTrelloContentProvider", "getLists()"); //Return all custom data as TrelloLists //RockApp has 2 default lists, and a list for each operation List<TrelloList> lists = new ArrayList<TrelloList>(); SharedPreferences prefs = this.getContext().getSharedPreferences("com.openatk.field_work", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); TrelloList listWorkers = new TrelloList(); if(prefs.contains("listWorkersLocalId")){ listWorkers.setLocalId(prefs.getString("listWorkersLocalId", "Fields")); listWorkers.setId(prefs.getString("listWorkersTrelloId", "")); listWorkers.setName(prefs.getString("listWorkersName", "")); listWorkers.setName_changed(TrelloContentProvider.stringToDate(prefs.getString("listWorkersName_change", ""))); listWorkers.setClosed(false); listWorkers.setClosed_changed(TrelloContentProvider.stringToDate(prefs.getString("listWorkersClosed_change", ""))); listWorkers.setBoardId(prefs.getString("boardTrelloId", "")); } else { Date theDate = new Date(); //TODO from Internet String workerLocalId = "workers"; String workerTrelloId = ""; String workerName = "Settings - Operator List"; String changeDate = TrelloContentProvider.dateToUnixString(theDate); SharedPreferences.Editor editor = prefs.edit(); editor.putString("listWorkersLocalId", workerLocalId); editor.putString("listWorkersTrelloId", workerTrelloId); editor.putString("listWorkersName", workerName); editor.putString("listWorkersName_change", changeDate); editor.putString("listWorkersClosed_change", changeDate); editor.commit(); listWorkers.setLocalId(workerLocalId); listWorkers.setId(workerTrelloId); listWorkers.setName(workerName); listWorkers.setName_changed(theDate); listWorkers.setClosed(false); listWorkers.setClosed_changed(theDate); listWorkers.setBoardId(prefs.getString("boardTrelloId", "")); } lists.add(listWorkers); TrelloList listFields = new TrelloList(); if(prefs.contains("listFieldsLocalId")){ listFields.setLocalId(prefs.getString("listFieldsLocalId", "0")); listFields.setId(prefs.getString("listFieldsTrelloId", "")); listFields.setName(prefs.getString("listFieldsName", "")); listFields.setName_changed(TrelloContentProvider.stringToDate(prefs.getString("listFieldsName_change", ""))); listFields.setClosed_changed(TrelloContentProvider.stringToDate(prefs.getString("listFieldsClosed_change", ""))); listFields.setBoardId(prefs.getString("boardTrelloId", "")); } else { Date theDate = new Date(); //TODO from Internet String dateChange = TrelloContentProvider.dateToUnixString(theDate); String fieldLocalId = "fields"; String fieldTrelloId = ""; String fieldName = "Settings - Field List"; SharedPreferences.Editor editor = prefs.edit(); editor.putString("listFieldsLocalId", fieldLocalId); editor.putString("listFieldsTrelloId", fieldTrelloId); editor.putString("listFieldsName", fieldName); editor.putString("listFieldsName_change", dateChange); editor.putString("listFieldsClosed_change", dateChange); editor.commit(); listFields.setLocalId(fieldLocalId); listFields.setId(fieldTrelloId); listFields.setName(fieldName); listFields.setName_changed(theDate); listFields.setClosed(false); listFields.setClosed_changed(theDate); listFields.setBoardId(prefs.getString("boardTrelloId", "")); } lists.add(listFields); //Add a list for each operation List<Operation> operations = DatabaseHelper.readOperations(dbHelper); for(int i=0; i<operations.size(); i++){ lists.add(this.trelloHelper.toTrelloList(operations.get(i))); } return lists; } //Custom implemented in every app @Override public List<TrelloBoard> getBoards(){ Log.d("MyTrelloContentProvider", "getBoards()"); //Return all custom data as boards, always return boards //FieldWork has 1 board List<TrelloBoard> boards = new ArrayList<TrelloBoard>(); SharedPreferences prefs = this.getContext().getSharedPreferences("com.openatk.field_work", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); TrelloBoard trelloBoard = new TrelloBoard(); if(prefs.contains("boardLocalId")){ Log.d("MyTrelloContentProvider", "Has local id, giving current local board"); Log.d("MyTrelloContentProvider", "Its trelloId:" + prefs.getString("boardTrelloId", "")); trelloBoard.setLocalId(prefs.getString("boardLocalId", "0")); trelloBoard.setId(prefs.getString("boardTrelloId", "")); trelloBoard.setName(prefs.getString("boardName", "")); trelloBoard.setName_changed(TrelloContentProvider.stringToDate(prefs.getString("boardName_change", ""))); trelloBoard.setDesc(prefs.getString("boardDesc", "")); trelloBoard.setDesc_changed(TrelloContentProvider.stringToDate(prefs.getString("boardDesc_change", ""))); trelloBoard.setClosed(false); trelloBoard.setClosed_changed(TrelloContentProvider.stringToDate(prefs.getString("boardClosed_change", ""))); trelloBoard.setOrganizationId(prefs.getString("boardOrganizationId", "")); trelloBoard.setOrganizationId_changed(TrelloContentProvider.stringToDate(prefs.getString("boardOrganizationId_change", ""))); trelloBoard.setLastSyncDate(prefs.getString("boardSyncDate", "")); trelloBoard.setLastTrelloActionDate(prefs.getString("boardTrelloActionDate", "")); } else { Log.d("MyTrelloContentProvider", "No local id, creating new local board"); Date theDate = new Date(); String localId = "0"; String trelloId = ""; String name = "OpenATK - Field Work App"; String dateChange = TrelloContentProvider.dateToUnixString(theDate); SharedPreferences.Editor editor = prefs.edit(); editor.putString("boardLocalId", localId); editor.putString("boardTrelloId", trelloId); editor.putString("boardName", name); editor.putString("boardName_change", dateChange); editor.putString("boardDesc", ""); editor.putString("boardDesc_change", dateChange); editor.putString("boardClosed_change", dateChange); editor.putString("boardOrganizationId", ""); //We don't know the organization id till it's on trello editor.putString("boardOrganizationId_change", dateChange); editor.putString("boardSyncDate", TrelloContentProvider.dateToUnixString(new Date(0))); editor.putString("boardTrelloActionDate", TrelloContentProvider.dateToUnixString(new Date(0))); editor.commit(); trelloBoard.setLocalId(localId); trelloBoard.setId(trelloId); trelloBoard.setName(name); trelloBoard.setName_changed(theDate); } boards.add(trelloBoard); return boards; } @Override public int updateCard(TrelloCard tcard){ dbHelper = new DatabaseHelper(getContext()); trelloHelper = new TrelloHelper(getContext()); //Update a card Log.d("MyTrelloContentProvider - updateCard", "updating card local id:" + tcard.getSource().getLocalId()); Log.d("MyTrelloContentProvider - updateCard", "updating card trello id:" + tcard.getId()); //First check list id of source to see what type it used to be int typeField = 0; int typeWorker = 1; int typeJob = 2; int oldType = 0; SharedPreferences prefs = this.getContext().getSharedPreferences("com.openatk.field_work", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); String listWorkersTrelloId = prefs.getString("listWorkersTrelloId", ""); String listFieldsTrelloId = prefs.getString("listFieldsTrelloId", ""); if(tcard.getSource().getListId() != null){ if(tcard.getSource().getListId().contentEquals(listWorkersTrelloId)){ Log.d("MyTrelloContentProvider getType", "was a worker"); oldType = typeWorker; } else if(tcard.getSource().getListId().contentEquals(listFieldsTrelloId)){ Log.d("MyTrelloContentProvider getType", "was a field"); oldType = typeField; } else { Log.d("MyTrelloContentProvider getType", "was a job"); oldType = typeJob; } } //Now see what type it is now int newType = 0; if(tcard.getListId() != null){ //Possible type change if(tcard.getListId().contentEquals(listWorkersTrelloId)){ Log.d("MyTrelloContentProvider getType", "is a worker"); newType = typeWorker; } else if(tcard.getListId().contentEquals(listFieldsTrelloId)){ Log.d("MyTrelloContentProvider getType", "is a field"); newType = typeField; } else { Log.d("MyTrelloContentProvider getType", "is a job"); newType = typeJob; } Log.w("MyTrelloContentProvider", "Update card, Card has a list id"); } else { //No listid, then it didn't change newType = oldType; } //Was a worker if(oldType == typeWorker){ if(newType != typeWorker){ //This card used to be a worker but now isn't, delete it Worker worker = trelloHelper.toWorker(tcard.getSource()); TableWorkers.deleteWorker(dbHelper, worker); Intent toSend = new Intent(MainActivity.INTENT_WORKER_DELETED); toSend.putExtra("id", worker.getId()); toSend.putExtra("workerName", worker.getName()); LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } else { //Same type so we know the local id tcard.setLocalId(tcard.getSource().getLocalId()); } } //Was a field if(oldType == typeField){ if(newType != typeField){ //This card used to be a worker but now isn't, delete it Field field = trelloHelper.toField(tcard.getSource()); TableFields.deleteField(dbHelper, field); Intent toSend = new Intent(MainActivity.INTENT_FIELD_DELETED); toSend.putExtra("id", field.getId()); LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } else { //Same type so we know the local id tcard.setLocalId(tcard.getSource().getLocalId()); } } //Was a job if(oldType == typeJob){ if(newType != typeJob){ //This card used to be a worker but now isn't, delete it Job job = trelloHelper.toJob(tcard.getSource()); TableJobs.deleteJob(dbHelper, job); Intent toSend = new Intent(MainActivity.INTENT_JOB_DELETED); toSend.putExtra("id", job.getId()); toSend.putExtra("fieldName", job.getFieldName()); Log.d("FieldName", "Fieldname:" + job.getFieldName()); LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } else { //Same type so we know the local id tcard.setLocalId(tcard.getSource().getLocalId()); } } //Is a worker if(newType == typeWorker){ //Try to convert new card to worker Worker worker = trelloHelper.toWorker(tcard); if(worker != null){ if(worker.getDeleted() != null && worker.getDeleted()){ if(newType == oldType){ //Worker is now deleted, remove it Worker oldWorker = trelloHelper.toWorker(tcard.getSource()); TableWorkers.deleteWorker(dbHelper, worker); Intent toSend = new Intent(MainActivity.INTENT_WORKER_DELETED); toSend.putExtra("id", worker.getId()); toSend.putExtra("workerName", oldWorker.getName()); LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } } else { //Update in the database accordingly Log.d("MyTrelloContentProvider", "update worker"); Boolean updated = TableWorkers.updateWorker(dbHelper, worker); if(updated){ Intent toSend = new Intent(MainActivity.INTENT_WORKER_UPDATED); toSend.putExtra("id", worker.getId()); //No need to pass name since its an update and not a delete LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } } } } //Is a field if(newType == typeField){ //Try to convert new card to field Field field = trelloHelper.toField(tcard); if(field != null){ if(field.getDeleted() != null && field.getDeleted()){ if(newType == oldType){ //field is now deleted, remove it TableFields.deleteField(dbHelper, field); Intent toSend = new Intent(MainActivity.INTENT_FIELD_DELETED); toSend.putExtra("id", field.getId()); LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } } else { //Update in the database accordingly Log.d("MyTrelloContentProvider", "update field"); Boolean updated = TableFields.updateField(dbHelper, field); if(updated){ Intent toSend = new Intent(MainActivity.INTENT_FIELD_UPDATED); toSend.putExtra("id", field.getId()); LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } } } } //Is a job if(newType == typeJob){ //Try to convert new card to job Job job = trelloHelper.toJob(tcard); if(job != null){ if(job.getDeleted() != null && job.getDeleted() == true){ if(newType == oldType){ Job oldJob = trelloHelper.toJob(tcard.getSource()); //Worker is now deleted, remove it TableJobs.deleteJob(dbHelper, job); Intent toSend = new Intent(MainActivity.INTENT_JOB_DELETED); toSend.putExtra("fieldName", oldJob.getFieldName()); toSend.putExtra("id", job.getId()); LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } } else { //Update in the database accordingly //Get operation if operation changed, this isn't handled in toJob TODO?... Integer oldOperationId = -1; if(tcard.getListId() != null){ Operation operation = TableOperations.FindOperationByTrelloId(dbHelper, tcard.getListId()); if(operation != null){ job.setOperationId(operation.getId()); job.setDateOperationIdChanged(tcard.getListId_changed()); //Save old operation id to pass to mainactivity to update field views oldOperationId = TableJobs.FindJobById(dbHelper, job.getId()).getOperationId(); } else { //If operation is null it's not on a operation list, should never happen Log.w("MyTrellContentProvider - updateCard", "Job doesn't have a valid operation id"); Log.w("MyTrellContentProvider - updateCard", "Job listid:" + tcard.getListId()); } } Log.d("MyTrelloContentProvider", "update job"); Boolean updated = TableJobs.updateJob(dbHelper, job); if(updated){ Intent toSend = new Intent(MainActivity.INTENT_JOB_UPDATED); //If field name changed we need to update old field if(job.getFieldName() != null) { //Field name changed, we need to pass this so we can update the status of the old field String oldFieldName = trelloHelper.toJob(tcard.getSource()).getFieldName(); if(oldFieldName != null) toSend.putExtra("oldFieldName", oldFieldName); } //If operation id changed we need to update the field status if(job.getOperationId() != null) { //Field name changed, we need to pass this so we can update the status of the old field if(oldOperationId != null && oldOperationId != job.getOperationId()){ toSend.putExtra("oldOperationId", oldOperationId); } else { Log.d("MyTrelloContent", "Old operation id null"); } } else { Log.d("MyTrelloContent", "new operation id null"); } toSend.putExtra("id", job.getId()); LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } } } } //Notify the activity TODO, switch to job by job or whatever //LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(new Intent(MainActivity.INTENT_JOBS_UPDATED)); return 1; } @Override public int updateList(TrelloList tlist){ dbHelper = new DatabaseHelper(getContext()); trelloHelper = new TrelloHelper(getContext()); Log.d("MyTrelloContentProvider", "updateList()"); SharedPreferences prefs = this.getContext().getSharedPreferences("com.openatk.field_work", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); String listWorkersTrelloId = prefs.getString("listWorkersTrelloId", ""); String listFieldsTrelloId = prefs.getString("listFieldsTrelloId", ""); String listWorkersId = prefs.getString("listWorkersLocalId", ""); String listFieldsId = prefs.getString("listFieldsLocalId", ""); String boardId = prefs.getString("boardTrelloId", ""); //Update our 2 static lists, notice these id's are different than operations Boolean isFieldList = false; Boolean isWorkerList = false; if(tlist.getSource() != null){ if(tlist.getSource().getLocalId().contentEquals(listFieldsId)){ isFieldList = true; } else if(tlist.getSource().getLocalId().contentEquals(listWorkersId)){ isWorkerList = true; } } if(tlist.getId() != null){ if(tlist.getId().contentEquals(listFieldsTrelloId)){ isFieldList = true; } else if(tlist.getId().contentEquals(listWorkersTrelloId)){ isWorkerList = true; } } if(isFieldList){ //Update field list accordingly SharedPreferences.Editor editor = prefs.edit(); boolean deleted = false; if(tlist.getClosed() != null && tlist.getClosed()) deleted = true; if(tlist.getBoardId() != null && tlist.getBoardId().contentEquals(boardId) == false) deleted = true; if(tlist.getId() != null) editor.putString("listFieldsTrelloId", tlist.getId()); if(tlist.getName() != null && tlist.getName().contentEquals(prefs.getString("listFieldsName", "")) == false) deleted = true; if(deleted){ //Remove this so fieldlist will be recreated editor.remove("listFieldsLocalId"); //Delete all the fields in the db TableFields.deleteAll(dbHelper); Intent toSend = new Intent(MainActivity.INTENT_ALL_FIELDS_DELETED); LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } editor.commit(); } if(isWorkerList){ //Update worker list accordingly SharedPreferences.Editor editor = prefs.edit(); boolean deleted = false; if(tlist.getClosed() != null && tlist.getClosed()) deleted = true; if(tlist.getBoardId() != null && tlist.getBoardId().contentEquals(boardId) == false) deleted = true; if(tlist.getId() != null) editor.putString("listWorkersTrelloId", tlist.getId()); if(tlist.getName() != null && tlist.getName().contentEquals(prefs.getString("listWorkersName", "")) == false) deleted = true; if(deleted){ //Remove this so fieldlist will be recreated editor.remove("listWorkersLocalId"); //Delete all the workers in the db TableWorkers.deleteAll(dbHelper); Intent toSend = new Intent(MainActivity.INTENT_ALL_WORKERS_DELETED); LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } editor.commit(); } if(isWorkerList == false && isFieldList == false){ //Update the other lists (Operations), if it is one of them, just call update if its not it will handle it //Update necessary info Operation toUpdate = new Operation(); Boolean deleted = false; toUpdate.setId(Integer.parseInt(tlist.getSource().getLocalId())); if(tlist.getClosed() != null) deleted = tlist.getClosed(); if(tlist.getId() != null) toUpdate.setRemote_id(tlist.getId()); if(tlist.getName() != null) toUpdate.setName(tlist.getName()); if(tlist.getName_changed() != null) toUpdate.setDateNameChanged(tlist.getName_changed()); if(tlist.getBoardId() != null && tlist.getBoardId().contentEquals(boardId) == false) deleted = true; if(deleted != null && deleted == true){ //Delete all jobs with this operation TableJobs.deleteAllWithOperationId(dbHelper, toUpdate.getId()); //Delete the operation TableOperations.deleteOperation(dbHelper, toUpdate); Intent toSend = new Intent(MainActivity.INTENT_OPERATION_DELETED); toSend.putExtra("id", toUpdate.getId()); LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } else { TableOperations.updateOperation(dbHelper, toUpdate); Intent toSend = new Intent(MainActivity.INTENT_OPERATION_UPDATED); toSend.putExtra("id", toUpdate.getId()); LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } } return 1; } @Override public int updateOrganization(String oldOrganizationId, String newOrganizationId){ dbHelper = new DatabaseHelper(getContext()); trelloHelper = new TrelloHelper(getContext()); Log.d("MyTrelloContentProvider", "updateOrganization()"); Log.d("MyTrelloContentProvider", "updateOrganization old:" + oldOrganizationId + " new:" + newOrganizationId); //Organization has changed, delete everything SharedPreferences prefs = this.getContext().getSharedPreferences("com.openatk.field_work", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); SharedPreferences.Editor editor = prefs.edit(); //Delete boards editor.remove("boardLocalId"); //Will cause it to be remade //Delete lists (Fields, Workers, Operations) editor.remove("listFieldsLocalId"); //Will cause it to be remade editor.remove("listWorkersLocalId"); //Will cause it to be remade editor.commit(); TableOperations.deleteAll(dbHelper); //Delete cards (Workers, Fields, and Jobs) TableWorkers.deleteAll(dbHelper); TableFields.deleteAll(dbHelper); TableJobs.deleteAll(dbHelper); if(prefs.getInt(MainActivity.PREF_GONE, MainActivity.PREF_GONE_NO_UPDATE) == MainActivity.PREF_GONE_NO_UPDATE){ //MainActivity is away, tell it that there has been an update editor = prefs.edit(); editor.putInt(MainActivity.PREF_GONE, MainActivity.PREF_GONE_UPDATE); editor.commit(); Log.d("MyTreloContentProvider", "MainActivity is gone, set update."); } else { Log.d("MyTreloContentProvider", "MainActivity is present."); } //Tell MainActivity if it is around that this is an update LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(new Intent(MainActivity.INTENT_EVERYTHING_DELETED)); return 0; } @Override public int updateBoard(TrelloBoard tBoard){ Log.d("MyTrelloContentProvider", "updateBoard()"); SharedPreferences prefs = this.getContext().getSharedPreferences("com.openatk.field_work", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); Boolean isIt = false; if(tBoard.getSource() != null){ if(tBoard.getSource().getLocalId().contentEquals(prefs.getString("boardLocalId", "something"))){ isIt = true; } } else if(tBoard.getId() != null){ if(tBoard.getId().contentEquals(prefs.getString("boardTrelloId", "something"))){ isIt = true; } } if(isIt){ Boolean delete = false; SharedPreferences.Editor editor = prefs.edit(); if(tBoard.getId() != null && tBoard.getId().contentEquals(prefs.getString("boardTrelloId", "something")) == false){ editor.putString("boardTrelloId", tBoard.getId()); Log.d("MyTrelloContentProvider", "updateBoard new trello id:" + tBoard.getId()); } //Name if(tBoard.getName() != null) { if(tBoard.getName().contentEquals(prefs.getString("boardName", "")) == false){ delete = true; } editor.putString("boardName_change", TrelloContentProvider.dateToUnixString(tBoard.getName_changed())); } //Desc if(tBoard.getDesc() != null){ editor.putString("boardDesc", tBoard.getDesc()); editor.putString("boardDesc_change", TrelloContentProvider.dateToUnixString(tBoard.getDesc_changed())); } //Closed if(tBoard.getClosed() != null){ if(tBoard.getClosed() == true){ delete = true; } editor.putString("boardClosed_change", TrelloContentProvider.dateToUnixString(tBoard.getClosed_changed())); } //Organization Id if(tBoard.getOrganizationId() != null){ if(prefs.getString("boardOrganizationId", "").length() == 0){ //Just added the board on trello, its sending back trello id and organization id editor.putString("boardOrganizationId", tBoard.getOrganizationId()); editor.putString("boardOrganizationId_change", TrelloContentProvider.dateToUnixString(tBoard.getOrganizationId_change())); } else if(tBoard.getOrganizationId().contentEquals(prefs.getString("boardOrganizationId", "")) == false){ //Means it's organization id changed... delete the board delete = true; } } //LastSync if(tBoard.getLastSyncDate() != null){ editor.putString("boardSyncDate", tBoard.getLastSyncDate()); } //LastTrelloAction if(tBoard.getLastTrelloActionDate() != null){ editor.putString("boardTrelloActionDate", tBoard.getLastTrelloActionDate()); } //TODO labels, etc, don't need for this i guess but could add... if(delete){ Log.d("MyTrelloContentProvider", "updateBoard deleting it"); //Delete everything //Delete boards editor.remove("boardLocalId"); //Will cause it to be remade //Delete lists (Fields, Workers, Operations) editor.remove("listFieldsLocalId"); //Will cause it to be remade editor.remove("listWorkersLocalId"); //Will cause it to be remade TableOperations.deleteAll(dbHelper); //Delete cards (Workers, Fields, and Jobs) TableWorkers.deleteAll(dbHelper); TableFields.deleteAll(dbHelper); TableJobs.deleteAll(dbHelper); } editor.commit(); //LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(new Intent(MainActivity.INTENT_ROCKS_UPDATED)); } else { return 0; } return 1; } @Override public void insertCard(TrelloCard tcard){ dbHelper = new DatabaseHelper(getContext()); trelloHelper = new TrelloHelper(getContext()); Log.d("MyTrelloContentProvider","insertCard()"); Log.d("MyTrelloContentProvider","insert Card name: " + tcard.getName()); Log.d("MyTrelloContentProvider","insert Card desc: " + tcard.getDesc()); SharedPreferences prefs = this.getContext().getSharedPreferences("com.openatk.field_work", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); String listWorkersTrelloId = prefs.getString("listWorkersTrelloId", ""); String listFieldsTrelloId = prefs.getString("listFieldsTrelloId", ""); String listWorkersId = prefs.getString("listWorkersLocalId", ""); String listFieldsId = prefs.getString("listFieldsLocalId", ""); String boardId = prefs.getString("boardTrelloId", ""); //Figure out if its a Field, Worker, or Job //First check list id to see what type it is if(tcard.getListId() == null || tcard.getListId().length() == 0){ Log.w("MyTrelloContentProvider - insertCard", "Card does not have a trello list id."); //Should never happen } else { if(tcard.getListId().contentEquals(listWorkersTrelloId)){ //This card is in the worker list //Try to convert to worker Worker worker = trelloHelper.toWorker(tcard); if(worker == null){ //Card is no longer a valid worker, delete it //This can't happen, all cards are valid workers Log.w("MyTrelloContentProvider - insertCard", "Invalid worker."); } else { if(worker.getDeleted() == null || worker.getDeleted() == false){ //Insert in the database accordingly Log.d("MyTrelloContentProvider - insertCard", "Inserted as worker"); TableWorkers.updateWorker(dbHelper, worker); Intent toSend = new Intent(MainActivity.INTENT_WORKER_UPDATED); toSend.putExtra("id", worker.getId()); //This is set in updateWorker() LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } } } else if(tcard.getListId().contentEquals(listFieldsTrelloId)){ //This card is in the field list //Try to convert it to a field Field field = trelloHelper.toField(tcard); if(field == null) { //Card is not a valid field, don't insert it Log.w("MyTrelloContentProvider - insertCard", "Invalid field."); } else { if(field.getDeleted() == null || field.getDeleted() == false){ //Insert field in database accordingly Log.d("MyTrelloContentProvider - insertCard", "Inserted as field"); TableFields.updateField(dbHelper, field); Intent toSend = new Intent(MainActivity.INTENT_FIELD_UPDATED); toSend.putExtra("id", field.getId()); //This is set in updateField() toSend.putExtra("insert", true); //So we know to look for a job on this field. LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } } } else { //This card is in another list //Try to convert it to a job Job job = trelloHelper.toJob(tcard); if(job == null){ //Card is not a valid job, don't insert it Log.w("MyTrelloContentProvider - insertCard", "Invalid job."); } else { if(job.getDeleted() == null || job.getDeleted() == false){ //Get operation if operation changed Operation operation = TableOperations.FindOperationByTrelloId(dbHelper, tcard.getListId()); if(operation != null){ //Insert job in database accordingly job.setOperationId(operation.getId()); job.setDateOperationIdChanged(tcard.getListId_changed()); Log.d("MyTrelloContentProvider - insertCard", "Inserted as job"); TableJobs.updateJob(dbHelper, job); //Insert job into db Intent toSend = new Intent(MainActivity.INTENT_JOB_UPDATED); toSend.putExtra("id", job.getId()); //This is set in updateJob() LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(toSend); } else { //If operation is null it's not on a operation list, should never happen Log.w("MyTrellContentProvider - updateCard", "Job doesn't have a valid operation id"); } } } } } //LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(new Intent(MainActivity.INTENT_ROCKS_UPDATED)); } @Override public void insertList(TrelloList tlist){ dbHelper = new DatabaseHelper(getContext()); trelloHelper = new TrelloHelper(getContext()); //New operation or new Worker List or Field List //TODO ask to merge??????? Log.d("MyTrelloContentProvider", "insertList()"); SharedPreferences prefs = this.getContext().getSharedPreferences("com.openatk.field_work", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); String listWorkersTrelloId = prefs.getString("listWorkersTrelloId", ""); String listFieldsTrelloId = prefs.getString("listFieldsTrelloId", ""); String listWorkersId = prefs.getString("listWorkersLocalId", ""); String listFieldsId = prefs.getString("listFieldsLocalId", ""); String boardId = prefs.getString("boardTrelloId", ""); //Try to convert to field list or worker list if(tlist.getClosed() == null || tlist.getClosed() == false){ if(tlist.getName() != null){ if(tlist.getName().contentEquals("Settings - Operator List")){ //Add this worker list if we don't already have one if(listWorkersTrelloId.length() == 0){ SharedPreferences.Editor editor = prefs.edit(); editor.putString("listWorkersTrelloId", tlist.getId().trim()); editor.commit(); } } else if(tlist.getName().contentEquals("Settings - Field List")){ //Add this field list if we don't already have one if(listFieldsTrelloId.length() == 0){ SharedPreferences.Editor editor = prefs.edit(); editor.putString("listFieldsTrelloId", tlist.getId().trim()); editor.commit(); } } else { if(tlist.getName().contentEquals("To Do") == false && tlist.getName().contentEquals("Doing") == false && tlist.getName().contentEquals("Done") == false){ //New operation, add it to the operation table Operation toAdd = new Operation(); Boolean deleted = false; if(tlist.getClosed() != null && tlist.getClosed() == true) deleted = true; if(tlist.getId() != null) toAdd.setRemote_id(tlist.getId()); if(tlist.getName() != null) toAdd.setName(tlist.getName()); if(tlist.getName_changed() != null) toAdd.setDateNameChanged(tlist.getName_changed()); if(tlist.getBoardId() != null && tlist.getBoardId().contentEquals(boardId) == false) deleted = true; if(deleted){ //Don't add to the db } else { //Add to the db TableOperations.updateOperation(dbHelper, toAdd); } } } } } //LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(new Intent(MainActivity.INTENT_ROCKS_UPDATED)); } @Override public void insertBoard(TrelloBoard tBoard){ Log.d("MyTrelloContentProvider", "insertBoard()"); SharedPreferences prefs = this.getContext().getSharedPreferences("com.openatk.field_work", Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS); String boardId = prefs.getString("boardTrelloId", ""); //Check if this is our board if we don't have it already if(tBoard.getClosed() == false && tBoard.getName().contentEquals("OpenATK - Field Work App")){ Log.d("MyTrelloContentProvider - insertBoard", "Found new board on trello named the same as ours."); if(prefs.getString("boardTrelloId", "").length() == 0){ //TODO prompt to merge etc... Log.d("MyTrelloContentProvider - insertBoard", "This is our trello board. Should we use it or make our own? PROMPT"); SharedPreferences.Editor editor = prefs.edit(); editor.putString("boardTrelloId", tBoard.getId()); editor.putString("boardName", tBoard.getName()); editor.putString("boardName_change", TrelloContentProvider.dateToUnixString(tBoard.getName_changed())); editor.putString("boardClosed_change", TrelloContentProvider.dateToUnixString(tBoard.getClosed_changed())); editor.putString("boardSyncDate", tBoard.getLastSyncDate()); editor.putString("boardTrelloActionDate", tBoard.getLastTrelloActionDate()); editor.commit(); } else { Log.d("MyTrelloContentProvider - insertBoard", "We are already syncing to a Trello board. Ignoring new board."); } } //LocalBroadcastManager.getInstance(this.getContext()).sendBroadcast(new Intent(MainActivity.INTENT_ROCKS_UPDATED)); } }
OpenATK/Field-Work
app/src/main/java/com/openatk/field_work/trello/MyTrelloContentProvider.java
Java
mit
37,058
package okeanos.core.entities; /** * Represents the interface for a group. A group is a collection of entities, * that is, also other groups can be contained in a group. * * @author Wolfgang Lausenhammer */ public interface Group extends Entity { boolean addEntity(Entity entity); boolean removeEntity(Entity entity); }
wolfgang-lausenhammer/Okeanos
okeanos.core/src/main/java/okeanos/core/entities/Group.java
Java
mit
343
package com.arkcraft.mod.core.book; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public interface IPage { @SideOnly(Side.CLIENT) void draw(int guiLeft, int guiTop, int mouseX, int mouseY, SmallFontRenderer renderer, boolean canTranslate, GuiDossier dossier); @Override boolean equals(Object o); }
tterrag1098/ARKCraft-Code
src/main/java/com/arkcraft/mod/core/book/IPage.java
Java
mit
363
package autofixture.implementationdetails; import com.google.common.reflect.TypeToken; import java.lang.reflect.Array; import java.util.*; import java.util.concurrent.*; /** * Created by astral on 07.02.15. */ public class CollectionFactory { public static <T, V> Map<T, V> createMapFrom(final T[] keys, final V[] values) { final Map<T, V> map = new HashMap<>(); for (int i = 0; i < keys.length; ++i) { map.put(keys[i], values[i]); } return map; } public static <T> Deque<T> createDequeFrom(final Collection<T> many) { return new ArrayDeque<>(many); } public static <T> SortedSet<T> createSortedSetFrom(final Collection<T> many) { return new TreeSet<>(many); } public static <T> Set<T> createSetFrom(final Collection<T> many) { return new HashSet<>(many); } public static <T, V> SortedMap<T, V> createSortedMapFrom(final Map<T, V> map) { return new TreeMap<>(map); } public static <T> List<T> createList() { return new ArrayList<>(); } public static ArrayList<Object> createEmptyArrayList() { return new ArrayList<>(); } public static Stack<Object> createEmptyStack() { return new Stack<>(); } public static ArrayDeque<Object> createEmptyArrayDeque() { return new ArrayDeque<>(); } public static ArrayBlockingQueue<Object> createEmptyArrayBlockingQueue(final int repeatCount) { return new ArrayBlockingQueue<>(repeatCount); } public static LinkedHashSet<Object> createEmptyLinkedHashSet() { return new LinkedHashSet<>(); } public static LinkedList<Object> createEmptyLinkedList() { return new LinkedList<>(); } public static ConcurrentLinkedQueue<Object> createEmptyConcurrentLinkedQueue() { return new ConcurrentLinkedQueue<>(); } public static ConcurrentSkipListSet<Object> createEmptyConcurrentSkipListSet() { return new ConcurrentSkipListSet<>(); } public static CopyOnWriteArrayList<Object> createEmptyCopyOnWriteArrayList() { return new CopyOnWriteArrayList<>(); } public static CopyOnWriteArraySet<Object> createEmptyCopyOnWriteArraySet() { return new CopyOnWriteArraySet<>(); } public static PriorityBlockingQueue<Object> createEmptyPriorityBlockingQueue() { return new PriorityBlockingQueue<>(); } public static PriorityQueue<Object> createEmptyPriorityQueue() { return new PriorityQueue<>(); } public static TreeSet<Object> createTreeSet() { return new TreeSet<>(); } public static Set<Object> createEmptySet() { return new HashSet<>(); } public static <T> PriorityQueue<T> createQueueFrom(final Collection<T> many) { return new PriorityQueue<>(many); } public static <T> T[] createArray(TypeToken<T> type, int length) { return (T[]) Array.newInstance( type.getRawType(), length); } public static Map createEmptyHashMap() { return new HashMap<>(); } public static Map createEmptySortedMap() { return new TreeMap<>(); } public static Map createEmptyTreeMap() { return new TreeMap<>(); } public static Map createEmptyNavigableMap() { return new TreeMap<>(); } public static Map createEmptyConcurrentHashMap() { return new ConcurrentHashMap<>(); } public static Map createEmptyConcurrentSkipListMap() { return new ConcurrentSkipListMap<>(); } public static Map createEmptyHashtable() { return new Hashtable<>(); } public static Map createEmptyLinkedHashMap() { return new LinkedHashMap<>(); } public static Map createEmptyWeakHashMap() { return new WeakHashMap<>(); } public static Map createEmptyIdentityHashMap() { return new IdentityHashMap<>(); } public static Map createEmptyEnumMap(Class<Enum> keyType) { return new EnumMap(keyType); } }
grzesiek-galezowski/AutoFixtureGenerator
src/main/java/autofixture/implementationdetails/CollectionFactory.java
Java
mit
3,776
package espe.edu.ec.educat.model; import espe.edu.ec.educat.model.CapacitacionAlumno; import espe.edu.ec.educat.model.ProgramaAlumno; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2017-07-15T08:26:21") @StaticMetamodel(Alumno.class) public class Alumno_ { public static volatile SingularAttribute<Alumno, String> codAlumno; public static volatile ListAttribute<Alumno, ProgramaAlumno> programaAlumnoList; public static volatile SingularAttribute<Alumno, Date> fechaNacimiento; public static volatile SingularAttribute<Alumno, String> genero; public static volatile SingularAttribute<Alumno, String> direccion; public static volatile SingularAttribute<Alumno, String> telefono; public static volatile SingularAttribute<Alumno, String> nombre; public static volatile SingularAttribute<Alumno, String> correoElectronico; public static volatile ListAttribute<Alumno, CapacitacionAlumno> capacitacionAlumnoList; }
JonathanAlejandroTorres/Educa05
Educa05-ejb/target/generated-sources/annotations/espe/edu/ec/educat/model/Alumno_.java
Java
mit
1,175
package ru.fizteh.fivt.students.kamilTalipov.database.commands; import ru.fizteh.fivt.students.kamilTalipov.database.core.NoTableSelectedException; import ru.fizteh.fivt.students.kamilTalipov.database.core.TransactionDatabase; import ru.fizteh.fivt.students.kamilTalipov.shell.Shell; import ru.fizteh.fivt.students.kamilTalipov.shell.SimpleCommand; import java.io.IOException; public class CommitCommand extends SimpleCommand { private final TransactionDatabase database; public CommitCommand(TransactionDatabase database) { super("commit", 0); this.database = database; } @Override public void run(Shell shell, String[] args) throws IllegalArgumentException { if (numberOfArguments != args.length) { throw new IllegalArgumentException(name + ": expected " + numberOfArguments + " but " + args.length + " got"); } try { System.out.println(database.commit()); } catch (NoTableSelectedException e) { System.err.println("no table"); } catch (IOException e) { System.err.println("io error"); } } }
kamiltalipov/database-fizteh
src/ru/fizteh/fivt/students/kamilTalipov/database/commands/CommitCommand.java
Java
mit
1,156
package hw; import java.util.Scanner; /* * 志明跟春嬌是班上的一對情侶,他們有寫交換日記來打發時間的習慣,為了防止他們 寫的內容被幫忙傳的同學,或者是不小心被老師沒收,而曝光了裡面寫的東西,他們 想到了一個辦法,就是把內容的所有字母都往後數幾次的字母替代,而往後數幾次的 數目就寫在內容的下一行。但是,問題來了,春嬌覺得每次寫完都要在數來數去的轉 化成”加密”格式,實在是太麻煩了。但又礙於不想被輕易的看到內容,於是她拜託你 寫個程式幫忙她可以直接把寫好的內容轉化成”加密”的型態。加密結果不會影響原字 母的大小寫,且數字部分亦作相同處理,但不處理符號及特殊字元及中文。(第一行為想輸入的內容,不超過 100 個字,第二行為打完你想輸入的內容之後,換 行輸入你想要往後替代的數目) * Date: 2016/12/12 * Author: 103051089 林冠磊 */ public class hw01_103051089 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String inputStr = sc.nextLine(); int key = sc.nextInt(); char[] str = inputStr.toCharArray(); for(int i = 0;i<str.length;i++){ if(str[i]>='A' && str[i]<='Z'){ if(str[i]+key>='Z'){ str[i]=(char)((((str[i]+key)-'Z'-1)%26)+'A'); }else { str[i]+=key; } }else if(str[i]>='a' && str[i]<='z'){ if(str[i]+key>='z'){ str[i]=(char)((((str[i]+key)-'z'-1)%26)+'a'); }else { str[i]+=key; } } } inputStr = String.copyValueOf(str); System.out.println(inputStr); } }
csie-asia-Java-Programming-1/week11-20161212-LinKuanLei
src/hw/hw01_103051089.java
Java
mit
1,674
package com.indignado.functional.test.levels.flyingDart; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.utils.ObjectMap; import com.indignado.logicbricks.components.RigidBodiesComponents; import com.indignado.logicbricks.core.Script; import com.indignado.logicbricks.config.Settings; import com.indignado.logicbricks.core.actuators.Actuator; import com.indignado.logicbricks.core.actuators.InstanceEntityActuator; import com.indignado.logicbricks.core.controllers.ScriptController; import com.indignado.logicbricks.core.data.LogicBrick; import com.indignado.logicbricks.core.sensors.AlwaysSensor; import com.indignado.logicbricks.core.sensors.MouseSensor; import com.indignado.logicbricks.core.sensors.Sensor; import com.indignado.logicbricks.utils.Log; /** * @author Rubentxu. */ public class MousePositionScript implements Script { private boolean init = false; @Override public void execute(ScriptController controller, ObjectMap<String, Sensor> sensors, ObjectMap<String, Actuator> actuators) { MouseSensor mouseSensor = (MouseSensor) sensors.get("SensorMouse"); AlwaysSensor delaySensor = (AlwaysSensor) sensors.get("DelayTrigger"); if (mouseSensor.pulseState.equals(LogicBrick.BrickMode.BM_ON) && mouseSensor.positive && delaySensor.pulseState.equals(LogicBrick.BrickMode.BM_ON) && delaySensor.positive) { controller.pulseState = mouseSensor.pulseState; Vector2 mousePosition = mouseSensor.positionSignal; Log.debug("MousePositionScript::Trigger", "mouse position %s", mousePosition); InstanceEntityActuator instanceEntityActuator = (InstanceEntityActuator) actuators.get("ActuatorInstanceDart"); Body ownerBody = instanceEntityActuator.owner.getComponent(RigidBodiesComponents.class).rigidBodies.first(); float angle = MathUtils.atan2(mousePosition.y - ownerBody.getPosition().y, mousePosition.x - ownerBody.getPosition().x); instanceEntityActuator.initialVelocity = new Vector2(Settings.WIDTH / 2 * MathUtils.cos(angle), Settings.WIDTH * MathUtils.sin(angle)); instanceEntityActuator.angle = angle; controller.pulseState = LogicBrick.BrickMode.BM_ON; Log.debug("MousePositionScript::Trigger", "Initial Velocity %s Angle %f", instanceEntityActuator.initialVelocity.toString(), angle); } else { controller.pulseState = LogicBrick.BrickMode.BM_OFF; } } }
Rubentxu/GDX-Logic-Bricks
functional-tests/src/main/java/com/indignado/functional/test/levels/flyingDart/MousePositionScript.java
Java
mit
2,576
/* The MIT License (MIT) Copyright (c) 2015 Los Andes University Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package co.edu.uniandes.csw.artwork.entities; import java.io.Serializable; import javax.persistence.Entity; import co.edu.uniandes.csw.crud.spi.entity.BaseEntity; import java.util.Objects; import uk.co.jemos.podam.common.PodamExclude; import javax.persistence.ManyToOne; /** * @generated */ @Entity public class CategoryEntity extends BaseEntity implements Serializable { @PodamExclude @ManyToOne private CategoryEntity parentCategory; /** * Obtiene el atributo parentCategory. * * @return atributo parentCategory. * @generated */ public CategoryEntity getParentCategory() { return parentCategory; } /** * Establece el valor del atributo parentCategory. * * @param parentCategory nuevo valor del atributo * @generated */ public void setParentCategory(CategoryEntity parentcategory) { this.parentCategory = parentcategory; } @Override public String toString() { return "CategoryEntity{" + "parentCategory=" + parentCategory + '}'; } }
Uniandes-MISO4203/artwork-201620-1
artwork-logic/src/main/java/co/edu/uniandes/csw/artwork/entities/CategoryEntity.java
Java
mit
2,157
package com.cmendenhall.utils; import java.io.IOException; import java.util.HashMap; import java.util.Properties; public class StringLoader { private HashMap<String, String> viewStrings = new HashMap<String, String>(); private Properties viewStringProperties = new Properties(); private void load(String propertyName) { String propertyString = viewStringProperties.getProperty(propertyName); viewStrings.put(propertyName, propertyString); } private void loadViewStrings(String filepath) { try { viewStringProperties.load(this.getClass().getResourceAsStream(filepath)); } catch (IOException exception) { exception.printStackTrace(); } String[] properties = { "welcome", "divider", "yourmove", "yourmovethreesquares", "playagain", "gameoverdraw", "gameoverwin", "xwins", "owins", "chooseplayerone", "chooseplayertwo", "boardsize"}; for (String property : properties) { load(property); } } public HashMap<String, String> getViewStrings(String filepath) { loadViewStrings(filepath); return viewStrings; } }
ecmendenhall/Java-TTT
src/com/cmendenhall/utils/StringLoader.java
Java
mit
1,510
package com.github.mrcritical.ironcache.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.joda.time.DateTime; /** * Represents an item stored in the cache. * * @author pjarrell * */ @Data @NoArgsConstructor @AllArgsConstructor public class CachedItem { private String cache; private String cas; private DateTime expires; private int flags; private String key; private Object value; }
mrcritical/ironcache
src/main/java/com/github/mrcritical/ironcache/model/CachedItem.java
Java
mit
460
package io.github.ageofwar.telejam.inline; import io.github.ageofwar.telejam.updates.ChosenInlineResultUpdate; import io.github.ageofwar.telejam.updates.InlineQueryUpdate; import io.github.ageofwar.telejam.updates.Update; import io.github.ageofwar.telejam.updates.UpdateHandler; /** * Interface that handles inline queries received from a bot. */ @FunctionalInterface public interface InlineQueryHandler extends UpdateHandler { /** * Handles an incoming inline query from the bot. * * @param inlineQuery new incoming message * @throws Throwable if a throwable is thrown */ void onInlineQuery(InlineQuery inlineQuery) throws Throwable; /** * Handles an incoming chosen inline result from the bot. * * @param chosenInlineResult new incoming chosen inline result * @throws Throwable if a throwable is thrown */ default void onChosenInlineResult(ChosenInlineResult chosenInlineResult) throws Throwable { } @Override default void onUpdate(Update update) throws Throwable { if (update instanceof InlineQueryUpdate) { onInlineQuery(((InlineQueryUpdate) update).getInlineQuery()); } else if (update instanceof ChosenInlineResultUpdate) { onChosenInlineResult(((ChosenInlineResultUpdate) update).getChosenInlineResult()); } } }
AgeOfWar/Telejam
src/main/java/io/github/ageofwar/telejam/inline/InlineQueryHandler.java
Java
mit
1,305
package main; import org.lwjgl.util.vector.Vector4f; /** * Created by Astemir Eleev on 14/06/14. */ public interface Pipeline { /** * Here all the classes and resources that are going to be used in run() method must be initialized */ public void init(); /** * This method initializes the base GL state * @param viewWidth - view area width * @param viewHeight - view area height * @param color - color that will be used as a base background when the screen will be updated */ public void initGL(int viewWidth, int viewHeight, Vector4f color); /** * The main OpenGL rendering loop. Here all the "magic" happens */ public void run(); /** * The beginning of rendering stage must be put into this method, then this method will be invoked by run() to render. */ public void renderBegin(); /** * Things that must be invoked after the renderBegin() method must be put here */ public void renderEnd(); /** * All the keyboard, mouse and etc. events must be handled here */ public void poolInput(); /** * Initializes the base state of the OpenGL context and pixel format of the display. It defines what * OpenGL's profile will be used e.g. if you put as versionGeneration value 1 and as versionUpdate value 1 as well * the OpenGL's state machine will be 1.1 which means no programmable features, just old fixed pipeline * @param versionGeneration - version that defines what generation of OpenGL will be used (e.g. 1, 2, 3, 4 (current version)) * @param versionUpdate - it defines which one of a generation updates will be used (e.g. 1.1, 1.2, 1.3 ect.) */ public void display(int versionGeneration, int versionUpdate, boolean forwardCompatible, boolean coreProfile, boolean debug); /** * This method destroyed the Display object that holds the hole graphics information. Also here you'd better put some * stuff that must be deallocated and cleaned up */ public void cleanUp(); /** * This method prints the most important information about the current graphics hardware & software */ public void printInformationAbountGraphics(); /** * Prints information about VM, OS and ect. */ public void printInformationAboutSystem(); }
jVirus/jToolkit
src/main/Pipeline.java
Java
mit
2,348
package com.globallogic.rss_reader.activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import com.globallogic.rss_reader.BuildConfig; import com.globallogic.rss_reader.R; import com.globallogic.rss_reader.fragment.RecyclerViewFragment; import com.globallogic.rss_reader.interfaces.IItemClick; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity extends AppCompatActivity implements IItemClick { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.activity_main_container, new RecyclerViewFragment()) .commit(); } @Override public void openItem(String link) { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(link)); startActivity(i); } }
globallogicargentina/android-rssreader-lp
app/src/main/java/com/globallogic/rss_reader/activity/MainActivity.java
Java
mit
1,224
package org.post; public class Post { private static PostPlatform post; public static PostPlatform getPost(){ return post; } public static void setPost(PostPlatform p){ post=p; } }
post-lang/ipost
post-api/src/main/java/org/post/Post.java
Java
mit
199
package com.github.openwebnet.repository.impl; import com.annimon.stream.Stream; import com.github.openwebnet.component.Injector; import com.github.openwebnet.model.AutomationModel; import com.github.openwebnet.model.DeviceModel; import com.github.openwebnet.model.EnergyModel; import com.github.openwebnet.model.EnvironmentModel; import com.github.openwebnet.model.GatewayModel; import com.github.openwebnet.model.IpcamModel; import com.github.openwebnet.model.LightModel; import com.github.openwebnet.model.ScenarioModel; import com.github.openwebnet.model.SoundModel; import com.github.openwebnet.model.TemperatureModel; import com.github.openwebnet.model.firestore.ProfileInfoModel; import com.github.openwebnet.model.firestore.ProfileModel; import com.github.openwebnet.model.firestore.ProfileVersionModel; import com.github.openwebnet.model.firestore.ShareProfileRequest; import com.github.openwebnet.model.firestore.UserModel; import com.github.openwebnet.model.firestore.UserProfileModel; import com.github.openwebnet.repository.AutomationRepository; import com.github.openwebnet.repository.DeviceRepository; import com.github.openwebnet.repository.EnergyRepository; import com.github.openwebnet.repository.EnvironmentRepository; import com.github.openwebnet.repository.FirestoreRepository; import com.github.openwebnet.repository.GatewayRepository; import com.github.openwebnet.repository.IpcamRepository; import com.github.openwebnet.repository.LightRepository; import com.github.openwebnet.repository.ScenarioRepository; import com.github.openwebnet.repository.SoundRepository; import com.github.openwebnet.repository.TemperatureRepository; import com.google.android.gms.tasks.Task; import com.google.common.collect.Lists; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FieldValue; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreSettings; import com.google.firebase.firestore.SetOptions; import com.google.firebase.firestore.Source; import com.google.firebase.firestore.WriteBatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import rx.Observable; public class FirestoreRepositoryImpl implements FirestoreRepository { private static final Logger log = LoggerFactory.getLogger(FirestoreRepositoryImpl.class); private static boolean DEVELOPMENT = false; private static final String ENVIRONMENT = DEVELOPMENT ? "dev_" : ""; private static final String COLLECTION_USERS = ENVIRONMENT + "users"; private static final String COLLECTION_USER_PROFILES = "profiles"; private static final String COLLECTION_PROFILES = ENVIRONMENT + "profiles"; private static final String COLLECTION_PROFILES_INFO = ENVIRONMENT + "profiles_info"; private static final String COLLECTION_SHARE_PROFILE = ENVIRONMENT + "share_profile"; private static final String COLLECTION_SHARE_PROFILE_REQUESTS = "requests"; @Inject AutomationRepository automationRepository; @Inject DeviceRepository deviceRepository; @Inject EnergyRepository energyRepository; @Inject EnvironmentRepository environmentRepository; @Inject GatewayRepository gatewayRepository; @Inject IpcamRepository ipcamRepository; @Inject LightRepository lightRepository; @Inject ScenarioRepository scenarioRepository; @Inject SoundRepository soundRepository; @Inject TemperatureRepository temperatureRepository; public FirestoreRepositoryImpl() { Injector.getApplicationComponent().inject(this); } private FirebaseFirestore getDb() { FirebaseFirestore firestore = FirebaseFirestore.getInstance(); FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder() // warning .setTimestampsInSnapshotsEnabled(true) // cache .setPersistenceEnabled(false) .build(); firestore.setFirestoreSettings(settings); return firestore; } @Override public Observable<Void> updateUser(UserModel user) { return Observable.create(subscriber -> { try { log.info("updating user: userId={}", user.getUserId()); getDb() .collection(COLLECTION_USERS) .document(user.getUserId()) .set(user, SetOptions.merge()) .addOnSuccessListener(aVoid -> { log.info("user updated with success"); subscriber.onNext(null); subscriber.onCompleted(); }) .addOnFailureListener(e -> { log.error("failed to update user", e); subscriber.onError(e); }); } catch (Exception e) { log.error("FirestoreRepository#updateUser", e); subscriber.onError(e); } }); } @Override public Observable<String> addProfile(UserModel user, String name) { List<Observable<?>> findAll = Lists.newArrayList( automationRepository.findAll(), deviceRepository.findAll(), energyRepository.findAll(), environmentRepository.findAll(), gatewayRepository.findAll(), ipcamRepository.findAll(), lightRepository.findAll(), scenarioRepository.findAll(), soundRepository.findAll(), temperatureRepository.findAll() ); // Observable.zip support only up to 9 parameters, use Iterable return Observable.zip(findAll, results -> ProfileModel.addBuilder() .version(ProfileVersionModel.newInstance()) .automations((List<AutomationModel>) results[0]) .devices((List<DeviceModel>) results[1]) .energies((List<EnergyModel>) results[2]) .environments((List<EnvironmentModel>) results[3]) .gateways((List<GatewayModel>) results[4]) .ipcams((List<IpcamModel>) results[5]) .lights((List<LightModel>) results[6]) .scenarios((List<ScenarioModel>) results[7]) .sounds((List<SoundModel>) results[8]) .temperatures((List<TemperatureModel>) results[9]) .build()) .flatMap(profile -> addProfile(user.getUserId(), name, profile)); } // issue: if there are too many DELETED profiles // user might be blocked to add more due to maxProfile restriction private Observable<String> addProfile(String userId, String name, ProfileModel profile) { return Observable.create(subscriber -> { try { FirebaseFirestore db = getDb(); WriteBatch batch = db.batch(); // add profile/{profileRef}/[ProfileModel + ProfileDetailModel] DocumentReference profileRef = db.collection(COLLECTION_PROFILES).document(); batch.set(profileRef, profile, SetOptions.merge()); UserProfileModel userProfile = UserProfileModel .addBuilder() .profileRef(profileRef) .name(name) .build(); // add user/{userId}/.../profiles/[UserProfileModel] DocumentReference userRef = db.collection(COLLECTION_USERS).document(userId); batch.update(userRef, COLLECTION_USER_PROFILES, FieldValue.arrayUnion(userProfile.toMap())); ProfileInfoModel profileInfo = ProfileInfoModel .builder(userProfile) .userId(userId) .build(); String profileKey = profileRef.getPath().replace(COLLECTION_PROFILES + "/", ""); // add profiles_info/{profileRef}/[ProfileInfoModel] DocumentReference profileInfoRef = db.collection(COLLECTION_PROFILES_INFO).document(profileKey); batch.set(profileInfoRef, profileInfo, SetOptions.merge()); batch.commit() .addOnSuccessListener(aVoid -> { log.info("profile added with success"); subscriber.onNext(profileRef.getPath()); subscriber.onCompleted(); }) .addOnFailureListener(e -> { log.error("failed to add profile", e); subscriber.onError(e); }); } catch (Exception e) { log.error("FirestoreRepository#addProfile", e); subscriber.onError(e); } }); } private boolean userHasProfiles(DocumentSnapshot document) { return document != null && document.exists() && document.getData() != null && document.getData().containsKey(COLLECTION_USER_PROFILES); } @Override public Observable<List<UserProfileModel>> getProfiles(String userId) { return Observable.create(subscriber -> { try { getDb() .collection(COLLECTION_USERS) .document(userId) .get(Source.DEFAULT) .addOnCompleteListener(task -> { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (userHasProfiles(document)) { List<UserProfileModel> userProfileModels = Stream.of((List<Map<String, Object>>) document.getData().get(COLLECTION_USER_PROFILES)) .map(userProfileMap -> UserProfileModel.getBuilder(userProfileMap).build()) // filter deleted .filterNot(userProfile -> userProfile.getStatus() == UserProfileModel.Status.DELETED) .toList(); log.info("active user profiles: size={}", userProfileModels.size()); subscriber.onNext(userProfileModels); subscriber.onCompleted(); } else { log.error("user profiles not found"); subscriber.onNext(new ArrayList<>()); subscriber.onCompleted(); } } else { log.error("failed to get user profiles", task.getException()); subscriber.onError(task.getException()); } }); } catch (Exception e) { log.error("FirestoreRepository#getUserProfiles", e); subscriber.onError(e); } }); } @Override public Observable<ProfileModel> getProfile(DocumentReference profileRef) { return Observable.create(subscriber -> { try { getDb() .collection(COLLECTION_PROFILES) .document(profileRef.getId()) .get() .addOnSuccessListener(documentSnapshot -> { log.info("profile retrieved with success"); ProfileModel profileModel = documentSnapshot.toObject(ProfileModel.class); subscriber.onNext(profileModel); subscriber.onCompleted(); }) .addOnFailureListener(e -> { log.error("failed to retrieve profile", e); subscriber.onError(e); }); } catch (Exception e) { log.error("FirestoreRepository#getProfile", e); subscriber.onError(e); } }); } @Override public Observable<List<Integer>> applyProfile(ProfileModel profile) { ProfileVersionModel version = profile.getVersion(); List<Observable<?>> addAll = Lists.newArrayList( automationRepository.addAll(Stream.of(profile.getAutomations()) .map(automationMap -> AutomationModel.newInstance(automationMap, version)).toList()), deviceRepository.addAll(Stream.of(profile.getDevices()) .map(deviceMap -> DeviceModel.newInstance(deviceMap, version)).toList()), energyRepository.addAll(Stream.of(profile.getEnergies()) .map(energyMap -> EnergyModel.newInstance(energyMap, version)).toList()), environmentRepository.addAll(Stream.of(profile.getEnvironments()) .map(environmentMap -> EnvironmentModel.newInstance(environmentMap, version)).toList()), gatewayRepository.addAll(Stream.of(profile.getGateways()) .map(gatewayMap -> GatewayModel.newInstance(gatewayMap, version)).toList()), ipcamRepository.addAll(Stream.of(profile.getIpcams()) .map(ipcamMap -> IpcamModel.newInstance(ipcamMap, version)).toList()), lightRepository.addAll(Stream.of(profile.getLights()) .map(lightMap -> LightModel.newInstance(lightMap, version)).toList()), scenarioRepository.addAll(Stream.of(profile.getScenarios()) .map(scenarioMap -> ScenarioModel.newInstance(scenarioMap, version)).toList()), soundRepository.addAll(Stream.of(profile.getSounds()) .map(soundMap -> SoundModel.newInstance(soundMap, version)).toList()), temperatureRepository.addAll(Stream.of(profile.getTemperatures()) .map(temperatureMap -> TemperatureModel.newInstance(temperatureMap, version)).toList()) ); // count of each model return Observable.zip(addAll, results -> Stream.of(results) .map(object -> ((List<?>) object).size()).toList()); } @Override public Observable<Void> renameProfile(String userId, DocumentReference profileRef, String name) { return getProfiles(userId) .flatMap(userProfiles -> { log.info("rename user profile: userId={} profileRef={} name={}", userId, profileRef.getPath(), name); List<UserProfileModel> updatedUserProfiles = Stream .of(userProfiles) .map(userProfile -> { // update name if (userProfile.getProfileRef().getPath().equals(profileRef.getPath())) { return UserProfileModel .getBuilder(userProfile.toMap()) .name(name) .modifiedAt(new Date()) .build(); } return userProfile; }) .toList(); return updateUserProfile(userId, updatedUserProfiles); }); } // immutable append-only @Override public Observable<Void> shareProfile(String userId, DocumentReference profileRef, String email) { return Observable.create(subscriber -> { try { log.info("share [userId={}|profileRef={}] to email [{}]", userId, profileRef.getPath(), email); ShareProfileRequest shareProfileRequest = ShareProfileRequest.addBuilder() .profileRef(profileRef) .email(email) .build(); DocumentReference requestRef = getDb() .collection(COLLECTION_SHARE_PROFILE) .document(userId); Task<Void> updateTask = requestRef.update(COLLECTION_SHARE_PROFILE_REQUESTS, FieldValue.arrayUnion(shareProfileRequest.toMap())); updateTask.addOnSuccessListener(aVoid -> { log.info("request created with success (1)"); subscriber.onNext(null); subscriber.onCompleted(); }); updateTask.addOnFailureListener(e1 -> { if (e1.getMessage().contains("NOT_FOUND")) { Map requestMap = new HashMap<String, Object>(); requestMap.put(COLLECTION_SHARE_PROFILE_REQUESTS, Lists.newArrayList(shareProfileRequest.toMap())); requestRef .set(requestMap) .addOnSuccessListener(aVoid -> { log.info("request created with success (2)"); subscriber.onNext(null); subscriber.onCompleted(); }) .addOnFailureListener(e2 -> { log.error("failed to create request (2)", e2); subscriber.onError(e2); }); } else { log.error("failed to create request (1)", e1); subscriber.onError(e1); } }); } catch (Exception e) { log.error("FirestoreRepository#shareProfile", e); subscriber.onError(e); } }); } @Override public Observable<Void> deleteProfile(String userId, DocumentReference profileRef) { return getProfiles(userId) .flatMap(userProfiles -> { log.info("delete user profile: userId={} profileRef={}", userId, profileRef.getPath()); List<UserProfileModel> updatedUserProfiles = Stream .of(userProfiles) .map(userProfile -> { // update status if (userProfile.getProfileRef().getPath().equals(profileRef.getPath())) { return UserProfileModel .getBuilder(userProfile.toMap()) .status(UserProfileModel.Status.DELETED) .modifiedAt(new Date()) .build(); } return userProfile; }) .toList(); return updateUserProfile(userId, updatedUserProfiles); }); } private Observable<Void> updateUserProfile(String userId, List<UserProfileModel> userProfiles) { return Observable.create(subscriber -> { try { log.info("updating user profile: new size={}", userProfiles.size()); List<Map<String, Object>> userProfilesMap = Stream.of(userProfiles).map(UserProfileModel::toMap).toList(); getDb() .collection(COLLECTION_USERS) .document(userId) .update(COLLECTION_USER_PROFILES, userProfilesMap) .addOnSuccessListener(aVoid -> { log.info("user profile updated with success"); subscriber.onNext(null); subscriber.onCompleted(); }) .addOnFailureListener(e -> { log.error("failed to update user profile", e); subscriber.onError(e); }); } catch (Exception e) { log.error("FirestoreRepository#updateUserProfile", e); subscriber.onError(e); } }); } @Override public Observable<Void> deleteLocalProfile() { return environmentRepository.deleteAll() .flatMap(aVoid -> gatewayRepository.deleteAll()); } @Override public Observable<Void> testQuery(String userId) { return Observable.create(subscriber -> { try { log.info("test query: userId={}", userId); // verify PERMISSION_DENIED getDb().collection(COLLECTION_USERS).document("USER_ID").get() //getDb().collection(COLLECTION_PROFILES).document("PROFILE_ID").get() //getDb().collection(COLLECTION_PROFILES_INFO).document("PROFILE_ID").get() .addOnSuccessListener(result -> { log.info("test query succeeded: {}", result); subscriber.onNext(null); subscriber.onCompleted(); }) .addOnFailureListener(e -> { log.error("failed to test query", e); subscriber.onError(e); }); } catch (Exception e) { log.error("FirestoreRepository#testQuery", e); subscriber.onError(e); } }); } }
openwebnet/openwebnet-android
app/src/main/java/com/github/openwebnet/repository/impl/FirestoreRepositoryImpl.java
Java
mit
21,309
/** * ¡¶¹¹½¨¸ßÐÔÄܵĴóÐÍ·Ö²¼Ê½JavaÓ¦Óá· * ÊéÖеÄʾÀý´úÂë * °æÈ¨ËùÓÐ 2008---2009 */ package book.chapter1.rmi.impl; import java.rmi.RemoteException; import book.chapter1.rmi.Business; /** * ÃèÊö£º * * @author bluedavy * ´´½¨Ê±¼ä£º 2009-1-4 */ public class BusinessImpl implements Business { /* (non-Javadoc) * @see book.chapter1.rmi.Business#echo(java.lang.String) */ public String echo(String message) throws RemoteException { if("quit".equalsIgnoreCase(message.toString())){ System.out.println("Server will be shutdown!"); System.exit(0); } System.out.println("Message from client: "+message); return "Server response£º"+message; } }
java-scott/java-project
分布式java应用基础与实践/Chapter1/src/book/chapter1/rmi/impl/BusinessImpl.java
Java
mit
676
package invtweaks; import invtweaks.api.IItemTree; import invtweaks.api.IItemTreeCategory; import invtweaks.api.IItemTreeItem; import net.minecraft.item.ItemStack; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.oredict.OreDictionary; import java.util.*; import java.util.logging.Logger; /** * Contains the whole hierarchy of categories and items, as defined in the XML item tree. Is used to recognize keywords * and store item orders. * * @author Jimeo Wan */ public class InvTweaksItemTree implements IItemTree { public static final int MAX_CATEGORY_RANGE = 1000; public static final String UNKNOWN_ITEM = "unknown"; private static final Logger log = InvTweaks.log; /** * All categories, stored by name */ private Map<String, IItemTreeCategory> categories = new HashMap<String, IItemTreeCategory>(); /** * Items stored by ID. A same ID can hold several names. */ private Map<Integer, Vector<IItemTreeItem>> itemsById = new HashMap<Integer, Vector<IItemTreeItem>>(500); private static Vector<IItemTreeItem> defaultItems = null; /** * Items stored by name. A same name can match several IDs. */ private Map<String, Vector<IItemTreeItem>> itemsByName = new HashMap<String, Vector<IItemTreeItem>>(500); private String rootCategory; public InvTweaksItemTree() { reset(); } public void reset() { if(defaultItems == null) { defaultItems = new Vector<IItemTreeItem>(); defaultItems.add(new InvTweaksItemTreeItem(UNKNOWN_ITEM, -1, InvTweaksConst.DAMAGE_WILDCARD, Integer.MAX_VALUE)); } // Reset tree categories.clear(); itemsByName.clear(); itemsById.clear(); } /** * Checks if given item ID matches a given keyword (either the item's name is the keyword, or it is in the keyword * category) * * @param items * @param keyword */ @Override public boolean matches(List<IItemTreeItem> items, String keyword) { if(items == null) { return false; } // The keyword is an item for(IItemTreeItem item : items) { if(item.getName() != null && item.getName().equals(keyword)) { return true; } } // The keyword is a category IItemTreeCategory category = getCategory(keyword); if(category != null) { for(IItemTreeItem item : items) { if(category.contains(item)) { return true; } } } // Everything is stuff return keyword.equals(rootCategory); } @Override public int getKeywordDepth(String keyword) { try { return getRootCategory().findKeywordDepth(keyword); } catch(NullPointerException e) { log.severe("The root category is missing: " + e.getMessage()); return 0; } } @Override public int getKeywordOrder(String keyword) { List<IItemTreeItem> items = getItems(keyword); if(items != null && items.size() != 0) { return items.get(0).getOrder(); } else { try { return getRootCategory().findCategoryOrder(keyword); } catch(NullPointerException e) { log.severe("The root category is missing: " + e.getMessage()); return -1; } } } /** * Checks if the given keyword is valid (i.e. represents either a registered item or a registered category) * * @param keyword */ @Override public boolean isKeywordValid(String keyword) { // Is the keyword an item? if(containsItem(keyword)) { return true; } // Or maybe a category ? else { IItemTreeCategory category = getCategory(keyword); return category != null; } } /** * Returns a reference to all categories. */ @Override public Collection<IItemTreeCategory> getAllCategories() { return categories.values(); } @Override public IItemTreeCategory getRootCategory() { return categories.get(rootCategory); } @Override public IItemTreeCategory getCategory(String keyword) { return categories.get(keyword); } @Override public boolean isItemUnknown(int id, int damage) { return itemsById.get(id) == null; } @Override public List<IItemTreeItem> getItems(int id, int damage) { List<IItemTreeItem> items = itemsById.get(id); List<IItemTreeItem> filteredItems = new ArrayList<IItemTreeItem>(); if(items != null) { filteredItems.addAll(items); } // Filter items of same ID, but different damage value if(items != null && !items.isEmpty()) { for(IItemTreeItem item : items) { if(item.getDamage() != InvTweaksConst.DAMAGE_WILDCARD && item.getDamage() != damage) { filteredItems.remove(item); } } } // If there's no matching item, create new ones if(filteredItems.isEmpty()) { IItemTreeItem newItemId = new InvTweaksItemTreeItem(String.format("%d-%d", id, damage), id, damage, 5000 + id * 16 + damage); IItemTreeItem newItemDamage = new InvTweaksItemTreeItem(Integer.toString(id), id, InvTweaksConst.DAMAGE_WILDCARD, 5000 + id * 16); addItem(getRootCategory().getName(), newItemId); addItem(getRootCategory().getName(), newItemDamage); filteredItems.add(newItemId); filteredItems.add(newItemDamage); } Iterator<IItemTreeItem> it = filteredItems.iterator(); while(it.hasNext()) { if(it.next() == null) { it.remove(); } } return filteredItems; } @Override public List<IItemTreeItem> getItems(String name) { return itemsByName.get(name); } @Override public IItemTreeItem getRandomItem(Random r) { return (IItemTreeItem) itemsByName.values().toArray()[r.nextInt(itemsByName.size())]; } @Override public boolean containsItem(String name) { return itemsByName.containsKey(name); } @Override public boolean containsCategory(String name) { return categories.containsKey(name); } @Override public void setRootCategory(IItemTreeCategory category) { rootCategory = category.getName(); categories.put(rootCategory, category); } @Override public IItemTreeCategory addCategory(String parentCategory, String newCategory) throws NullPointerException { IItemTreeCategory addedCategory = new InvTweaksItemTreeCategory(newCategory); addCategory(parentCategory, addedCategory); return addedCategory; } @Override public IItemTreeItem addItem(String parentCategory, String name, int id, int damage, int order) throws NullPointerException { InvTweaksItemTreeItem addedItem = new InvTweaksItemTreeItem(name, id, damage, order); addItem(parentCategory, addedItem); return addedItem; } @Override public void addCategory(String parentCategory, IItemTreeCategory newCategory) throws NullPointerException { // Build tree categories.get(parentCategory.toLowerCase()).addCategory(newCategory); // Register category categories.put(newCategory.getName(), newCategory); } @Override public void addItem(String parentCategory, IItemTreeItem newItem) throws NullPointerException { // Build tree categories.get(parentCategory.toLowerCase()).addItem(newItem); // Register item if(itemsByName.containsKey(newItem.getName())) { itemsByName.get(newItem.getName()).add(newItem); } else { Vector<IItemTreeItem> list = new Vector<IItemTreeItem>(); list.add(newItem); itemsByName.put(newItem.getName(), list); } if(itemsById.containsKey(newItem.getId())) { itemsById.get(newItem.getId()).add(newItem); } else { Vector<IItemTreeItem> list = new Vector<IItemTreeItem>(); list.add(newItem); itemsById.put(newItem.getId(), list); } } /** * For debug purposes. Call log(getRootCategory(), 0) to log the whole tree. */ private void log(IItemTreeCategory category, int indentLevel) { String logIdent = ""; for(int i = 0; i < indentLevel; i++) { logIdent += " "; } log.info(logIdent + category.getName()); for(IItemTreeCategory subCategory : category.getSubCategories()) { log(subCategory, indentLevel + 1); } for(List<IItemTreeItem> itemList : category.getItems()) { for(IItemTreeItem item : itemList) { log.info(logIdent + " " + item + " " + item.getId() + " " + item.getDamage()); } } } private class OreDictInfo { String category; String name; String oreName; int order; OreDictInfo(String category, String name, String oreName, int order) { this.category = category; this.name = name; this.oreName = oreName; this.order = order; } } @Override public void registerOre(String category, String name, String oreName, int order) { for(ItemStack i : OreDictionary.getOres(oreName)) { addItem(category, new InvTweaksItemTreeItem(name, i.itemID, i.getItemDamage(), order)); } oresRegistered.add(new OreDictInfo(category, name, oreName, order)); } private List<OreDictInfo> oresRegistered = new ArrayList<OreDictInfo>(); @ForgeSubscribe public void oreRegistered(OreDictionary.OreRegisterEvent ev) { for(OreDictInfo ore : oresRegistered) { if(ore.oreName.equals(ev.Name)) { addItem(ore.category, new InvTweaksItemTreeItem(ore.name, ev.Ore.itemID, ev.Ore.getItemDamage(), ore.order)); } } } }
Vexatos/inventory-tweaks
src/minecraft/invtweaks/InvTweaksItemTree.java
Java
mit
10,539
package gnu.expr; import gnu.bytecode.Type; import gnu.mapping.*; import gnu.text.Printable; import gnu.text.SourceLocator; import gnu.lists.Consumer; import java.io.PrintWriter; import gnu.kawa.util.IdentityHashTable; import gnu.kawa.reflect.OccurrenceType; /** * Abstract class for syntactic forms that evaluate to a value. * Scheme S-expressions get re-written to these before evaluation. * @author Per Bothner */ public abstract class Expression extends Procedure0 implements Printable, SourceLocator { public final Object eval (CallContext ctx) throws Throwable { int start = ctx.startFromContext(); try { match0(ctx); return ctx.getFromContext(start); } catch (Throwable ex) { ctx.cleanupFromContext(start); throw ex; } } public final Object eval (Environment env) throws Throwable { CallContext ctx = CallContext.getInstance(); Environment saveEnv = Environment.setSaveCurrent(env); try { return eval(ctx); } finally { Environment.restoreCurrent(saveEnv); } } protected abstract boolean mustCompile (); public final int match0 (CallContext ctx) { ctx.proc = this; ctx.pc = 0; return 0; } public final Object apply0 () throws Throwable { CallContext ctx = CallContext.getInstance(); check0(ctx); return ctx.runUntilValue(); } /** Evaluate the expression. * This is named apply rather than eval so it is compatible with the * full-tail-call calling convention, and we can stash an Expression in * CallContext's proc field. FIXME - are we making use of this? */ public void apply (CallContext ctx) throws Throwable { throw new RuntimeException ("internal error - " + getClass() + ".eval called"); } public final void print (Consumer out) { if (out instanceof OutPort) print((OutPort) out); else if (out instanceof PrintWriter) { OutPort port = new OutPort((PrintWriter) out); print(port); port.close(); } else { CharArrayOutPort port = new CharArrayOutPort(); print(port); port.close(); port.writeTo(out); } } public abstract void print (OutPort ps); /** * Print line and column number if specified. * This is a helper routineintended for use by print(OutPort). */ public void printLineColumn(OutPort out) { int line = getLineNumber(); if (line > 0) { out.print("line:"); out.print(line); int column = getColumnNumber(); if (column > 0) { out.print(':'); out.print(column); } out.writeSpaceFill(); } } public abstract void compile (Compilation comp, Target target); /** Same as compile, but emit line number beforehard. */ public final void compileWithPosition(Compilation comp, Target target) { int line = getLineNumber (); if (line > 0) { comp.getCode().putLineNumber(getFileName(), line); compileNotePosition(comp, target, this); } else compile(comp, target); } /** Same as 2-argument compileWithPosition, * but use some other Expression's line number. */ public final void compileWithPosition(Compilation comp, Target target, Expression position) { int line = position.getLineNumber (); if (line > 0) { comp.getCode().putLineNumber(position.getFileName(), line); compileNotePosition(comp, target, position); } else compile(comp, target); } /** Compile, but take note of line number. */ public final void compileNotePosition(Compilation comp, Target target, Expression position) { String saveFilename = comp.getFileName(); int saveLine = comp.getLineNumber(); int saveColumn = comp.getColumnNumber(); comp.setLine(position); compile(comp, target); // This might logically belong in a `finally' clause. // It is intentionally not so, so if there is an internal error causing // an exception, we get the line number where the exception was thrown. comp.setLine(saveFilename, saveLine, saveColumn); } public final void compile (Compilation comp, Type type) { // Should we use Target.pushValue instead? FIXME. compile (comp, StackTarget.getInstance(type)); } /** Compile an expression with checking suitable for a known Declaration. * Leaves the result on the stack (i.e. does not assign to the lhs). * It does coerce the value to a suitable type for the lhs, and * throw a hopefully-informative WrongType exception on failure. */ public final void compile (Compilation comp, Declaration lhs) { compile (comp, CheckedTarget.getInstance(lhs)); } /** Compile all but the first sub-"statement". * A kludge used for constructor methods, since if the first "statement" * is a super-constructor we need to inject initializer expressions. */ public static void compileButFirst (Expression exp, Compilation comp) { if (exp instanceof BeginExp) { BeginExp bexp = (BeginExp) exp; int n = bexp.length; if (n == 0) return; Expression[] exps = bexp.exps; compileButFirst(exps[0], comp); for (int i = 1; i < n; i++) exps[i].compileWithPosition(comp, Target.Ignore); } } /** Make a deep copy of this expression, if possible. * @param mapper used to lookup parts (expressions, declarations) * that have been translated in the parent. * Needed for copied Declarations and BlockExps. * @return a copy, or null if we can't copy. */ public static Expression deepCopy (Expression exp, IdentityHashTable mapper) { if (exp == null) return null; Object tr = mapper.get(exp); if (tr != null) return (Expression) tr; Expression copy = exp.deepCopy(mapper); mapper.put(exp, copy); return copy; } public static Expression[] deepCopy (Expression[] exps, IdentityHashTable mapper) { if (exps == null) return null; int nargs = exps.length; Expression[] a = new Expression[nargs]; for (int i = 0; i < nargs; i++) { Expression ei = exps[i]; Expression ai = deepCopy(ei, mapper); if (ai == null && ei != null) return null; a[i] = ai; } return a; } protected static Expression deepCopy (Expression exp) { return deepCopy(exp, new IdentityHashTable()); } protected Expression deepCopy (IdentityHashTable mapper) { return null; } protected <R,D> R visit (ExpVisitor<R,D> visitor, D d) { return visitor.visitExpression(this, d); } protected <R,D> void visitChildren (ExpVisitor<R,D> visitor, D d) { } /** Apply inlining transformations on a given ApplyExp. * Assumes the ApplyExp's function is this expression, * or can be optimized to this expression. * @param exp an application whose function expression can be simplified * to this expression. * @param visitor the context for the current inlining pass * @param decl if non-null, a Declaration bound to this expression. * @return an Expression equivalent to the passed-in exp. */ public Expression validateApply (ApplyExp exp, InlineCalls visitor, Type required, Declaration decl) { exp.args = visitor.visitExps(exp.args, null); return exp; } String filename; int position; public static final Expression[] noExpressions = new Expression[0]; /** Helper method to create a `while' statement. */ public static Expression makeWhile(Object cond, Object body, Compilation parser) { parser.loopStart(); parser.loopEnter(); parser.loopCond(parser.parse(cond)); parser.loopBody(parser.parse(body)); return parser.loopRepeat(); } /** Copies the current location. */ public final void setLocation (SourceLocator location) { this.filename = location.getFileName(); setLine(location.getLineNumber(), location.getColumnNumber()); } public final Expression setLine(Expression old) { setLocation(old); return this; } public final void setFile (String filename) { this.filename = filename; } public final void setLine (int lineno, int colno) { if (lineno < 0) lineno = 0; if (colno < 0) colno = 0; position = (lineno << 12) + colno; } public final void setLine (int lineno) { setLine (lineno, 0); } public final String getFileName () { return filename; } /** Set line number from current position in <code>Compilation</code>. */ public void setLine (Compilation comp) { int line = comp.getLineNumber(); if (line > 0) { setFile(comp.getFileName()); setLine(line, comp.getColumnNumber()); } } public String getPublicId () { return null; } public String getSystemId () { return filename; } /** Get the line number of (the start of) this Expression. * The "first" line is line 1; unknown is -1. */ public final int getLineNumber() { int line = position >> 12; return line == 0 ? -1 : line; } public final int getColumnNumber() { int column = position & ((1 << 12) - 1); return column == 0 ? -1 : column; } public boolean isStableSourceLocation() { return true; } protected Type type; /** Return the Type used to represent the values of this Expression. */ public final Type getType() { if (type == null) { type = Type.objectType; // to guard against cycles type = calculateType(); } return type; } protected Type calculateType () { return Type.pointer_type; } /** True if the expression provably never returns. * Currently, this is very limited, not handling infinite recursion * (tail- or otherwise), but better analysis is planned. */ public boolean neverReturns() { return getType() == Type.neverReturnsType; } public boolean isSingleValue() { return OccurrenceType.itemCountIsOne(getType()); } /** Return value if it is constant, or null if non-constant or unknown. */ public Object valueIfConstant () { return null; } protected int flags; public static final int VALIDATED = 1; protected static final int NEXT_AVAIL_FLAG = 2; public void setFlag (boolean setting, int flag) { if (setting) flags |= flag; else flags &= ~flag; } public void setFlag (int flag) { flags |= flag; } public int getFlags() { return flags; } public boolean getFlag (int flag) { return (flags & flag) != 0; } /** True if evaluating may have side-effects. */ public boolean side_effects () { return true; } public String toString () { String tname = getClass().getName(); if (tname.startsWith("gnu.expr.")) tname = tname.substring(9); return tname+"@"+Integer.toHexString(hashCode()); } }
alain91/kawa
gnu/expr/Expression.java
Java
mit
10,912
package tech.codemaster.kotlin.koans.util; public class YourOldJavaCodeUsingRunnable { public static void run(Runnable runnable) { runnable.run(); } }
xianrendzw/CodeMaster
codemaster-kotlin/src/main/kotlin/tech/codemaster/kotlin/koans/util/YourOldJavaCodeUsingRunnable.java
Java
mit
168
package hu.kazocsaba.math.matrix.backbone; import hu.kazocsaba.math.matrix.Matrix; import hu.kazocsaba.math.matrix.MatrixFactory; import hu.kazocsaba.math.matrix.SingularityException; /** * LU decomposition algorithm. Adapted from Jama. * @author Kazó Csaba */ class JamaLU { /* ------------------------ Class variables * ------------------------ */ /** Array for internal storage of decomposition. @serial internal array storage. */ private double[][] LU; /** Row and column dimensions, and pivot sign. @serial column dimension. @serial row dimension. @serial pivot sign. */ private int m, n, pivsign; /** Internal storage of pivot vector. @serial pivot vector. */ private int[] piv; /* ------------------------ Constructor * ------------------------ */ /** LU Decomposition @param A Rectangular matrix */ public JamaLU (Matrix A) { // Use a "left-looking", dot-product, Crout/Doolittle algorithm. LU = new double[A.getRowCount()][A.getColumnCount()]; for (int row=0; row<A.getRowCount(); row++) for (int col=0; col<A.getColumnCount(); col++) { LU[row][col]=A.getQuick(row, col); } m = A.getRowCount(); n = A.getColumnCount(); piv = new int[m]; for (int i = 0; i < m; i++) { piv[i] = i; } pivsign = 1; double[] LUrowi; double[] LUcolj = new double[m]; // Outer loop. for (int j = 0; j < n; j++) { // Make a copy of the j-th column to localize references. for (int i = 0; i < m; i++) { LUcolj[i] = LU[i][j]; } // Apply previous transformations. for (int i = 0; i < m; i++) { LUrowi = LU[i]; // Most of the time is spent in the following dot product. int kmax = Math.min(i,j); double s = 0.0; for (int k = 0; k < kmax; k++) { s += LUrowi[k]*LUcolj[k]; } LUrowi[j] = LUcolj[i] -= s; } // Find pivot and exchange if necessary. int p = j; for (int i = j+1; i < m; i++) { if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) { p = i; } } if (p != j) { for (int k = 0; k < n; k++) { double t = LU[p][k]; LU[p][k] = LU[j][k]; LU[j][k] = t; } int k = piv[p]; piv[p] = piv[j]; piv[j] = k; pivsign = -pivsign; } // Compute multipliers. if (j < m & LU[j][j] != 0.0) { for (int i = j+1; i < m; i++) { LU[i][j] /= LU[j][j]; } } } } /* ------------------------ Temporary, experimental code. ------------------------ *\ \** LU Decomposition, computed by Gaussian elimination. <P> This constructor computes L and U with the "daxpy"-based elimination algorithm used in LINPACK and MATLAB. In Java, we suspect the dot-product, Crout algorithm will be faster. We have temporarily included this constructor until timing experiments confirm this suspicion. <P> @param A Rectangular matrix @param linpackflag Use Gaussian elimination. Actual value ignored. @return Structure to access L, U and piv. *\ public LUDecomposition (Matrix A, int linpackflag) { // Initialize. LU = A.getArrayCopy(); m = A.getRowDimension(); n = A.getColumnDimension(); piv = new int[m]; for (int i = 0; i < m; i++) { piv[i] = i; } pivsign = 1; // Main loop. for (int k = 0; k < n; k++) { // Find pivot. int p = k; for (int i = k+1; i < m; i++) { if (Math.abs(LU[i][k]) > Math.abs(LU[p][k])) { p = i; } } // Exchange if necessary. if (p != k) { for (int j = 0; j < n; j++) { double t = LU[p][j]; LU[p][j] = LU[k][j]; LU[k][j] = t; } int t = piv[p]; piv[p] = piv[k]; piv[k] = t; pivsign = -pivsign; } // Compute multipliers and eliminate k-th column. if (LU[k][k] != 0.0) { for (int i = k+1; i < m; i++) { LU[i][k] /= LU[k][k]; for (int j = k+1; j < n; j++) { LU[i][j] -= LU[i][k]*LU[k][j]; } } } } } \* ------------------------ End of temporary code. * ------------------------ */ /* ------------------------ Public Methods * ------------------------ */ /** Is the matrix nonsingular? @return true if U, and hence A, is nonsingular. */ public boolean isNonsingular () { for (int j = 0; j < n; j++) { if (LU[j][j] == 0) return false; } return true; } /** Return lower triangular factor @return L */ public Matrix getL () { Matrix X = MatrixFactory.createMatrix(m,n); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i > j) { X.set(i, j, LU[i][j]); } else if (i == j) { X.set(i, j, 1); } } } return X; } /** Return upper triangular factor @return U */ public Matrix getU () { Matrix X = MatrixFactory.createMatrix(n,n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i <= j) { X.set(i, j, LU[i][j]); } } } return X; } /** Return pivot permutation vector @return piv */ public int[] getPivot () { int[] p = new int[m]; System.arraycopy(piv, 0, p, 0, m); return p; } /** Return pivot permutation vector as a one-dimensional double array @return (double) piv */ public double[] getDoublePivot () { double[] vals = new double[m]; for (int i = 0; i < m; i++) { vals[i] = (double) piv[i]; } return vals; } /** Determinant @return det(A) @exception IllegalArgumentException Matrix must be square */ public double det () { if (m != n) { throw new IllegalArgumentException("Matrix must be square."); } double d = (double) pivsign; for (int j = 0; j < n; j++) { d *= LU[j][j]; } return d; } /** Solve A*X = B @param B A Matrix with as many rows as A and any number of columns. @return X so that L*U*X = B(piv,:) @exception IllegalArgumentException Matrix row dimensions must agree. @exception SingularityException Matrix is singular. */ public Matrix solve (Matrix B) throws SingularityException { if (B.getRowCount() != m) { throw new IllegalArgumentException("Matrix row dimensions must agree."); } if (!this.isNonsingular()) { throw new SingularityException("Matrix is singular."); } // Copy right hand side with pivoting int nx = B.getColumnCount(); double[][] X = new double[piv.length][nx]; for (int i=0; i<piv.length; i++) { for (int j=0; j<nx; j++) { X[i][j]=B.getQuick(piv[i], j); } } // Solve L*Y = B(piv,:) for (int k = 0; k < n; k++) { for (int i = k+1; i < n; i++) { for (int j = 0; j < nx; j++) { X[i][j] -= X[k][j]*LU[i][k]; } } } // Solve U*X = Y; for (int k = n-1; k >= 0; k--) { for (int j = 0; j < nx; j++) { X[k][j] /= LU[k][k]; } for (int i = 0; i < k; i++) { for (int j = 0; j < nx; j++) { X[i][j] -= X[k][j]*LU[i][k]; } } } return MatrixFactory.createMatrix(X); } }
kazocsaba/matrix
src/main/java/hu/kazocsaba/math/matrix/backbone/JamaLU.java
Java
mit
7,829
// This file is automatically generated. package adila.db; /* * Samsung Galaxy Note 4 * * DEVICE: trlte * MODEL: SM-N910G */ final class trlte_sm2dn910g { public static final String DATA = "Samsung|Galaxy Note 4|Galaxy Note"; }
karim/adila
database/src/main/java/adila/db/trlte_sm2dn910g.java
Java
mit
239
/** * * created by Mr.Simple, Sep 5, 201411:09:38 AM. * Copyright (c) 2014, [email protected] All Rights Reserved. * * ##################################################### * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # * ##################################################### */ package com.example.xiongcen.myapplication.imageloader.utils; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.util.Log; /** * 封装先加载图片bound,计算出inSmallSize之后再加载图片的逻辑操作 * * @author mrsimple */ public abstract class BitmapDecoder { /** * @param options * @return */ public abstract Bitmap decodeBitmapWithOption(Options options); /** * @param width 图片的目标宽度 * @param height 图片的目标高度 * @return */ public final Bitmap decodeBitmap(int width, int height) { // 如果请求原图,则直接加载原图 if (width <= 0 || height <= 0) { return decodeBitmapWithOption(null); } // 1、获取只加载Bitmap宽高等数据的Option, 即设置options.inJustDecodeBounds = true; Options options = new Options(); // 设置为true,表示解析Bitmap对象,该对象不占内存 options.inJustDecodeBounds = true; // 2、通过options加载bitmap,此时返回的bitmap为空,数据将存储在options中 // decodeBitmapWithOption(options); // 3、计算缩放比例, 并且将options.inJustDecodeBounds设置为false; configBitmapOptions(options, width, height); // 4、通过options设置的缩放比例加载图片 return decodeBitmapWithOption(options); } /** * 加载原图 * * @return */ public Bitmap decodeOriginBitmap() { return decodeBitmapWithOption(null); } /** * @param options * @param width * @param height */ protected void configBitmapOptions(Options options, int width, int height) { // 设置缩放比例 options.inSampleSize = computeInSmallSize(options, width, height); Log.d("", "$## inSampleSize = " + options.inSampleSize + ", width = " + width + ", height= " + height); // 图片质量 options.inPreferredConfig = Config.RGB_565; // 设置为false,解析Bitmap对象加入到内存中 options.inJustDecodeBounds = false; options.inPurgeable = true; options.inInputShareable = true; } private int computeInSmallSize(Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and // width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, // this will guarantee a final image // with both dimensions larger than or equal to the requested // height and width. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; // This offers some additional logic in case the image has a strange // aspect ratio. For example, a panorama may have a much larger // width than height. In these cases the total pixels might still // end up being too large to fit comfortably in memory, so we should // be more aggressive with sample down the image (=larger // inSampleSize). final float totalPixels = width * height; // Anything more than 2x the requested pixels we'll sample down // further final float totalReqPixelsCap = reqWidth * reqHeight * 2; while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) { inSampleSize++; } } return inSampleSize; } }
xiongcen/WaveViewDemo
WaveViewDemo/src/main/java/com/example/xiongcen/myapplication/imageloader/utils/BitmapDecoder.java
Java
mit
5,961
package controllers; import static akka.pattern.Patterns.ask; import java.util.HashMap; import java.util.Map; import play.api.mvc.Session; import play.mvc.*; import com.fasterxml.jackson.databind.JsonNode; import views.html.*; import models.*; public class Application extends Controller { static Map<String, String> roomhost = new HashMap<String, String>(); /** * Display the home page. */ public static Result index() { String username = session("username"); if(username == null) return ok(index.render()); else return redirect(routes.Application.lobby()); } public static Result loginSubmit() { final Map<String, String[]> values = request().body().asFormUrlEncoded(); String username = values.get("username")[0]; if(username == null || username.trim().equals("")) { flash("error", "Please choose a valid username."); return redirect(routes.Application.index()); } else if(Lobby.isNameUsed(username)) { flash("error", "This username is already used."); return redirect(routes.Application.index()); } session("username", username); session("state", "lobby"); return redirect(routes.Application.lobby()); } public static Result disconnect() { String username = session("username"); String roomname = session("roomname"); String state = session("state"); Lobby.disconnect(session("username")); if(state.equals("gameRoom")) { GameRoom.defaultRoom.tell(new Messages.Leave(username, roomname), null); } else if(state.equals("game")) { Game.defaultRoom.tell(new Messages.Leave(username, roomname), null); } session().clear(); return redirect(routes.Application.index()); } /** * Display the chat room. */ public static Result lobby() { String username = session("username"); return ok(lobby.render(username)); } public static Result reLobby() { String username = session("username"); String roomname = session("roomname"); String state = session("state"); if(state.equals("gameRoom")) { GameRoom.defaultRoom.tell(new Messages.Leave(username, roomname), null); } else if(state.equals("game")) { Game.defaultRoom.tell(new Messages.Leave(username, roomname), null); } if(roomhost.get(roomname) != null) if(roomhost.get(roomname).equals(username)) roomhost.remove(roomname); return redirect(routes.Application.lobby()); } public static Result lobbyJs(String username) { return ok(views.js.lobby.render(username)); } public static Result gameRoom() { final Map<String, String[]> values = request().body().asFormUrlEncoded(); String game = values.get("game")[0]; String host = ""; String username = session("username"); //ChatRoom.defaultRoom.tell(new Messages.DisconnectWS(username), null); if(game.equals("Create_Game")) { GameRoom.game_list.put("test room", new GameRoom.GameRoomData("test room",username)); GameRoom.defaultRoom.tell(new Messages.CreateGame(username, "test room"), null); session("roomname", "test room"); host = username; roomhost.put("test room", host); } else { if(!GameRoom.game_list.containsKey("test room")) { flash("error", "Room doesn't exist."); return redirect(routes.Application.lobby()); } else if(GameRoom.game_list.get("test room").isFull()) { flash("error", "Room is full."); return redirect(routes.Application.lobby()); } else { GameRoom.defaultRoom.tell(new Messages.JoinGameRoom(username, "test room"), null); session("roomname", "test room"); } } session("state", "gameRoom"); return ok(gameRoom.render(username, "test room", host)); } public static Result gameRoomJs(String username, String host) { return ok(views.js.gameRoom.render(username, host)); } public static Result game() { String username = session("username"); String roomname = session("roomname"); if(username == roomhost.get(roomname)) GameRoom.defaultRoom.tell(new Messages.StartGame(username, roomname), null); session("state", "game"); return ok(game.render(username, roomhost.get(roomname))); } public static Result gameJs(String username, String host) { return ok(views.js.game.render(username, host)); } /** * Handle the chat websocket. */ public static WebSocket<JsonNode> chat(final String username) { return new WebSocket<JsonNode>() { // Called when the Websocket Handshake is done. public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out){ // Join the chat room. try { Lobby.join(username, in, out); } catch (Exception ex) { ex.printStackTrace(); } } }; } /** * Handle the chat websocket. */ public static WebSocket<JsonNode> gameRoomWS(final String username) { return new WebSocket<JsonNode>() { // Called when the Websocket Handshake is done. public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out){ // Join the chat room. try { GameRoom.join(username, in, out); } catch (Exception ex) { ex.printStackTrace(); } } }; } /** * Handle the chat websocket. */ public static WebSocket<JsonNode> gameWS(final String username) { return new WebSocket<JsonNode>() { // Called when the Websocket Handshake is done. public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out){ // Join the chat room. try { Game.join(username, in, out); } catch (Exception ex) { ex.printStackTrace(); } } }; } }
KreskiPPT/main
app/controllers/Application.java
Java
mit
5,479
package com.apssouza.eventsourcing.events; import com.apssouza.eventsourcing.entities.Email; import com.apssouza.infra.AbstractDomainEvent; import java.time.Instant; /** * Email delivered event * * @author apssouza */ public class EmailDeliveredEvent extends AbstractDomainEvent implements EmailEvent { private final String uuid; private final Instant when = Instant.now(); private final String type = "sent"; private final Email email; public EmailDeliveredEvent(String uuid, Email email) { this.uuid = uuid; this.email = email; } @Override public String uuid() { return uuid; } public String type() { return type; } @Override public Instant when() { return when; } @Override public Email getEmail() { return email; } }
apssouza22/java-microservice
mail-service/src/main/java/com/apssouza/eventsourcing/events/EmailDeliveredEvent.java
Java
mit
855
package br.com.project.checkskills.entities.dadosbasicos; import javax.persistence.AttributeOverride; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import org.springframework.stereotype.Component; import br.com.project.checkskills.utils.BaseEntity; @Entity @Table(name = "TB_ESCALA") @AttributeOverride(name = "id", column = @Column(name = "ID_ESCALA")) @Component(value="escalaEntity") public class EscalaEntity extends BaseEntity<Long>{ private static final long serialVersionUID = 1L; @Basic(optional = false) @Column(name = "NOME",nullable=false) private String nome; @Basic(optional = false) @Column(name = "VALOR",nullable=false) private int valor; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public int getValor() { return valor; } public void setValor(int valor) { this.valor = valor; } @Override public String toString() { return String.format("%s[id=%d]", getClass().getSimpleName(), getId()); } }
luan-analiseinfo/sistema-avaliacao-competencia
src/main/java/br/com/project/checkskills/entities/dadosbasicos/EscalaEntity.java
Java
mit
1,192
package br.edu.entidade; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; @Entity @NamedQueries({ @NamedQuery(name = "Assunto.findAll", query = "SELECT a FROM Assunto a"), @NamedQuery(name = "Assunto.findByDisciplina", query = "SELECT a FROM Assunto a WHERE a.disciplina = :disciplina_id"), @NamedQuery(name = "Assunto.update", query = "SELECT a FROM Assunto a WHERE a.idAssunto = :id_ssunto") }) @Table(name = "tb_assunto") @XmlRootElement(name = "assunto") public class Assunto { @Id @GeneratedValue @Column(name = "id_assunto") private int idAssunto; @Column(name = "nm_assunto", nullable = false) private String nomeAssunto; @ManyToOne @JoinColumn(name = "disciplina_id") private Disciplina disciplina; public Assunto() { disciplina = new Disciplina(); } public int getIdAssunto() { return idAssunto; } public void setIdAssunto(int idAssunto) { this.idAssunto = idAssunto; } public String getNomeAssunto() { return nomeAssunto; } public void setNomeAssunto(String nomeAssunto) { this.nomeAssunto = nomeAssunto; } public Disciplina getDisciplina() { return disciplina; } public void setDisciplina(Disciplina disciplina) { this.disciplina = disciplina; } }
LADOSSIFPB/EAV
EAV/src/br/edu/entidade/Assunto.java
Java
mit
1,593
package com.jaquadro.minecraft.extrabuttons.block; import com.jaquadro.minecraft.extrabuttons.ExtraButtons; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityMinecart; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import java.util.List; import java.util.Random; public class PlayerPoweredRail extends PlayerDetectorRail { @SideOnly(Side.CLIENT) private IIcon[] iconArray; public PlayerPoweredRail () { this.setTickRandomly(true); } @Override public void onEntityCollidedWithBlock (World world, int x, int y, int z, Entity entity) { if (!world.isRemote) { int data = world.getBlockMetadata(x, y, z); if ((data & 8) == 0) { this.setStateIfMinecartInteractsWithRail(world, x, y, z, data); } } } @Override public void updateTick (World world, int x, int y, int z, Random rand) { if (!world.isRemote) { int data = world.getBlockMetadata(x, y, z); if ((data & 8) != 0) { this.setStateIfMinecartInteractsWithRail(world, x, y, z, data); } } } private void setStateIfMinecartInteractsWithRail (World world, int x, int y, int z, int data) { boolean isPowerBitSet = (data & 8) != 0; boolean isValidTarget = false; float boundAdjust = 0.125F; List entities = world.getEntitiesWithinAABB(EntityMinecart.class, AxisAlignedBB.getBoundingBox((double) ((float) x + boundAdjust), (double) y, (double) ((float) z + boundAdjust), (double) ((float) (x + 1) - boundAdjust), (double) ((float) (y + 1) - boundAdjust), (double) ((float) (z + 1) - boundAdjust))); if (!entities.isEmpty()) { for (Object item : entities) { EntityMinecart minecart = (EntityMinecart) item; if (minecart.riddenByEntity != null) isValidTarget = true; } } if (isValidTarget && !isPowerBitSet) { world.setBlockMetadataWithNotify(x, y, z, data | 8, 3); world.notifyBlocksOfNeighborChange(x, y, z, this); world.notifyBlocksOfNeighborChange(x, y - 1, z, this); world.markBlockRangeForRenderUpdate(x, y, z, x, y, z); } if (!isValidTarget && isPowerBitSet) { world.setBlockMetadataWithNotify(x, y, z, data & 7, 3); world.notifyBlocksOfNeighborChange(x, y, z, this); world.notifyBlocksOfNeighborChange(x, y - 1, z, this); world.markBlockRangeForRenderUpdate(x, y, z, x, y, z); } if (isValidTarget) { world.scheduleBlockUpdate(x, y, z, this, this.tickRate(world)); } data = world.getBlockMetadata(x, y, z); for (Object item : entities) { EntityMinecart minecart = (EntityMinecart) item; if (minecart != null) updateMinecart(minecart, data); } } private void updateMinecart (EntityMinecart entity, int railData) { int direction = railData & 7; boolean isPoweredBitSet = (railData & 8) != 0; if (entity.shouldDoRailFunctions()) { int posX = MathHelper.floor_double(entity.posX); int posY = MathHelper.floor_double(entity.posY); int posZ = MathHelper.floor_double(entity.posZ); double motion = Math.sqrt(entity.motionX * entity.motionX + entity.motionZ * entity.motionZ); if (isPoweredBitSet) { if (motion > 0.01D) { double boost = 0.06D; entity.motionX += entity.motionX / motion * boost; entity.motionZ += entity.motionZ / motion * boost; } else if (direction == 1) { if (entity.worldObj.isBlockNormalCubeDefault(posX - 1, posY, posZ, true)) { entity.motionX = 0.04D; } else if (entity.worldObj.isBlockNormalCubeDefault(posX + 1, posY, posZ, true)) { entity.motionX = -0.04D; } } else if (direction == 0) { if (entity.worldObj.isBlockNormalCubeDefault(posX, posY, posZ - 1, true)) { entity.motionZ = 0.04D; } else if (entity.worldObj.isBlockNormalCubeDefault(posX, posY, posZ + 1, true)) { entity.motionZ = -0.04D; } } } else { if (motion < 0.03D) { entity.motionX *= 0.0D; entity.motionY *= 0.0D; entity.motionZ *= 0.0D; } else { entity.motionX *= 0.5D; entity.motionY *= 0.0D; entity.motionZ *= 0.5D; } } } } @SideOnly(Side.CLIENT) @Override public IIcon getIcon (int side, int data) { if ((data & 8) != 0) return iconArray[1]; else return iconArray[0]; } @SideOnly(Side.CLIENT) @Override public void registerBlockIcons(IIconRegister iconRegister) { iconArray = new IIcon[] { iconRegister.registerIcon(ExtraButtons.MOD_ID + ":player_powered_rail_off"), iconRegister.registerIcon(ExtraButtons.MOD_ID + ":player_powered_rail_on"), }; } }
jaquadro/ForgeMods
ExtraButtons/src/com/jaquadro/minecraft/extrabuttons/block/PlayerPoweredRail.java
Java
mit
5,777
package com.balanceball.controller; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Preferences; import com.badlogic.gdx.utils.IntArray; /** * Created by tijs on 18/07/2017. */ public class HighScoreController { // Warning, change this will break existing high scores! private static final String PREFERENCES_NAME = "preferences"; private static final String PREFERENCES_SCORE_NAME = "score_"; private static final String PREFERENCES_USER_NAME = "name"; public static final int MIN_NAME_LENGTH = 3; public static final int MAX_NAME_LENGTH = 12; private static int MAX_NR_SCORES = 100; public static IntArray fetchHighScores() { Preferences prefs = Gdx.app.getPreferences(PREFERENCES_NAME); IntArray scores = new IntArray(); for (int i = 0; i < MAX_NR_SCORES; i++) { int score = prefs.getInteger(PREFERENCES_SCORE_NAME + i, -1); if (score == -1) { break; } scores.add(score); } return scores; } public static void addHighScore(int score) { IntArray scores = fetchHighScores(); scores.add(score); scores.sort(); scores.reverse(); Preferences prefs = Gdx.app.getPreferences(PREFERENCES_NAME); for (int i = 0; i < Math.min(scores.size, MAX_NR_SCORES); ++i) { prefs.putInteger(PREFERENCES_SCORE_NAME + i, scores.get(i)); } prefs.flush(); } public static void setUserName(String name) { Preferences prefs = Gdx.app.getPreferences(PREFERENCES_NAME); // make sure the name is correct if (name.length() < MIN_NAME_LENGTH) { name = name + "---"; } else if (name.length() > MAX_NAME_LENGTH){ name += name.substring(0, MAX_NAME_LENGTH - 1); } prefs.putString(PREFERENCES_USER_NAME, name.trim()); prefs.flush(); } public static String getUserName() { Preferences prefs = Gdx.app.getPreferences(PREFERENCES_NAME); return prefs.getString(PREFERENCES_USER_NAME, null); } }
tgobbens/fluffybalance
core/src/com/balanceball/controller/HighScoreController.java
Java
mit
2,123
import java.util.*; public class UnweightedGraph<V> extends AbstractGraph<V> { /** Construct an empty graph */ public UnweightedGraph() { } /** Construct a graph from vertices and edges stored in arrays */ public UnweightedGraph(V[] vertices, int[][] edges) { super(vertices, edges); } /** Construct a graph from vertices and edges stored in List */ public UnweightedGraph(List<V> vertices, List<Edge> edges) { super(vertices, edges); } /** Construct a graph for interger vertices 0, 1, 2 and edge list */ public UnweightedGraph(List<Edge> edges, int numberOfVertices) { super(edges, numberOfVertices); } /** Construct a graph from integer vertices 0, 1, and edge array */ public UnweightedGraph(int[][] edges, int numberOfVertices) { super(edges, numberOfVertices); } }
jsquared21/Intro-to-Java-Programming
Exercise_28/Exercise_28_01/UnweightedGraph.java
Java
mit
798
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.loganalytics.v2020_08_01.implementation; import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; import com.microsoft.azure.CloudException; import com.microsoft.azure.management.loganalytics.v2020_08_01.DataSourceType; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceFuture; import com.microsoft.rest.ServiceResponse; import com.microsoft.rest.Validator; import java.io.IOException; import java.util.List; import okhttp3.ResponseBody; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.HTTP; import retrofit2.http.Path; import retrofit2.http.PUT; import retrofit2.http.Query; import retrofit2.Response; import rx.functions.Func1; import rx.Observable; /** * An instance of this class provides access to all the operations defined * in LinkedStorageAccounts. */ public class LinkedStorageAccountsInner { /** The Retrofit service to perform REST calls. */ private LinkedStorageAccountsService service; /** The service client containing this operation class. */ private OperationalInsightsManagementClientImpl client; /** * Initializes an instance of LinkedStorageAccountsInner. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public LinkedStorageAccountsInner(Retrofit retrofit, OperationalInsightsManagementClientImpl client) { this.service = retrofit.create(LinkedStorageAccountsService.class); this.client = client; } /** * The interface defining all the services for LinkedStorageAccounts to be * used by Retrofit to perform actually REST calls. */ interface LinkedStorageAccountsService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.loganalytics.v2020_08_01.LinkedStorageAccounts createOrUpdate" }) @PUT("subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/linkedStorageAccounts/{dataSourceType}") Observable<Response<ResponseBody>> createOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("workspaceName") String workspaceName, @Path("dataSourceType") DataSourceType dataSourceType1, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body LinkedStorageAccountsResourceInner parameters, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.loganalytics.v2020_08_01.LinkedStorageAccounts delete" }) @HTTP(path = "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/linkedStorageAccounts/{dataSourceType}", method = "DELETE", hasBody = true) Observable<Response<ResponseBody>> delete(@Path("resourceGroupName") String resourceGroupName, @Path("workspaceName") String workspaceName, @Path("dataSourceType") DataSourceType dataSourceType1, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.loganalytics.v2020_08_01.LinkedStorageAccounts get" }) @GET("subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/linkedStorageAccounts/{dataSourceType}") Observable<Response<ResponseBody>> get(@Path("resourceGroupName") String resourceGroupName, @Path("workspaceName") String workspaceName, @Path("dataSourceType") DataSourceType dataSourceType1, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.loganalytics.v2020_08_01.LinkedStorageAccounts listByWorkspace" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.OperationalInsights/workspaces/{workspaceName}/linkedStorageAccounts") Observable<Response<ResponseBody>> listByWorkspace(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("workspaceName") String workspaceName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } /** * Create or Update a link relation between current workspace and a group of storage accounts of a specific data source type. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the LinkedStorageAccountsResourceInner object if successful. */ public LinkedStorageAccountsResourceInner createOrUpdate(String resourceGroupName, String workspaceName, DataSourceType dataSourceType) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, workspaceName, dataSourceType).toBlocking().single().body(); } /** * Create or Update a link relation between current workspace and a group of storage accounts of a specific data source type. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<LinkedStorageAccountsResourceInner> createOrUpdateAsync(String resourceGroupName, String workspaceName, DataSourceType dataSourceType, final ServiceCallback<LinkedStorageAccountsResourceInner> serviceCallback) { return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, workspaceName, dataSourceType), serviceCallback); } /** * Create or Update a link relation between current workspace and a group of storage accounts of a specific data source type. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the LinkedStorageAccountsResourceInner object */ public Observable<LinkedStorageAccountsResourceInner> createOrUpdateAsync(String resourceGroupName, String workspaceName, DataSourceType dataSourceType) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, workspaceName, dataSourceType).map(new Func1<ServiceResponse<LinkedStorageAccountsResourceInner>, LinkedStorageAccountsResourceInner>() { @Override public LinkedStorageAccountsResourceInner call(ServiceResponse<LinkedStorageAccountsResourceInner> response) { return response.body(); } }); } /** * Create or Update a link relation between current workspace and a group of storage accounts of a specific data source type. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the LinkedStorageAccountsResourceInner object */ public Observable<ServiceResponse<LinkedStorageAccountsResourceInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String workspaceName, DataSourceType dataSourceType) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (workspaceName == null) { throw new IllegalArgumentException("Parameter workspaceName is required and cannot be null."); } if (dataSourceType == null) { throw new IllegalArgumentException("Parameter dataSourceType is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } final List<String> storageAccountIds = null; LinkedStorageAccountsResourceInner parameters = new LinkedStorageAccountsResourceInner(); parameters.withStorageAccountIds(null); return service.createOrUpdate(resourceGroupName, workspaceName, dataSourceType, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LinkedStorageAccountsResourceInner>>>() { @Override public Observable<ServiceResponse<LinkedStorageAccountsResourceInner>> call(Response<ResponseBody> response) { try { ServiceResponse<LinkedStorageAccountsResourceInner> clientResponse = createOrUpdateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } /** * Create or Update a link relation between current workspace and a group of storage accounts of a specific data source type. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @param storageAccountIds Linked storage accounts resources ids. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the LinkedStorageAccountsResourceInner object if successful. */ public LinkedStorageAccountsResourceInner createOrUpdate(String resourceGroupName, String workspaceName, DataSourceType dataSourceType, List<String> storageAccountIds) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, workspaceName, dataSourceType, storageAccountIds).toBlocking().single().body(); } /** * Create or Update a link relation between current workspace and a group of storage accounts of a specific data source type. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @param storageAccountIds Linked storage accounts resources ids. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<LinkedStorageAccountsResourceInner> createOrUpdateAsync(String resourceGroupName, String workspaceName, DataSourceType dataSourceType, List<String> storageAccountIds, final ServiceCallback<LinkedStorageAccountsResourceInner> serviceCallback) { return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, workspaceName, dataSourceType, storageAccountIds), serviceCallback); } /** * Create or Update a link relation between current workspace and a group of storage accounts of a specific data source type. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @param storageAccountIds Linked storage accounts resources ids. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the LinkedStorageAccountsResourceInner object */ public Observable<LinkedStorageAccountsResourceInner> createOrUpdateAsync(String resourceGroupName, String workspaceName, DataSourceType dataSourceType, List<String> storageAccountIds) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, workspaceName, dataSourceType, storageAccountIds).map(new Func1<ServiceResponse<LinkedStorageAccountsResourceInner>, LinkedStorageAccountsResourceInner>() { @Override public LinkedStorageAccountsResourceInner call(ServiceResponse<LinkedStorageAccountsResourceInner> response) { return response.body(); } }); } /** * Create or Update a link relation between current workspace and a group of storage accounts of a specific data source type. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @param storageAccountIds Linked storage accounts resources ids. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the LinkedStorageAccountsResourceInner object */ public Observable<ServiceResponse<LinkedStorageAccountsResourceInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String workspaceName, DataSourceType dataSourceType, List<String> storageAccountIds) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (workspaceName == null) { throw new IllegalArgumentException("Parameter workspaceName is required and cannot be null."); } if (dataSourceType == null) { throw new IllegalArgumentException("Parameter dataSourceType is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } Validator.validate(storageAccountIds); LinkedStorageAccountsResourceInner parameters = new LinkedStorageAccountsResourceInner(); parameters.withStorageAccountIds(storageAccountIds); return service.createOrUpdate(resourceGroupName, workspaceName, dataSourceType, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LinkedStorageAccountsResourceInner>>>() { @Override public Observable<ServiceResponse<LinkedStorageAccountsResourceInner>> call(Response<ResponseBody> response) { try { ServiceResponse<LinkedStorageAccountsResourceInner> clientResponse = createOrUpdateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<LinkedStorageAccountsResourceInner> createOrUpdateDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<LinkedStorageAccountsResourceInner, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<LinkedStorageAccountsResourceInner>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Deletes all linked storage accounts of a specific data source type associated with the specified workspace. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void delete(String resourceGroupName, String workspaceName, DataSourceType dataSourceType) { deleteWithServiceResponseAsync(resourceGroupName, workspaceName, dataSourceType).toBlocking().single().body(); } /** * Deletes all linked storage accounts of a specific data source type associated with the specified workspace. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> deleteAsync(String resourceGroupName, String workspaceName, DataSourceType dataSourceType, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, workspaceName, dataSourceType), serviceCallback); } /** * Deletes all linked storage accounts of a specific data source type associated with the specified workspace. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<Void> deleteAsync(String resourceGroupName, String workspaceName, DataSourceType dataSourceType) { return deleteWithServiceResponseAsync(resourceGroupName, workspaceName, dataSourceType).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Deletes all linked storage accounts of a specific data source type associated with the specified workspace. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String workspaceName, DataSourceType dataSourceType) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (workspaceName == null) { throw new IllegalArgumentException("Parameter workspaceName is required and cannot be null."); } if (dataSourceType == null) { throw new IllegalArgumentException("Parameter dataSourceType is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.delete(resourceGroupName, workspaceName, dataSourceType, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() { @Override public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) { try { ServiceResponse<Void> clientResponse = deleteDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Void> deleteDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<Void, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<Void>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Gets all linked storage account of a specific data source type associated with the specified workspace. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the LinkedStorageAccountsResourceInner object if successful. */ public LinkedStorageAccountsResourceInner get(String resourceGroupName, String workspaceName, DataSourceType dataSourceType) { return getWithServiceResponseAsync(resourceGroupName, workspaceName, dataSourceType).toBlocking().single().body(); } /** * Gets all linked storage account of a specific data source type associated with the specified workspace. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<LinkedStorageAccountsResourceInner> getAsync(String resourceGroupName, String workspaceName, DataSourceType dataSourceType, final ServiceCallback<LinkedStorageAccountsResourceInner> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, workspaceName, dataSourceType), serviceCallback); } /** * Gets all linked storage account of a specific data source type associated with the specified workspace. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the LinkedStorageAccountsResourceInner object */ public Observable<LinkedStorageAccountsResourceInner> getAsync(String resourceGroupName, String workspaceName, DataSourceType dataSourceType) { return getWithServiceResponseAsync(resourceGroupName, workspaceName, dataSourceType).map(new Func1<ServiceResponse<LinkedStorageAccountsResourceInner>, LinkedStorageAccountsResourceInner>() { @Override public LinkedStorageAccountsResourceInner call(ServiceResponse<LinkedStorageAccountsResourceInner> response) { return response.body(); } }); } /** * Gets all linked storage account of a specific data source type associated with the specified workspace. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param dataSourceType Linked storage accounts type. Possible values include: 'CustomLogs', 'AzureWatson', 'Query', 'Alerts' * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the LinkedStorageAccountsResourceInner object */ public Observable<ServiceResponse<LinkedStorageAccountsResourceInner>> getWithServiceResponseAsync(String resourceGroupName, String workspaceName, DataSourceType dataSourceType) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (workspaceName == null) { throw new IllegalArgumentException("Parameter workspaceName is required and cannot be null."); } if (dataSourceType == null) { throw new IllegalArgumentException("Parameter dataSourceType is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.get(resourceGroupName, workspaceName, dataSourceType, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LinkedStorageAccountsResourceInner>>>() { @Override public Observable<ServiceResponse<LinkedStorageAccountsResourceInner>> call(Response<ResponseBody> response) { try { ServiceResponse<LinkedStorageAccountsResourceInner> clientResponse = getDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<LinkedStorageAccountsResourceInner> getDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<LinkedStorageAccountsResourceInner, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<LinkedStorageAccountsResourceInner>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Gets all linked storage accounts associated with the specified workspace, storage accounts will be sorted by their data source type. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the List&lt;LinkedStorageAccountsResourceInner&gt; object if successful. */ public List<LinkedStorageAccountsResourceInner> listByWorkspace(String resourceGroupName, String workspaceName) { return listByWorkspaceWithServiceResponseAsync(resourceGroupName, workspaceName).toBlocking().single().body(); } /** * Gets all linked storage accounts associated with the specified workspace, storage accounts will be sorted by their data source type. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<LinkedStorageAccountsResourceInner>> listByWorkspaceAsync(String resourceGroupName, String workspaceName, final ServiceCallback<List<LinkedStorageAccountsResourceInner>> serviceCallback) { return ServiceFuture.fromResponse(listByWorkspaceWithServiceResponseAsync(resourceGroupName, workspaceName), serviceCallback); } /** * Gets all linked storage accounts associated with the specified workspace, storage accounts will be sorted by their data source type. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the List&lt;LinkedStorageAccountsResourceInner&gt; object */ public Observable<List<LinkedStorageAccountsResourceInner>> listByWorkspaceAsync(String resourceGroupName, String workspaceName) { return listByWorkspaceWithServiceResponseAsync(resourceGroupName, workspaceName).map(new Func1<ServiceResponse<List<LinkedStorageAccountsResourceInner>>, List<LinkedStorageAccountsResourceInner>>() { @Override public List<LinkedStorageAccountsResourceInner> call(ServiceResponse<List<LinkedStorageAccountsResourceInner>> response) { return response.body(); } }); } /** * Gets all linked storage accounts associated with the specified workspace, storage accounts will be sorted by their data source type. * * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param workspaceName The name of the workspace. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the List&lt;LinkedStorageAccountsResourceInner&gt; object */ public Observable<ServiceResponse<List<LinkedStorageAccountsResourceInner>>> listByWorkspaceWithServiceResponseAsync(String resourceGroupName, String workspaceName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (workspaceName == null) { throw new IllegalArgumentException("Parameter workspaceName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } return service.listByWorkspace(this.client.subscriptionId(), resourceGroupName, workspaceName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<LinkedStorageAccountsResourceInner>>>>() { @Override public Observable<ServiceResponse<List<LinkedStorageAccountsResourceInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<LinkedStorageAccountsResourceInner>> result = listByWorkspaceDelegate(response); List<LinkedStorageAccountsResourceInner> items = null; if (result.body() != null) { items = result.body().items(); } ServiceResponse<List<LinkedStorageAccountsResourceInner>> clientResponse = new ServiceResponse<List<LinkedStorageAccountsResourceInner>>(items, result.response()); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<LinkedStorageAccountsResourceInner>> listByWorkspaceDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<LinkedStorageAccountsResourceInner>, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<LinkedStorageAccountsResourceInner>>() { }.getType()) .registerError(CloudException.class) .build(response); } }
selvasingh/azure-sdk-for-java
sdk/loganalytics/mgmt-v2020_08_01/src/main/java/com/microsoft/azure/management/loganalytics/v2020_08_01/implementation/LinkedStorageAccountsInner.java
Java
mit
35,832
package org.multij.model; import javax.lang.model.element.ExecutableElement; import java.util.List; public abstract class DecisionTree { public static interface Visitor { public void visitDecision(DecisionTree.DecisionNode node); public void visitAmbiguity(DecisionTree.AmbiguityNode node); public void visitCondition(DecisionTree.ConditionNode node); } public static final class DecisionNode extends DecisionTree { private final ExecutableElement definition; public DecisionNode(ExecutableElement definition) { this.definition = definition; } public ExecutableElement getDefinition() { return definition; } public void accept(DecisionTree.Visitor visitor) { visitor.visitDecision(this); } @Override public String toString() { return "DecisionNode(" + definition + ")"; } } public static final class AmbiguityNode extends DecisionTree { private final List<ExecutableElement> definitions; public AmbiguityNode(List<ExecutableElement> definitions) { this.definitions = definitions; } public List<ExecutableElement> getDefinitions() { return definitions; } public void accept(DecisionTree.Visitor visitor) { visitor.visitAmbiguity(this); } @Override public String toString() { return "AmbiguityNode(" + definitions + ")"; } } public static final class ConditionNode extends DecisionTree { private final Condition condition; private final DecisionTree isTrue; private final DecisionTree isFalse; public ConditionNode(Condition condition, DecisionTree isTrue, DecisionTree isFalse) { this.condition = condition; this.isTrue = isTrue; this.isFalse = isFalse; } public Condition getCondition() { return condition; } public DecisionTree getIsTrue() { return isTrue; } public DecisionTree getIsFalse() { return isFalse; } public void accept(DecisionTree.Visitor visitor) { visitor.visitCondition(this); } @Override public String toString() { return "ConditionNode(" + condition + ", " + isTrue + ", " + isFalse + ")"; } } private DecisionTree() { } public abstract void accept(DecisionTree.Visitor visitor); }
gustavcedersjo/multij
multij-processor/src/main/java/org/multij/model/DecisionTree.java
Java
mit
2,162
package org.commacq.client; import org.commacq.layer.SubscribeLayer; /** * Simple implementation of a BeanCacheFactory which just delegates * to a CsvDataSourceFactory and then wires the bean cache up with the * csv data source. */ public class BeanCacheFactoryCsvDataSourceFactory implements BeanCacheFactory { final SubscribeLayer layer; final CsvToBeanConverterFactory csvToBeanConverterFactory; public BeanCacheFactoryCsvDataSourceFactory(SubscribeLayer layer, CsvToBeanConverterFactory csvToBeanConverterFactory) { this.layer = layer; this.csvToBeanConverterFactory = csvToBeanConverterFactory; } @Override public BeanCache<?> createBeanCache(String entityId) throws Exception { CsvToBeanConverter<?> csvToBeanConverter; try { csvToBeanConverter = csvToBeanConverterFactory.getCsvBeanConverter(entityId); } catch (ClassNotFoundException ex) { throw new RuntimeException("Could not find bean class", ex); } BeanCache<?> beanCache = new BeanCache<>(layer, entityId, csvToBeanConverter); return beanCache; } @Override public <BeanType> BeanCache<BeanType> createBeanCache(String entityId, Class<BeanType> beanType) throws Exception { CsvToBeanConverter<BeanType> csvToBeanConverter = csvToBeanConverterFactory.getCsvBeanConverter(entityId, beanType); BeanCache<BeanType> beanCache = new BeanCache<>(layer, entityId, csvToBeanConverter); return beanCache; } }
daveboden/CommaCQ
client/src/main/java/org/commacq/client/BeanCacheFactoryCsvDataSourceFactory.java
Java
mit
1,411
/* * MIT License * * Copyright (c) 2018 Asynchronous Game Query Library * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.ibasco.agql.core.exceptions; public class InvalidPacketException extends ResponseProcessingException { public InvalidPacketException() { super(); } public InvalidPacketException(String message) { super(message); } public InvalidPacketException(String message, Throwable cause) { super(message, cause); } public InvalidPacketException(Throwable cause) { super(cause); } public InvalidPacketException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
ribasco/async-gamequery-lib
core/src/main/java/com/ibasco/agql/core/exceptions/InvalidPacketException.java
Java
mit
1,808
package space.cyberworlds.ljpostj; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
electrodyssey/ljpostj
ljpostj/src/test/java/space/cyberworlds/ljpostj/AppTest.java
Java
mit
653
package org.pbrt.openexr.types; import org.pbrt.openexr.header.Attribute; import org.pbrt.openexr.util.DataReader; /** * Copyright (c) Bartosz Zaczynski, 2010 * http://syntaxcandy.blogspot.com */ public class EnvMap extends Attribute { public String value; public EnvMap(DataReader data) { switch(data.readByte()) { case 0: value = "ENVMAP_LATLONG"; break; case 1: value = "ENVMAP_CUBE"; break; default: value = "?"; } } @Override public String toString() { return name + " = " + value; } }
rweyrauch/PBrtJ
src/main/java/org/pbrt/openexr/types/EnvMap.java
Java
mit
522
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.core.tests; import io.github.nucleuspowered.nucleus.core.Util; import org.junit.Ignore; import org.spongepowered.api.world.server.ServerLocation; import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.math.vector.Vector2d; import org.spongepowered.math.vector.Vector3d; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.Mockito; import org.spongepowered.api.world.border.WorldBorder; import java.time.Duration; import java.util.Arrays; public class UtilTests { @SuppressWarnings("CanBeFinal") @RunWith(Parameterized.class) public static class WorldBorderTests { @Parameterized.Parameters(name = "{index}: Co-ords ({0}, {1}, {2}), border centre ({3}, {4}, {5}), diameter: {6}, expecting {7}") public static Iterable<Object[]> data() { return Arrays.asList(new Object[][]{ {0, 0, 0, 0, 0, 0, 10, true}, {20, 0, 0, 0, 0, 0, 10, false}, {0, 20, 0, 0, 0, 0, 10, true}, {20, 0, 20, 0, 0, 0, 10, false}, {0, 0, 20, 0, 0, 0, 10, false}, {4, 0, 4, 0, 0, 0, 10, true}, {5, 0, 5, 0, 0, 0, 10, true}, {5, 0, 5, 0, 20, 0, 10, true}, {6, 0, 5, 0, 20, 0, 10, false}, {5, 0, 5, 500, 0, 0, 10, false}, {499, 0, 5, 500, 0, 0, 10, true}, {499, 0, 500, 500, 0, 0, 10, false} }); } @Parameterized.Parameter() public double x; @Parameterized.Parameter(1) public double y; @Parameterized.Parameter(2) public double z; @Parameterized.Parameter(3) public double borderX; @Parameterized.Parameter(4) public double borderY; @Parameterized.Parameter(5) public double borderZ; @Parameterized.Parameter(6) public double dia; @Parameterized.Parameter(7) public boolean result; private WorldBorder getBorder() { return new WorldBorder() { @Override public Vector2d center() { return null; } @Override public double diameter() { return 0; } @Override public double targetDiameter() { return 0; } @Override public Duration timeUntilTargetDiameter() { return null; } @Override public double safeZone() { return 0; } @Override public double damagePerBlock() { return 0; } @Override public Duration warningTime() { return null; } @Override public int warningDistance() { return 0; } }; } @Test @Ignore public void testInWorldBorder() { final WorldBorder wb = this.getBorder(); final ServerWorld world = Mockito.mock(ServerWorld.class); Mockito.when(world.properties().worldBorder()).thenReturn(wb); final ServerLocation lw = Mockito.mock(ServerLocation.class); Mockito.when(lw.world()).thenReturn(world); Mockito.when(lw.position()).thenReturn(new Vector3d(this.x, this.y, this.z)); Assert.assertEquals(this.result, Util.isLocationInWorldBorder(lw)); } } }
NucleusPowered/Nucleus
nucleus-core/src/test/java/io/github/nucleuspowered/nucleus/core/tests/UtilTests.java
Java
mit
3,855
package springcourse.exercises.exercise4.dao.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import springcourse.exercises.exercise4.dao.api.IBookDao; import springcourse.exercises.exercise4.model.Book; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author Amit Tal * @since 3/24/14 */ @Repository public class BookInMemoryDao implements IBookDao { private Logger logger = LoggerFactory.getLogger(BookInMemoryDao.class); private ConcurrentHashMap<String, Book> books; private ConcurrentHashMap<String, String> loanedBooks; public BookInMemoryDao() { books = new ConcurrentHashMap<String, Book>(); loanedBooks = new ConcurrentHashMap<String, String>(); } @Override public boolean checkConnection() { logger.info("The connection is stable"); return true; } @Override public Book addBook(Book book) { if (book.getGenre() == null) { throw new IllegalArgumentException("Genre cannot be null"); } books.put(book.getCatalogId(), book); logger.info("Added book: {}", book); return book; } @Override public void removeBook(String catalogId) { Book book = books.remove(catalogId); logger.info("Removed book: {}", book); if (book == null) { throw new IllegalArgumentException("Cannot remove book " + catalogId + " since it does not exist"); } } @Override public Collection<Book> getAllBooks() { return books.values(); } @Override public Book loanBook(String catalogId, String memberId) { Book book = books.get(catalogId); if (book == null) { throw new IllegalArgumentException("Book " + catalogId + " does not exist"); } if (loanedBooks.containsKey(catalogId)) { throw new IllegalStateException("Book already loaned"); } loanedBooks.put(catalogId, memberId); logger.info("member {} has loaned book {}", memberId, book); return book; } @Override public String returnBook(String catalogId) { String memberId = loanedBooks.remove(catalogId); logger.info("member {} has returned book {}", memberId, catalogId); return memberId; } @Override public Collection<Book> getLoanedBooks(String memberId) { Collection<Book> myBooks = new ArrayList<Book>(); for (Map.Entry<String, String> entry : loanedBooks.entrySet()) { if (entry.getValue().equals(memberId)) { myBooks.add(books.get(entry.getKey())); } } return myBooks; } }
amitt03/spring-course-exercise-4
exercise/src/main/java/springcourse/exercises/exercise4/dao/impl/BookInMemoryDao.java
Java
mit
2,793
package com.microsoft.azure.documentdb; import org.apache.commons.lang3.text.WordUtils; import org.json.JSONObject; public final class SpatialIndex extends Index { /** * Initializes a new instance of the SpatialIndex class. * * Here is an example to instantiate SpatialIndex class passing in the DataType * * <pre> * {@code * * SpatialIndex spatialIndex = new SpatialIndex(DataType.Point); * * } * </pre> * * @param dataType specifies the target data type for the index path specification. */ public SpatialIndex(DataType dataType) { super(IndexKind.Spatial); this.setDataType(dataType); } /** * Initializes a new instance of the SpatialIndex class. * * @param jsonString the json string that represents the index. */ public SpatialIndex(String jsonString) { super(jsonString, IndexKind.Spatial); if (this.getDataType() == null) { throw new IllegalArgumentException("The jsonString doesn't contain a valid 'dataType'."); } } /** * Initializes a new instance of the SpatialIndex class. * * @param jsonObject the json object that represents the index. */ public SpatialIndex(JSONObject jsonObject) { super(jsonObject, IndexKind.Spatial); if (this.getDataType() == null) { throw new IllegalArgumentException("The jsonObject doesn't contain a valid 'dataType'."); } } /** * Gets data type. * * @return the data type. */ public DataType getDataType() { DataType result = null; try { result = DataType.valueOf(WordUtils.capitalize(super.getString(Constants.Properties.DATA_TYPE))); } catch(IllegalArgumentException e) { e.printStackTrace(); } return result; } /** * Sets data type. * * @param dataType the data type. */ public void setDataType(DataType dataType) { super.set(Constants.Properties.DATA_TYPE, dataType.name()); } }
rnagpal/azure-documentdb-java
src/com/microsoft/azure/documentdb/SpatialIndex.java
Java
mit
2,109
package org.sistcoop.socio.models; import java.math.BigDecimal; import java.util.Date; public interface InteresGeneradoCuentaPersonalModel extends Model { String getId(); CuentaPersonalModel getCuentaPersonal(); BigDecimal getCapital(); BigDecimal getInteresGenerado(); Date getFecha(); }
sistcoop/socio
socio-model/socio-model-api/src/main/java/org/sistcoop/socio/models/InteresGeneradoCuentaPersonalModel.java
Java
mit
317
package com.bullhornsdk.data.model.response.list; import com.bullhornsdk.data.model.entity.core.paybill.invoice.InvoiceStatementDiscount; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"data", "count", "start"}) public class InvoiceStatementDiscountListWrapper extends StandardListWrapper<InvoiceStatementDiscount> { }
bullhorn/sdk-rest
src/main/java/com/bullhornsdk/data/model/response/list/InvoiceStatementDiscountListWrapper.java
Java
mit
450
/** * */ package edu.incense.designer.task; /** * @author mxpxgx * */ public class CustomizableFilter extends Task { private static final long serialVersionUID = -3002842093326677272L; private String userCode = "Empty"; /** * @param userCode */ public CustomizableFilter() { setType(TaskType.CustomizableFilter.toString()); } /** * @return the userCode */ public String getUserCode() { return userCode; } /** * @param userCode the userCode to set */ public void setUserCode(String userCode) { this.userCode = userCode; } }
mxpxgx/InCense-Designer
src/edu/incense/designer/task/CustomizableFilter.java
Java
mit
636
package dejv.jfx.radialmenu.event; import javafx.event.ActionEvent; import javafx.geometry.Point2D; import javafx.scene.Node; /** * An object, that is being sent as {@link ActionEvent#getSource()} into actions, triggered by Radial Menu items. * <p> * * @author dejv78 (http://dejv78.github.io) * @since 1.0.0 */ public class RadialMenuEventSource { private final Point2D menuTriggerCoords; private final Node targetNode; public RadialMenuEventSource(Point2D menuTriggerCoords, Node targetNode) { this.menuTriggerCoords = menuTriggerCoords; this.targetNode = targetNode; } /** * @return Location, at which the RadialMenu was triggered to display. * @see dejv.jfx.radialmenu.ContextRadialMenu#showAt(Node, double, double) */ public Point2D getMenuTriggerCoords() { return menuTriggerCoords; } /** * @return Action target node. * @see dejv.jfx.radialmenu.ContextRadialMenu#showOver(Node) * @see dejv.jfx.radialmenu.ContextRadialMenu#showAt(Node, double, double) */ public Node getTargetNode() { return targetNode; } }
dejv78/jfx.radialmenu
radialmenu/src/main/java/dejv/jfx/radialmenu/event/RadialMenuEventSource.java
Java
mit
1,137
/* * Copyright 2002-2016 the original author or 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 org.springframework.mock.web; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.BeanUtils; import org.springframework.util.Assert; import org.springframework.web.util.WebUtils; /** * Mock implementation of the {@link AsyncContext} interface. * * @author Rossen Stoyanchev * @since 3.2 */ public class MockAsyncContext implements AsyncContext { private final HttpServletRequest request; private final HttpServletResponse response; private final List<AsyncListener> listeners = new ArrayList<>(); private String dispatchedPath; private long timeout = 10 * 1000L; // 10 seconds is Tomcat's default private final List<Runnable> dispatchHandlers = new ArrayList<>(); public MockAsyncContext(ServletRequest request, ServletResponse response) { this.request = (HttpServletRequest) request; this.response = (HttpServletResponse) response; } public void addDispatchHandler(Runnable handler) { Assert.notNull(handler); this.dispatchHandlers.add(handler); } @Override public ServletRequest getRequest() { return this.request; } @Override public ServletResponse getResponse() { return this.response; } @Override public boolean hasOriginalRequestAndResponse() { return (this.request instanceof MockHttpServletRequest) && (this.response instanceof MockHttpServletResponse); } @Override public void dispatch() { dispatch(this.request.getRequestURI()); } @Override public void dispatch(String path) { dispatch(null, path); } @Override public void dispatch(ServletContext context, String path) { this.dispatchedPath = path; for (Runnable r : this.dispatchHandlers) { r.run(); } } public String getDispatchedPath() { return this.dispatchedPath; } @Override public void complete() { MockHttpServletRequest mockRequest = WebUtils.getNativeRequest(request, MockHttpServletRequest.class); if (mockRequest != null) { mockRequest.setAsyncStarted(false); } for (AsyncListener listener : this.listeners) { try { listener.onComplete(new AsyncEvent(this, this.request, this.response)); } catch (IOException ex) { throw new IllegalStateException("AsyncListener failure", ex); } } } @Override public void start(Runnable runnable) { runnable.run(); } @Override public void addListener(AsyncListener listener) { this.listeners.add(listener); } @Override public void addListener(AsyncListener listener, ServletRequest request, ServletResponse response) { this.listeners.add(listener); } public List<AsyncListener> getListeners() { return this.listeners; } @Override public <T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException { return BeanUtils.instantiateClass(clazz); } @Override public void setTimeout(long timeout) { this.timeout = timeout; } @Override public long getTimeout() { return this.timeout; } }
boggad/jdk9-sample
sample-catalog/spring-jdk9/src/spring.test/org/springframework/mock/web/MockAsyncContext.java
Java
mit
3,910
package awqatty.b.ViewUtilities; import java.util.ArrayList; import java.util.List; import android.view.View; import android.view.ViewGroup; public class ViewFinder { /***************************************************************** * Private Classes/Interfaces */ public static interface ViewMatcher { public boolean viewIsAMatch(View v); } protected static class IdMatcher implements ViewMatcher { private final int match_id; public IdMatcher(int id) { match_id = id; } @Override public boolean viewIsAMatch(View v) { return v.getId() == match_id; } } protected static class TagMatcher implements ViewMatcher { private final String match_tag; public TagMatcher(String tag) { match_tag = tag; } @Override public boolean viewIsAMatch(View v) { return match_tag.equals(v.getTag()); } } /**************************************************************** * Private Members */ private final List<View> views; private final List<ViewGroup> view_groups; // Used locally in loop private ViewMatcher matcher; private ViewGroup temp_group; private int temp_childCount; private View temp_child; /**************************************************************** * Public Methods */ public ViewFinder() { views = new ArrayList<View>(); view_groups = new ArrayList<ViewGroup>(); } protected List<View> findViews(ViewMatcher match, View root) { // Clears results from last search views.clear(); // Sets matching condition matcher = match; // Checks root view if (matcher.viewIsAMatch(root)) views.add(root); // Adds root to checking stack, & starts loop if (isAValidViewGroup(root)) view_groups.add((ViewGroup)root); while (!view_groups.isEmpty()) { // Assigns group to local variable & removes it from future loops temp_group = view_groups.remove(0); // Checks every child of group temp_childCount = temp_group.getChildCount(); for (int i=0; i < temp_childCount; ++i) { // Assigns child to local variable temp_child = temp_group.getChildAt(i); // Adds valid views to results stack if (matcher.viewIsAMatch(temp_child)) views.add(temp_child); // Adds any groups to future loops if (isAValidViewGroup(temp_child)) view_groups.add((ViewGroup)temp_child); } } // Returns results return views; } // Methods that can be overriden in inherited class protected boolean isAValidViewGroup(View v) { return v instanceof ViewGroup; } public final List<View> findViewsByTag(View root, String view_tag) { return findViews(new TagMatcher(view_tag), root); } public final List<View> findViewsById(View root, int view_id) { return findViews(new IdMatcher(view_id), root); } }
Studentoflife/CalQ
main/java/awqatty/b/ViewUtilities/ViewFinder.java
Java
mit
2,756
package fr.pizzeria.dao; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import fr.pizzeria.exception.DaoException; import fr.pizzeria.exception.SavePizzaException; import fr.pizzeria.modele.CategoriePizza; import fr.pizzeria.modele.Pizza; public class IPizzaDaoFichier implements Dao<Pizza, String> { private List<Pizza> listOfPizza = new ArrayList<>(); public IPizzaDaoFichier() { try (Stream<Path> files = Files.list(Paths.get("data"))) { listOfPizza = files.map(chemin -> { Pizza pz = new Pizza(); pz.setCode(chemin.getFileName().toFile().getName().replaceFirst(".txt", "")); try { String[] contenuFichier = Files.lines(chemin, Charset.forName("UTF-8")).findFirst().get() .split(";"); pz.setNom(contenuFichier[0]); pz.setPrix(Double.valueOf(contenuFichier[1])); pz.setCategoriePizza(CategoriePizza.valueOf(contenuFichier[2])); return pz; } catch (IOException e) { // System.out.println("Fichier au mauvais format"); throw new DaoException(e); } }).collect(Collectors.toList()); } catch (IOException e) { // System.out.println("Pas lecture data"); throw new DaoException(e); } } @Override public List<Pizza> findAllPizzas() { return listOfPizza; } @Override public boolean save(Pizza pizza) throws DaoException { if (listOfPizza.stream().filter(p -> p.getCode().equals(pizza.getCode())).count() != 0) throw new SavePizzaException(); listOfPizza.add(pizza); return true; } @Override public boolean update(String codePizza, Pizza pizza) { listOfPizza.removeIf(p -> p.getCode().equals(codePizza)); listOfPizza.add(pizza); return true; } @Override public boolean delete(String codePizza) throws DaoException { listOfPizza.removeIf(p -> p.getCode().equals(codePizza)); return false; } }
DavidLHY/TP-DTA-formation
apps/Pizza-Objet-Exceptions/src/fr/pizzeria/dao/IPizzaDaoFichier.java
Java
mit
2,042
/*=========================================================================== * Licensed Materials - Property of IBM * "Restricted Materials of IBM" * * IBM SDK, Java(tm) Technology Edition, v8 * (C) Copyright IBM Corp. 2015, 2015. All Rights Reserved * * US Government Users Restricted Rights - Use, duplication or disclosure * restricted by GSA ADP Schedule Contract with IBM Corp. *=========================================================================== */ /* * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ /* * * * * * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ package java.util.concurrent.locks; import sun.misc.Unsafe; /** * Basic thread blocking primitives for creating locks and other * synchronization classes. * * <p>This class associates, with each thread that uses it, a permit * (in the sense of the {@link java.util.concurrent.Semaphore * Semaphore} class). A call to {@code park} will return immediately * if the permit is available, consuming it in the process; otherwise * it <em>may</em> block. A call to {@code unpark} makes the permit * available, if it was not already available. (Unlike with Semaphores * though, permits do not accumulate. There is at most one.) * * <p>Methods {@code park} and {@code unpark} provide efficient * means of blocking and unblocking threads that do not encounter the * problems that cause the deprecated methods {@code Thread.suspend} * and {@code Thread.resume} to be unusable for such purposes: Races * between one thread invoking {@code park} and another thread trying * to {@code unpark} it will preserve liveness, due to the * permit. Additionally, {@code park} will return if the caller's * thread was interrupted, and timeout versions are supported. The * {@code park} method may also return at any other time, for "no * reason", so in general must be invoked within a loop that rechecks * conditions upon return. In this sense {@code park} serves as an * optimization of a "busy wait" that does not waste as much time * spinning, but must be paired with an {@code unpark} to be * effective. * * <p>The three forms of {@code park} each also support a * {@code blocker} object parameter. This object is recorded while * the thread is blocked to permit monitoring and diagnostic tools to * identify the reasons that threads are blocked. (Such tools may * access blockers using method {@link #getBlocker(Thread)}.) * The use of these forms rather than the original forms without this * parameter is strongly encouraged. The normal argument to supply as * a {@code blocker} within a lock implementation is {@code this}. * * <p>These methods are designed to be used as tools for creating * higher-level synchronization utilities, and are not in themselves * useful for most concurrency control applications. The {@code park} * method is designed for use only in constructions of the form: * * <pre> {@code * while (!canProceed()) { ... LockSupport.park(this); }}</pre> * * where neither {@code canProceed} nor any other actions prior to the * call to {@code park} entail locking or blocking. Because only one * permit is associated with each thread, any intermediary uses of * {@code park} could interfere with its intended effects. * * <p><b>Sample Usage.</b> Here is a sketch of a first-in-first-out * non-reentrant lock class: * <pre> {@code * class FIFOMutex { * private final AtomicBoolean locked = new AtomicBoolean(false); * private final Queue<Thread> waiters * = new ConcurrentLinkedQueue<Thread>(); * * public void lock() { * boolean wasInterrupted = false; * Thread current = Thread.currentThread(); * waiters.add(current); * * // Block while not first in queue or cannot acquire lock * while (waiters.peek() != current || * !locked.compareAndSet(false, true)) { * LockSupport.park(this); * if (Thread.interrupted()) // ignore interrupts while waiting * wasInterrupted = true; * } * * waiters.remove(); * if (wasInterrupted) // reassert interrupt status on exit * current.interrupt(); * } * * public void unlock() { * locked.set(false); * LockSupport.unpark(waiters.peek()); * } * }}</pre> */ public class LockSupport { private LockSupport() {} // Cannot be instantiated. private static void setBlocker(Thread t, Object arg) { // Even though volatile, hotspot doesn't need a write barrier here. UNSAFE.putObject(t, parkBlockerOffset, arg); } /** * Makes available the permit for the given thread, if it * was not already available. If the thread was blocked on * {@code park} then it will unblock. Otherwise, its next call * to {@code park} is guaranteed not to block. This operation * is not guaranteed to have any effect at all if the given * thread has not been started. * * @param thread the thread to unpark, or {@code null}, in which case * this operation has no effect */ public static void unpark(Thread thread) { if (thread != null) UNSAFE.unpark(thread); } /** * Disables the current thread for thread scheduling purposes unless the * permit is available. * * <p>If the permit is available then it is consumed and the call returns * immediately; otherwise * the current thread becomes disabled for thread scheduling * purposes and lies dormant until one of three things happens: * * <ul> * <li>Some other thread invokes {@link #unpark unpark} with the * current thread as the target; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * * <li>The call spuriously (that is, for no reason) returns. * </ul> * * <p>This method does <em>not</em> report which of these caused the * method to return. Callers should re-check the conditions which caused * the thread to park in the first place. Callers may also determine, * for example, the interrupt status of the thread upon return. * * @param blocker the synchronization object responsible for this * thread parking * @since 1.6 */ public static void park(Object blocker) { Thread t = Thread.currentThread(); setBlocker(t, blocker); UNSAFE.park(false, 0L); setBlocker(t, null); } /** * Disables the current thread for thread scheduling purposes, for up to * the specified waiting time, unless the permit is available. * * <p>If the permit is available then it is consumed and the call * returns immediately; otherwise the current thread becomes disabled * for thread scheduling purposes and lies dormant until one of four * things happens: * * <ul> * <li>Some other thread invokes {@link #unpark unpark} with the * current thread as the target; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * * <li>The specified waiting time elapses; or * * <li>The call spuriously (that is, for no reason) returns. * </ul> * * <p>This method does <em>not</em> report which of these caused the * method to return. Callers should re-check the conditions which caused * the thread to park in the first place. Callers may also determine, * for example, the interrupt status of the thread, or the elapsed time * upon return. * * @param blocker the synchronization object responsible for this * thread parking * @param nanos the maximum number of nanoseconds to wait * @since 1.6 */ public static void parkNanos(Object blocker, long nanos) { if (nanos > 0) { Thread t = Thread.currentThread(); setBlocker(t, blocker); UNSAFE.park(false, nanos); setBlocker(t, null); } } /** * Disables the current thread for thread scheduling purposes, until * the specified deadline, unless the permit is available. * * <p>If the permit is available then it is consumed and the call * returns immediately; otherwise the current thread becomes disabled * for thread scheduling purposes and lies dormant until one of four * things happens: * * <ul> * <li>Some other thread invokes {@link #unpark unpark} with the * current thread as the target; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} the * current thread; or * * <li>The specified deadline passes; or * * <li>The call spuriously (that is, for no reason) returns. * </ul> * * <p>This method does <em>not</em> report which of these caused the * method to return. Callers should re-check the conditions which caused * the thread to park in the first place. Callers may also determine, * for example, the interrupt status of the thread, or the current time * upon return. * * @param blocker the synchronization object responsible for this * thread parking * @param deadline the absolute time, in milliseconds from the Epoch, * to wait until * @since 1.6 */ public static void parkUntil(Object blocker, long deadline) { Thread t = Thread.currentThread(); setBlocker(t, blocker); UNSAFE.park(true, deadline); setBlocker(t, null); } /** * Returns the blocker object supplied to the most recent * invocation of a park method that has not yet unblocked, or null * if not blocked. The value returned is just a momentary * snapshot -- the thread may have since unblocked or blocked on a * different blocker object. * * @param t the thread * @return the blocker * @throws NullPointerException if argument is null * @since 1.6 */ public static Object getBlocker(Thread t) { if (t == null) throw new NullPointerException(); return UNSAFE.getObjectVolatile(t, parkBlockerOffset); } /** * Disables the current thread for thread scheduling purposes unless the * permit is available. * * <p>If the permit is available then it is consumed and the call * returns immediately; otherwise the current thread becomes disabled * for thread scheduling purposes and lies dormant until one of three * things happens: * * <ul> * * <li>Some other thread invokes {@link #unpark unpark} with the * current thread as the target; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * * <li>The call spuriously (that is, for no reason) returns. * </ul> * * <p>This method does <em>not</em> report which of these caused the * method to return. Callers should re-check the conditions which caused * the thread to park in the first place. Callers may also determine, * for example, the interrupt status of the thread upon return. */ public static void park() { UNSAFE.park(false, 0L); } /** * Disables the current thread for thread scheduling purposes, for up to * the specified waiting time, unless the permit is available. * * <p>If the permit is available then it is consumed and the call * returns immediately; otherwise the current thread becomes disabled * for thread scheduling purposes and lies dormant until one of four * things happens: * * <ul> * <li>Some other thread invokes {@link #unpark unpark} with the * current thread as the target; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * * <li>The specified waiting time elapses; or * * <li>The call spuriously (that is, for no reason) returns. * </ul> * * <p>This method does <em>not</em> report which of these caused the * method to return. Callers should re-check the conditions which caused * the thread to park in the first place. Callers may also determine, * for example, the interrupt status of the thread, or the elapsed time * upon return. * * @param nanos the maximum number of nanoseconds to wait */ public static void parkNanos(long nanos) { if (nanos > 0) UNSAFE.park(false, nanos); } /** * Disables the current thread for thread scheduling purposes, until * the specified deadline, unless the permit is available. * * <p>If the permit is available then it is consumed and the call * returns immediately; otherwise the current thread becomes disabled * for thread scheduling purposes and lies dormant until one of four * things happens: * * <ul> * <li>Some other thread invokes {@link #unpark unpark} with the * current thread as the target; or * * <li>Some other thread {@linkplain Thread#interrupt interrupts} * the current thread; or * * <li>The specified deadline passes; or * * <li>The call spuriously (that is, for no reason) returns. * </ul> * * <p>This method does <em>not</em> report which of these caused the * method to return. Callers should re-check the conditions which caused * the thread to park in the first place. Callers may also determine, * for example, the interrupt status of the thread, or the current time * upon return. * * @param deadline the absolute time, in milliseconds from the Epoch, * to wait until */ public static void parkUntil(long deadline) { UNSAFE.park(true, deadline); } /** * Returns the pseudo-randomly initialized or updated secondary seed. * Copied from ThreadLocalRandom due to package access restrictions. */ static final int nextSecondarySeed() { int r; Thread t = Thread.currentThread(); if ((r = UNSAFE.getInt(t, SECONDARY)) != 0) { r ^= r << 13; // xorshift r ^= r >>> 17; r ^= r << 5; } else if ((r = java.util.concurrent.ThreadLocalRandom.current().nextInt()) == 0) r = 1; // avoid zero UNSAFE.putInt(t, SECONDARY, r); return r; } // Hotspot implementation via intrinsics API private static final sun.misc.Unsafe UNSAFE; private static final long parkBlockerOffset; private static final long SEED; private static final long PROBE; private static final long SECONDARY; static { try { UNSAFE = sun.misc.Unsafe.getUnsafe(); Class<?> tk = Thread.class; parkBlockerOffset = UNSAFE.objectFieldOffset (tk.getDeclaredField("parkBlocker")); SEED = UNSAFE.objectFieldOffset (tk.getDeclaredField("threadLocalRandomSeed")); PROBE = UNSAFE.objectFieldOffset (tk.getDeclaredField("threadLocalRandomProbe")); SECONDARY = UNSAFE.objectFieldOffset (tk.getDeclaredField("threadLocalRandomSecondarySeed")); } catch (Exception ex) { throw new Error(ex); } } }
flyzsd/java-code-snippets
ibm.jdk8/src/java/util/concurrent/locks/LockSupport.java
Java
mit
15,596
package com.designpatterns.behavioural.visitor; public class Fruit implements Item { private String name; private float weight; private float pricePerKg; Category category; public Fruit(String name, float weight, float pricePerKg) { this.name = name; this.weight = weight; this.pricePerKg = pricePerKg; this.category = Category.FRUITS; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } public float getPricePerKg() { return pricePerKg; } public void setPricePerKg(float pricePerKg) { this.pricePerKg = pricePerKg; } public Category getCategory() { return category; } public float accept(Visitor visitor) { return visitor.visit(this); } }
deepaksama/Design-Patterns
DesignPatterns/src/com/designpatterns/behavioural/visitor/Fruit.java
Java
mit
849