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 com.yannic.rdv.data.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "locations")
public class Location {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "location_id")
private Long locationId;
private String name;
@Column(name = "street_address")
private String streetAddress;
@Column(name = "postal_code")
private String postalCode;
@Column(name = "address_country")
private String addressCountry;
@OneToOne // default fetch strategy is eager
@JoinColumn(name = "organizer_id")
private Organizer organizer;
public Long getLocationId() {
return locationId;
}
public void setLocationId(Long locationId) {
this.locationId = locationId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getAddressCountry() {
return addressCountry;
}
public void setAddressCountry(String addressCountry) {
this.addressCountry = addressCountry;
}
public Organizer getOrganizer() {
return organizer;
}
public void setOrganizer(Organizer organizer) {
this.organizer = organizer;
}
}
| yannicl/rdv | rdv-data/src/main/java/com/yannic/rdv/data/model/Location.java | Java | mit | 1,685 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ccc.mavenbmcp.servlet;
import com.ccc.mavenbmcp.entity.Contact;
import com.ccc.mavenbmcp.entity.JdbcConnBmcp;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author davidchang
*/
@WebServlet(name = "ContactServlet", urlPatterns = {"/ContactServlet"})
public class ContactServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs;
try {
Class.forName(JdbcConnBmcp.DRIVER_MANAGER);
conn = DriverManager.getConnection(JdbcConnBmcp.DB_URL, JdbcConnBmcp.USER, JdbcConnBmcp.PASS);
String cmd = request.getParameter("cmd");
switch(cmd){
case "get":
pstmt = conn.prepareStatement("SELECT * FROM `contact`");
rs = pstmt.executeQuery();
List contacts = new ArrayList<>();
while(rs.next()){
Contact contact = new Contact();
contact.setId(rs.getInt("id"));
contact.setName(rs.getString("name"));
contact.setEngName(rs.getString("engName"));
contact.setTitle(rs.getString("title"));
contact.setDepartment(rs.getString("department"));
contact.setEmail(rs.getString("email"));
contact.setExt(rs.getString("ext"));
contact.setMobile(rs.getString("mobile"));
contacts.add(contact);
}
HttpSession session = request.getSession();
session.setAttribute("contacts", contacts);
session.setMaxInactiveInterval(5*60);
/*
String json = new Gson().toJson(contacts);
response.setContentType("application/json");
response.setContentType("text/html;charset=UTF-8");
out.write(json);
*/
break;
}
} catch (Exception e) {
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| chechiachang/booking-manager-maven | src/main/java/com/ccc/mavenbmcp/servlet/ContactServlet.java | Java | mit | 4,667 |
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.guserpsw;
public final class R {
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
*/
public static final int activity_horizontal_margin=0x7f040000;
public static final int activity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int action_settings=0x7f080006;
public static final int button1=0x7f080004;
public static final int editText1=0x7f080002;
public static final int editText2=0x7f080003;
public static final int textView1=0x7f080000;
public static final int textView2=0x7f080001;
public static final int textView3=0x7f080005;
}
public static final class layout {
public static final int activity_main=0x7f030000;
public static final int activity_main_activity2=0x7f030001;
}
public static final class menu {
public static final int main=0x7f070000;
public static final int main_activity2=0x7f070001;
}
public static final class string {
public static final int action_settings=0x7f050001;
public static final int app_name=0x7f050000;
public static final int hello_world=0x7f050002;
public static final int title_activity_main_activity2=0x7f050003;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f060000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
}
}
| rahulpareek2440/AndroidPrograms | guserpsw/gen/com/example/guserpsw/R.java | Java | mit | 2,950 |
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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 hudson.util;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.mapper.Mapper;
import hudson.model.AbstractProject;
import hudson.model.DependecyDeclarer;
import hudson.model.DependencyGraph;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Descriptor.FormException;
import hudson.model.Saveable;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Persisted list of {@link Describable}s with some operations specific
* to {@link Descriptor}s.
*
* <p>
* This class allows multiple instances of the same descriptor. Some clients
* use this semantics, while other clients use it as "up to one instance per
* one descriptor" model.
*
* Some of the methods defined in this class only makes sense in the latter model,
* such as {@link #remove(Descriptor)}.
*
* @author Kohsuke Kawaguchi
*/
public class DescribableList<T extends Describable<T>, D extends Descriptor<T>> extends PersistedList<T> {
protected DescribableList() {
}
/**
* @deprecated since 2008-08-15.
* Use {@link #DescribableList(Saveable)}
*/
public DescribableList(Owner owner) {
setOwner(owner);
}
public DescribableList(Saveable owner) {
setOwner(owner);
}
public DescribableList(Saveable owner, Collection<? extends T> initialList) {
super(initialList);
setOwner(owner);
}
/**
* @deprecated since 2008-08-15.
* Use {@link #setOwner(Saveable)}
*/
public void setOwner(Owner owner) {
this.owner = owner;
}
/**
* Removes all instances of the same type, then add the new one.
*/
public void replace(T item) throws IOException {
removeAll((Class)item.getClass());
data.add(item);
onModified();
}
public T get(D descriptor) {
for (T t : data)
if(t.getDescriptor()==descriptor)
return t;
return null;
}
public boolean contains(D d) {
return get(d)!=null;
}
public void remove(D descriptor) throws IOException {
for (T t : data) {
if(t.getDescriptor()==descriptor) {
data.remove(t);
onModified();
return;
}
}
}
@SuppressWarnings("unchecked")
public Map<D,T> toMap() {
return (Map)Descriptor.toMap(data);
}
/**
* Rebuilds the list by creating a fresh instances from the submitted form.
*
* <p>
* This method is almost always used by the owner.
* This method does not invoke the save method.
*
* @param json
* Structured form data that includes the data for nested descriptor list.
*/
public void rebuild(StaplerRequest req, JSONObject json, List<? extends Descriptor<T>> descriptors) throws FormException {
List<T> newList = new ArrayList<T>();
for (Descriptor<T> d : descriptors) {
String name = d.getJsonSafeClassName();
if (json.has(name)) {
T instance = d.newInstance(req, json.getJSONObject(name));
newList.add(instance);
}
}
data.replaceBy(newList);
}
/**
* @deprecated as of 1.271
* Use {@link #rebuild(StaplerRequest, JSONObject, List)} instead.
*/
public void rebuild(StaplerRequest req, JSONObject json, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException {
rebuild(req,json,descriptors);
}
/**
* Rebuilds the list by creating a fresh instances from the submitted form.
*
* <p>
* This version works with the the <f:hetero-list> UI tag, where the user
* is allowed to create multiple instances of the same descriptor. Order is also
* significant.
*/
public void rebuildHetero(StaplerRequest req, JSONObject formData, Collection<? extends Descriptor<T>> descriptors, String key) throws FormException {
data.replaceBy(Descriptor.newInstancesFromHeteroList(req,formData,key,descriptors));
}
/**
* Picks up {@link DependecyDeclarer}s and allow it to build dependencies.
*/
public void buildDependencyGraph(AbstractProject owner,DependencyGraph graph) {
for (Object o : this) {
if (o instanceof DependecyDeclarer) {
DependecyDeclarer dd = (DependecyDeclarer) o;
dd.buildDependencyGraph(owner,graph);
}
}
}
/*
The following two seemingly pointless method definitions are necessary to produce
backward compatible binary signatures. Without this we only get
get(Ljava/lang/Class;)Ljava/lang/Object; from PersistedList where we need
get(Ljava/lang/Class;)Lhudson/model/Describable;
*/
public <U extends T> U get(Class<U> type) {
return super.get(type);
}
public T[] toArray(T[] array) {
return super.toArray(array);
}
/**
* @deprecated since 2008-08-15.
* Just implement {@link Saveable}.
*/
public interface Owner extends Saveable {
}
/**
* {@link Converter} implementation for XStream.
*
* Serializaion form is compatible with plain {@link List}.
*/
public static class ConverterImpl extends AbstractCollectionConverter {
CopyOnWriteList.ConverterImpl copyOnWriteListConverter;
public ConverterImpl(Mapper mapper) {
super(mapper);
copyOnWriteListConverter = new CopyOnWriteList.ConverterImpl(mapper());
}
public boolean canConvert(Class type) {
// handle subtypes in case the onModified method is overridden.
return DescribableList.class.isAssignableFrom(type);
}
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
for (Object o : (DescribableList) source)
writeItem(o, context, writer);
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
CopyOnWriteList core = copyOnWriteListConverter.unmarshal(reader, context);
try {
DescribableList r = (DescribableList)context.getRequiredType().newInstance();
r.data.replaceBy(core);
return r;
} catch (InstantiationException e) {
InstantiationError x = new InstantiationError();
x.initCause(e);
throw x;
} catch (IllegalAccessException e) {
IllegalAccessError x = new IllegalAccessError();
x.initCause(e);
throw x;
}
}
}
}
| vivek/hudson | core/src/main/java/hudson/util/DescribableList.java | Java | mit | 8,429 |
package extracells.container;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import extracells.container.slot.SlotRespective;
public class ContainerFluidCrafter extends Container {
IInventory tileentity;
public ContainerFluidCrafter(InventoryPlayer player, IInventory tileentity) {
this.tileentity = tileentity;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
addSlotToContainer(new SlotRespective(tileentity, j + i * 3,
62 + j * 18, 17 + i * 18));
}
}
bindPlayerInventory(player);
}
protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 9; j++) {
addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9,
8 + j * 18, i * 18 + 84));
}
}
for (int i = 0; i < 9; i++) {
addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 142));
}
}
@Override
public boolean canInteractWith(EntityPlayer entityplayer) {
return true;
}
@Override
public void onContainerClosed(EntityPlayer entityplayer) {
super.onContainerClosed(entityplayer);
}
@Override
protected void retrySlotClick(int par1, int par2, boolean par3,
EntityPlayer par4EntityPlayer) {
// DON'T DO ANYTHING, YOU SHITTY METHOD!
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) {
ItemStack itemstack = null;
Slot slot = (Slot) this.inventorySlots.get(slotnumber);
if (slot != null && slot.getHasStack()) {
ItemStack itemstack1 = slot.getStack();
itemstack = itemstack1.copy();
if (this.tileentity.isItemValidForSlot(0, itemstack1)) {
if (slotnumber < 10) {
if (!mergeItemStack(itemstack1, 10, 36, false))
return null;
} else if (slotnumber >= 10 && slotnumber <= 36) {
if (!mergeItemStack(itemstack1, 0, 1, false))
return null;
}
if (itemstack1.stackSize == 0) {
slot.putStack(null);
} else {
slot.onSlotChanged();
}
} else {
return null;
}
}
return itemstack;
}
}
| AmethystAir/ExtraCells2 | src/main/scala/extracells/container/ContainerFluidCrafter.java | Java | mit | 2,218 |
package com.owolp.comicsand.injection.qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Qualifier;
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface ApplicationContext {
} | owolp/Comicsand | app/src/main/java/com/owolp/comicsand/injection/qualifier/ApplicationContext.java | Java | mit | 253 |
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VowelCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
Pattern pattern = Pattern.compile("[AOIUEYaoiuey]");
Matcher matcher = pattern.matcher(text);
int count = 0;
while (matcher.find()){
count++;
}
System.out.printf("Vowels: %d", count);
}
}
| AneliaDoychinova/Java-Advanced | 03. String processing/Lab/VowelCount.java | Java | mit | 510 |
/*******************************************************************************
* Copyright 2013 Fabio D. C. Depin <[email protected]>.
*
* 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.
*
* Contributors:
* Fabio D. C. Depin <[email protected]> - initial implementation this Class
******************************************************************************/
package domain;
public class Pessoa {
private String nome;
private String cpf;
private String telefone;
public Pessoa(String nome, String cpf, String telefone) {
this.nome = nome;
this.cpf = cpf;
this.telefone = telefone;
}
public Pessoa(String nome, String cpf) {
this.nome = nome;
this.cpf = cpf;
}
public String getNome() {
return nome;
}
public String getCpf() {
return cpf;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
}
| fabiodepin/Estacionamento_java | src/domain/Pessoa.java | Java | mit | 1,485 |
package com.acunu.castle;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public abstract class AbstractCallback implements Runnable
{
protected final Map<BufferManager, List<ByteBuffer>> buffers = new HashMap<BufferManager, List<ByteBuffer>>();
protected abstract void process();
public void run()
{
try
{
process();
} finally
{
cleanup();
}
}
/* package private */
void collect(final BufferManager manager, final ByteBuffer... bufs)
{
if (!buffers.containsKey(manager))
buffers.put(manager, new LinkedList<ByteBuffer>());
buffers.get(manager).addAll(Arrays.asList(bufs));
}
public void collect(final Castle castle, final ByteBuffer... bufs)
{
collect(castle.getBufferManager(), bufs);
}
/*
* last chance to avoid leaking NB: finalize methods are not guaranteed to
* be run, ever.
*/
@Override
public void finalize()
{
cleanup();
}
protected void cleanup()
{
for (final Map.Entry<BufferManager, List<ByteBuffer>> entry : buffers.entrySet())
{
for (final ByteBuffer buf : entry.getValue())
{
try
{
entry.getKey().put(buf);
} catch (final IOException e)
{
}
}
entry.getValue().clear();
}
}
}
| fohr/java-castle | src/java/com/acunu/castle/AbstractCallback.java | Java | mit | 1,334 |
package battler2;
import pokemon.Pokemon;
public class Player
{
protected String name;
protected Pokemon pokemon[];
protected Pokemon activePokemon;
public Player(String name, Pokemon pokemon[])
{
this.name = name;
this.pokemon = pokemon;
this.activePokemon = null;
}
public String showAllPokemonBasic()
{
if(pokemon.length <= 0)
{
return "No Pokemon!";
}
String basicPokemonList = "";
for(int i = 0; i < pokemon.length; i++)
{
basicPokemonList += "'s";
basicPokemonList += i+1; // # command to switch to this pokemon
basicPokemonList += "'";
if(pokemon[i].isActive())
{
basicPokemonList += " - ACTIVE";
}
basicPokemonList += " - " + pokemon[i].showBasicDetails() + "\n";
}
return basicPokemonList;
}
public String showAllPokemonDetailed()
{
if(pokemon.length <= 0)
{
return "No Pokemon!";
}
String detailedPokemonList = "";
for(int i = 0; i < pokemon.length; i++)
{
detailedPokemonList += "'s";
detailedPokemonList += i+1; // # command to switch to this pokemon
detailedPokemonList += "'";
if(pokemon[i].isActive())
{
detailedPokemonList += " - ACTIVE";
}
detailedPokemonList += " - " + pokemon[i].showExtenedDetails() + "\n";
}
return detailedPokemonList;
}
// GETTERS AND SETTERS
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Pokemon[] getPokemon()
{
return pokemon;
}
public void setPokemon(Pokemon[] pokemon)
{
this.pokemon = pokemon;
}
public Pokemon getActivePokemon()
{
return activePokemon;
}
public void setActivePokemon(Pokemon activePokemon)
{
if(this.activePokemon != null)
{
this.activePokemon.setActive(false); // un-set old pokemon
}
this.activePokemon = activePokemon; // set new pokemon
this.activePokemon.setActive(true);
}
}
| FlyMeToSomeday/ryans-pokeman-battler | src/battler2/Player.java | Java | mit | 1,903 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.automation.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Definition of the module error info type. */
@Fluent
public final class ModuleErrorInfo {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ModuleErrorInfo.class);
/*
* Gets or sets the error code.
*/
@JsonProperty(value = "code")
private String code;
/*
* Gets or sets the error message.
*/
@JsonProperty(value = "message")
private String message;
/**
* Get the code property: Gets or sets the error code.
*
* @return the code value.
*/
public String code() {
return this.code;
}
/**
* Set the code property: Gets or sets the error code.
*
* @param code the code value to set.
* @return the ModuleErrorInfo object itself.
*/
public ModuleErrorInfo withCode(String code) {
this.code = code;
return this;
}
/**
* Get the message property: Gets or sets the error message.
*
* @return the message value.
*/
public String message() {
return this.message;
}
/**
* Set the message property: Gets or sets the error message.
*
* @param message the message value to set.
* @return the ModuleErrorInfo object itself.
*/
public ModuleErrorInfo withMessage(String message) {
this.message = message;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| Azure/azure-sdk-for-java | sdk/automation/azure-resourcemanager-automation/src/main/java/com/azure/resourcemanager/automation/models/ModuleErrorInfo.java | Java | mit | 1,938 |
//The MIT License
//
//Copyright (c) 2009 nodchip
//
//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 tv.dyndns.kishibe.qmaclone.client.packet;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.collect.ComparisonChain;
import com.google.gwt.user.client.rpc.IsSerializable;
public class PacketWrongAnswer implements IsSerializable, Comparable<PacketWrongAnswer> {
public String answer;
public int count;
public PacketWrongAnswer setAnswer(String answer) {
this.answer = answer;
return this;
}
public PacketWrongAnswer setCount(int count) {
this.count = count;
return this;
}
@Override
public int hashCode() {
return Objects.hashCode(answer, count);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof PacketWrongAnswer)) {
return false;
}
PacketWrongAnswer rh = (PacketWrongAnswer) obj;
return Objects.equal(answer, rh.answer) && count == rh.count;
}
@Override
public int compareTo(PacketWrongAnswer o) {
return ComparisonChain.start().compare(answer, o.answer).compare(count, o.count).result();
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("answer", answer).add("count", count).toString();
}
}
| nodchip/QMAClone | src/main/java/tv/dyndns/kishibe/qmaclone/client/packet/PacketWrongAnswer.java | Java | mit | 2,317 |
package org.lla_private;
import java.net.URI;
import javax.ws.rs.client.Client;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.lla_private.guice.annotation.WebserviceRestClient;
import org.mockito.Mockito;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class TestWebservice {
private Webservice kontingente;
private WebserviceTestModule testModule;
@Before
public void before() {
testModule = new WebserviceTestModule();
final Injector injector = Guice.createInjector(testModule);
kontingente = new Webservice();
injector.injectMembers(kontingente);
}
// private static class WebserviceTestModule extends AbstractModule {
//
// public Builder builderMock;
// public ClientResponse clientResponseMock;
//
// @Override
// protected void configure() {
// final ClientBuilder clientMock = Mockito.mock(ClientBuilder.class);
//
// final WebTarget webResourceMock = Mockito.mock(WebTarget.class);
// builderMock = Mockito.mock(Builder.class);
// clientResponseMock = Mockito.mock(ClientResponse.class);
//
// // Gesamtaufruf: response =
// // restClient.resource(...).accept(...).get(...);
// // client.resource() -> webResource
// Mockito.doReturn(webResourceMock).when(clientMock).resource(Mockito.any(URI.class));
// // webResource.accept() -> builder
// Mockito.doReturn(builderMock).when(webResourceMock).accept(Mockito.anyString());
// // builder.get() -> clientResponse
// Mockito.doReturn(clientResponseMock).when(builderMock).get(Mockito.<Class<?>> any());
// // clientResponse.getEntity() -> ""
// Mockito.doReturn("").when(clientResponseMock).getEntity(Mockito.<Class<?>> any());
//
// // Gesamtaufruf: response =
// // restClient.resource(...).type(...).accept(...).post(..., ...);
// Mockito.doReturn(clientResponseMock).when(builderMock).post(Mockito.<Class<?>> any(), Mockito.anyString());
//
// bind(ClientBuilder.class).annotatedWith(WebserviceRestClient.class).toInstance(clientMock);
// }
//
// }
private static class WebserviceTestModule extends AbstractModule {
@Override
protected void configure() {
final Client clientMock = Mockito.mock(Client.class);
// final WebTarget webResourceMock = Mockito.mock(WebTarget.class);
bind(Client.class).annotatedWith(WebserviceRestClient.class).toInstance(clientMock);
}
}
@Test
public void testCreateUriWithKundenNr_with_KundenNr() {
final URI uri = kontingente.createUriWithKundenNr(1799);
Assert.assertEquals(Webservice.QA_REST_URL + Webservice.REQUEST_PATH + "1799", uri.toString());
}
@Test
public void testCreateUriWithKundenNr_with_KundenNr_null() {
final URI uri = kontingente.createUriWithKundenNr(null);
Assert.assertNull(uri);
}
@Test
public void testCreateUriWithKundenNrAndPlz_with_KundenNr_and_Plz() {
final URI uri = kontingente.createUriWithKundenNrAndPlz(1799, 4);
Assert.assertEquals(Webservice.QA_REST_URL + Webservice.REQUEST_PATH + "1799/4", uri.toString());
}
@Test
public void testCreateUriWithKundenNrAndPlz_with_KundenNr_null() {
final URI uri = kontingente.createUriWithKundenNrAndPlz(null, 1);
Assert.assertNull(uri);
}
@Test
public void testCreateDecrementUriWithKundenNrAndPlz_with_KundenNr_and_Plz() {
final URI uri = kontingente.createDecrementUriWithKundenNrAndPlz(1799, 4);
Assert.assertEquals(Webservice.QA_REST_URL + Webservice.UPDATE_PATH + "1799/4", uri.toString());
}
@Test
public void testCreateDecrementUriWithKundenNrAndPlz_with_KundenNr_null() {
final URI uri = kontingente.createDecrementUriWithKundenNrAndPlz(null, 1);
Assert.assertNull(uri);
}
// @Test
// public void testHasKontingent_Available_true() {
// Mockito.doReturn("{\"available\":true,\"reason\":\"reason\"}").when(testModule.clientResponseMock).getEntity(String.class);
// final String actual = kontingente.hasKontingent(1799, 40000);
// Assert.assertEquals("has Kontingent", actual);
// }
}
| LarsImNetz/microservice-sentences | client/src/test/java/org/lla_private/TestWebservice.java | Java | mit | 4,002 |
package put.poznan.ai.common;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import org.primefaces.validate.ClientValidator;
@FacesValidator("custom.emailValidator")
public class EmailValidator implements Validator, ClientValidator {
private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(
"messages", new Locale("pl"));
private Pattern pattern;
public static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}
public void validate(FacesContext context, UIComponent component,
Object value) throws ValidatorException {
if (value == null) {
return;
}
if (!pattern.matcher(value.toString()).matches()) {
throw new ValidatorException(new FacesMessage(
FacesMessage.SEVERITY_ERROR,
BUNDLE.getString("register.email"),
BUNDLE.getString("register.validatorEmail") + ": " + value));
}
}
public Map<String, Object> getMetadata() {
return null;
}
public String getValidatorId() {
return "custom.emailValidator";
}
} | Shymwo/contest-masters | src/main/java/put/poznan/ai/common/EmailValidator.java | Java | mit | 1,461 |
/*
* Encog(tm) Core v3.1 - Java Version
* http://www.heatonresearch.com/encog/
* http://code.google.com/p/encog-java/
* Copyright 2008-2012 Heaton Research, Inc.
*
* 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.ml.schedule;
import org.encog.ml.graph.BasicEdge;
import org.encog.ml.world.basic.BasicAction;
public class CalculateScheduleTimes {
public void forward(ActionNode node) {
// find the max
double m = Double.NEGATIVE_INFINITY;
for(BasicEdge edge: node.getBackConnections()) {
double d = ((ActionNode)edge.getFrom()).getEarliestStartTime()+((ActionNode)edge.getFrom()).getDuration();
m = Math.max(d, m);
}
node.setEarliestStartTime(m);
// handle other nodes
for(BasicEdge edge: node.getConnections()) {
forward((ActionNode)edge.getTo());
}
}
public void backward(ActionNode node) {
// find the min
double m = Double.POSITIVE_INFINITY;
for(BasicEdge edge: node.getConnections()) {
double d = ((ActionNode)edge.getTo()).getLatestStartTime()-((ActionNode)edge.getFrom()).getDuration();
m = Math.min(d, m);
}
node.setLatestStartTime(m);
// handle other nodes
for(BasicEdge edge: node.getBackConnections()) {
backward((ActionNode)edge.getFrom());
}
}
public void calculate(ScheduleGraph graph) {
// forward pass
graph.getStartNode().setEarliestStartTime(0);
for(BasicEdge edge: graph.getStartNode().getConnections()) {
forward((ActionNode)edge.getTo());
}
// backward
graph.getFinishNode().setLatestStartTime(graph.getFinishNode().getEarliestStartTime());
for(BasicEdge edge: graph.getFinishNode().getBackConnections()) {
backward((ActionNode)edge.getFrom());
}
}
}
| larhoy/SentimentProjectV2 | SentimentAnalysisV2/encog-core-3.1.0/src/main/java/org/encog/ml/schedule/CalculateScheduleTimes.java | Java | mit | 2,346 |
/*
* -------------------------------- MIT License --------------------------------
*
* Copyright (c) 2021 SNF4J contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* -----------------------------------------------------------------------------
*/
package org.snf4j.core.proxy;
class Socks5Reply implements ISocksReply {
private final int status;
private final String address;
private final SocksAddressType addressType;
private final int port;
Socks5Reply(int status, SocksAddressType addressType, String address, int port) {
this.status = status;
this.addressType = addressType;
this.address = address;
this.port = port;
}
@Override
public boolean isSuccessful() {
return status == Socks5Status.SUCCESS.code();
}
@Override
public int getStatus() {
return status;
}
@Override
public String getStatusDescription() {
return Socks5Status.valueOf(status).description();
}
@Override
public int getPort() {
return port;
}
@Override
public String getAddress() {
return address;
}
@Override
public SocksAddressType getAddressType() {
return addressType;
}
}
| snf4j/snf4j | snf4j-core/src/main/java/org/snf4j/core/proxy/Socks5Reply.java | Java | mit | 2,161 |
package com.example.rxjava;
public class AirplaneStatusText {
public final static String RED = "red";
public final static String GREEN = "green";
}
| FridayCoders/FrpOnAndroid | GDG_Airplane/RxjavaExample/app/src/main/java/com/example/rxjava/AirplaneStatusText.java | Java | mit | 157 |
/**
* The MIT License
* Copyright (c) ${project.inceptionYear} the-james-burton
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jimsey.projects.turbine.inlet.service;
import java.lang.invoke.MethodHandles;
import java.net.InetSocketAddress;
import javax.annotation.PostConstruct;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.jimsey.projects.turbine.fuel.domain.Ticker;
import org.jimsey.projects.turbine.inlet.external.domain.LseCompany;
import org.jimsey.projects.turbine.inlet.external.domain.LseSecurity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class ElasticsearchNativeServiceImpl implements ElasticsearchService {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
@Value("${elasticsearch.cluster}")
private String cluster;
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private Integer port;
@Value("${elasticsearch.index.company}")
private String indexForCompany;
@Value("${elasticsearch.type.company}")
private String typeForCompany;
@Value("${elasticsearch.index.security}")
private String indexForSecurity;
@Value("${elasticsearch.type.security}")
private String typeForSecurity;
@Value("${elasticsearch.index.ticker}")
private String indexForTicker;
@Value("${elasticsearch.type.ticker}")
private String typeForTicker;
private TransportClient elasticsearch;
@PostConstruct
public void init() {
Settings settings = Settings.builder()
.put("cluster.name", cluster)
.put("transport.type", "netty4")
.build();
elasticsearch = new PreBuiltTransportClient(settings);
logger.info(" *** connecting to : {}:{}:{}", cluster, host, port);
InetSocketAddress address = new InetSocketAddress(host, port);
InetSocketTransportAddress transport = new InetSocketTransportAddress(address);
elasticsearch.addTransportAddress(transport);
}
@Override
public String indexCompany(LseCompany company) {
logger.info("indexCompany:{}", company.toString());
return indexObject(company, indexForCompany, typeForCompany);
}
@Override
public String indexSecurity(LseSecurity security) {
logger.info("indexSecurity:{}", security.toString());
return indexObject(security, indexForSecurity, typeForSecurity);
}
@Override
public String indexTicker(Ticker ticker) {
logger.info("indexTicker:{}", ticker.toString());
return indexObject(ticker, indexForTicker, typeForTicker);
}
@Override
public boolean deleteCompaniesIndex() {
return deleteIndex(indexForCompany);
}
@Override
public boolean deleteSecuritiesIndex() {
return deleteIndex(indexForSecurity);
}
@Override
public boolean deleteTickersIndex() {
return deleteIndex(indexForTicker);
}
/**
* Adds (indexes) a given object to the given index with the given type
* @param object to index which should have a toString() method returning valid JSON
* @param index to add the object to
* @param type to give the object
* @return
*/
private String indexObject(Object object, String index, String type) {
IndexResponse response = elasticsearch
.prepareIndex(index, type)
.setSource(object.toString())
.get();
return response.toString();
}
/**
* Removes the given index from elasticsearch
* @param index to delete
* @return true if successfully deleted
*/
private boolean deleteIndex(String index) {
boolean result = false;
try {
DeleteIndexResponse response = elasticsearch.admin().indices().prepareDelete(index).get();
logger.info("successfully deleted: index:{}, isAcknowledged:{}", index, response.isAcknowledged());
result = response.isAcknowledged();
} catch (IndexNotFoundException e) {
logger.info("index not found: index:{}", index);
result = true;
} catch (Exception e) {
logger.error(e.getMessage());
result = false;
}
return result;
}
}
| the-james-burton/the-turbine | turbine-engine-hall/turbine-inlet/src/main/java/org/jimsey/projects/turbine/inlet/service/ElasticsearchNativeServiceImpl.java | Java | mit | 5,571 |
package functional.com.bitdubai.fermat_p2p_plugin.layer._11_communication.cloud_server.developer.bitdubai.version_1.structure.CloudNetworkServiceManager;
import functional.com.bitdubai.fermat_p2p_plugin.layer._11_communication.cloud_server.developer.bitdubai.version_1.structure.mocks.MockFMPPacketsFactory;
import functional.com.bitdubai.fermat_p2p_plugin.layer._11_communication.cloud_server.developer.bitdubai.version_1.structure.mocks.MockNIOClient;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.bitdubai.fermat_p2p_api.layer.p2p_communication.CommunicationChannelAddress;
import com.bitdubai.fermat_p2p_api.layer.p2p_communication.fmp.FMPPacket;
import com.bitdubai.fermat_p2p_api.layer.all_definition.communication.CommunicationChannelAddressFactory;
import com.bitdubai.fermat_api.layer.all_definition.enums.NetworkServices;
import com.bitdubai.fermat_api.layer.all_definition.crypto.asymmetric.ECCKeyPair;
import com.bitdubai.fermat_p2p_plugin.layer.communication.cloud_server.developer.bitdubai.version_1.structure.CloudNetworkServiceManager;
public abstract class CloudNetworkServiceManagerIntegrationTest {
protected CloudNetworkServiceManager testManager;
protected String testHost;
protected Integer testPort;
protected CommunicationChannelAddress testAddress;
protected ExecutorService testExecutor;
protected String testPrivateKey;
protected String testPublicKey;
protected ECCKeyPair testKeyPair;
protected NetworkServices testNetworkService;
protected Set<Integer> testVPNPorts;
protected MockNIOClient testClient;
protected static final int RESPONSE_READ_ATTEMPTS = 10;
protected static final int TCP_BASE_TEST_PORT = 50000;
protected void setUpAddressInfo(int port) throws Exception{
testHost = "localhost";
testPort = Integer.valueOf(port);
}
protected void setUpKeyPair(){
testPrivateKey = "BE823188D332F3C73BFA34F8F453CFC184718273195194D4A9F5BB27A191886D";
testPublicKey = "04F0F591F89E3CA948824F3CA8FD7D2115AE20B801EDE4CA090E3DA1856C1AC199CAB9BCF755162159C3C999F921ACE78B9529DFE67715C321DA8208B483DC74DB";
testKeyPair = new ECCKeyPair(testPrivateKey, testPublicKey);
}
protected void setUpExecutor(int threads) throws Exception{
testExecutor = Executors.newFixedThreadPool(threads);
}
protected void setUpConnections(int portPadding) throws Exception{
testAddress = CommunicationChannelAddressFactory.constructCloudAddress(testHost, testPort+portPadding);
testNetworkService = NetworkServices.INTRA_USER;
testVPNPorts = new HashSet<Integer>();
testVPNPorts.add(testPort+portPadding+1);
testManager = new CloudNetworkServiceManager(testAddress, testExecutor, testKeyPair, testNetworkService, testVPNPorts);
testManager.start();
testClient = new MockNIOClient(testHost, testPort+portPadding);
}
protected FMPPacket requestConnection() throws Exception{
FMPPacket request = MockFMPPacketsFactory.mockRequestConnectionNetworkServicePacket(testNetworkService, testManager.getIdentityPublicKey());
testClient.sendMessage(request);
return getResponse();
}
protected FMPPacket registerConnection() throws Exception{
FMPPacket register = MockFMPPacketsFactory.mockRegisterConnectionPacket(testManager.getIdentityPublicKey());
testClient.sendMessage(register);
return getResponse();
}
protected synchronized FMPPacket getResponse() throws Exception {
FMPPacket response = null;
int attempts = 0;
while(response == null){
if(attempts>RESPONSE_READ_ATTEMPTS)
break;
response = testClient.getResponse();
++attempts;
}
return response;
}
}
| fvasquezjatar/fermat-unused | P2P/plugin/communication/fermat-p2p-plugin-communication-cloud-server-bitdubai/src/test/java/functional/com/bitdubai/fermat_p2p_plugin/layer/_11_communication/cloud_server/developer/bitdubai/version_1/structure/CloudNetworkServiceManager/CloudNetworkServiceManagerIntegrationTest.java | Java | mit | 3,664 |
package sculture.models.tables.relations;
import java.io.Serializable;
public class ReportStoryPK implements Serializable {
private long user_id;
private long story_id;
public ReportStoryPK() {
}
public ReportStoryPK(long user_id, long story_id) {
this.user_id = user_id;
this.story_id = story_id;
}
} | bounswe/bounswe2015group7 | sculture-rest/src/main/java/sculture/models/tables/relations/ReportStoryPK.java | Java | mit | 351 |
package com.example.homebrewtimer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| CDargis/HomeberwTimer | src/com/example/homebrewtimer/MainActivity.java | Java | mit | 571 |
package org.cyclops.integrateddynamics.core.client.model;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.mojang.datafixers.util.Either;
import com.mojang.datafixers.util.Pair;
import net.minecraft.client.renderer.model.*;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.IModelConfiguration;
import net.minecraftforge.client.model.ItemLayerModel;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.client.model.geometry.IModelGeometry;
import org.cyclops.integrateddynamics.api.client.model.IVariableModelProvider;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.function.Function;
/**
* Model for a variant of a variable item.
* @author rubensworks
*/
public class VariableModel implements IUnbakedModel, IModelGeometry<VariableModel> {
private final BlockModel base;
public VariableModel(BlockModel base) {
this.base = base;
}
public void loadSubModels(ModelLoader modelLoader) {
for(IVariableModelProvider provider : VariableModelProviders.REGISTRY.getProviders()) {
provider.loadModels(modelLoader);
}
}
public static void addAdditionalModels(ImmutableSet.Builder<ResourceLocation> builder) {
for(IVariableModelProvider<?> provider : VariableModelProviders.REGISTRY.getProviders()) {
builder.addAll(provider.getDependencies());
}
}
@Override
public Collection<ResourceLocation> getDependencies() {
if(base.getParentLocation() == null || base.getParentLocation().getPath().startsWith("builtin/")) {
return Collections.emptyList();
}
ImmutableSet.Builder<ResourceLocation> builder = ImmutableSet.builder();
builder.add(base.getParentLocation());
addAdditionalModels(builder);
return builder.build();
}
@Override
public Collection<RenderMaterial> getTextures(Function<ResourceLocation, IUnbakedModel> modelGetter, Set<Pair<String, String>> missingTextureErrors) {
base.parent = ModelHelpers.MODEL_GENERATED; // To enable texture resolving
Set<RenderMaterial> textures = Sets.newHashSet(base.resolveTextureName("particle"));
// Loop over all textures for the default layers and add them to the collection if available.
if(base.getRootModel() == ModelBakery.MODEL_GENERATED) {
ItemModelGenerator.LAYERS.forEach((p_228814_2_) -> {
textures.add(base.resolveTextureName(p_228814_2_));
});
}
// Loop over all textures in this model and add them to the collection.
for(Either<RenderMaterial, String> texture : base.textures.values()) {
texture.ifLeft(textures::add);
}
return textures;
}
@Nullable
@Override
public IBakedModel bakeModel(ModelBakery bakery, Function<RenderMaterial, TextureAtlasSprite> spriteGetter,
IModelTransform transform, ResourceLocation location) {
RenderMaterial textureName = base.resolveTextureName("layer0");
BlockModel itemModel = ModelHelpers.MODEL_GENERATOR.makeItemModel(spriteGetter, base);
SimpleBakedModel.Builder builder = (new SimpleBakedModel.Builder(itemModel.customData, itemModel.getOverrides(bakery, itemModel, spriteGetter)));
itemModel.textures.put("layer0", Either.left(textureName));
TextureAtlasSprite textureAtlasSprite = spriteGetter.apply(textureName);
builder.setTexture(textureAtlasSprite);
for (BakedQuad bakedQuad : ItemLayerModel.getQuadsForSprite(0, textureAtlasSprite, transform.getRotation())) {
builder.addGeneralQuad(bakedQuad);
}
IBakedModel baseModel = builder.build();
VariableModelBaked bakedModel = new VariableModelBaked(baseModel);
for(IVariableModelProvider provider : VariableModelProviders.REGISTRY.getProviders()) {
bakedModel.setSubModels(provider, provider.bakeOverlayModels(bakery, spriteGetter, transform, location));
}
return bakedModel;
}
@Override
public IBakedModel bake(IModelConfiguration owner, ModelBakery bakery, Function<RenderMaterial, TextureAtlasSprite> spriteGetter, IModelTransform modelTransform, ItemOverrideList overrides, ResourceLocation modelLocation) {
return bakeModel(bakery, spriteGetter, modelTransform, modelLocation);
}
@Override
public Collection<RenderMaterial> getTextures(IModelConfiguration owner, Function<ResourceLocation, IUnbakedModel> modelGetter, Set<Pair<String, String>> missingTextureErrors) {
return getTextures(modelGetter, missingTextureErrors);
}
}
| CyclopsMC/IntegratedDynamics | src/main/java/org/cyclops/integrateddynamics/core/client/model/VariableModel.java | Java | mit | 4,860 |
package fallk.tuples;
import java.util.Iterator;
import java.util.Arrays;
import java.util.stream.Stream;
import fallk.tuples.values.IValue0;
import fallk.tuples.values.IValue1;
import fallk.tuples.values.IValue2;
import fallk.tuples.values.IValue3;
import fallk.tuples.values.IValue4;
import fallk.tuples.values.IValue5;
import fallk.tuples.values.IValue6;
import fallk.tuples.values.IValue7;
import fallk.tuples.values.IValue8;
import fallk.tuples.values.IValue9;
import fallk.tuples.values.IValue10;
import fallk.tuples.values.IValue11;
import fallk.tuples.values.IValue12;
import fallk.tuples.values.IValue13;
import fallk.tuples.values.IValue14;
import fallk.tuples.values.IValue15;
import fallk.tuples.values.IValue16;
import fallk.tuples.values.IValue17;
import fallk.tuples.values.IValue18;
import fallk.tuples.values.IValue19;
import fallk.tuples.values.IValue20;
import fallk.tuples.values.IValue21;
import fallk.tuples.values.IValue22;
import fallk.tuples.values.IValue23;
import fallk.tuples.values.IValue24;
import fallk.tuples.values.IValue25;
import fallk.tuples.values.IValue26;
import fallk.tuples.values.IValue27;
import fallk.tuples.values.IValue28;
import fallk.tuples.values.IValue29;
/**
* A tuple of 30 elements.
*/
public final class Tuple30 <K1,K2,K3,K4,K5,K6,K7,K8,K9,K10,K11,K12,K13,K14,K15,K16,K17,K18,K19,K20,K21,K22,K23,K24,K25,K26,K27,K28,K29,K30>
implements BaseTuple,
IValue0 <K1> ,
IValue1 <K2> ,
IValue2 <K3> ,
IValue3 <K4> ,
IValue4 <K5> ,
IValue5 <K6> ,
IValue6 <K7> ,
IValue7 <K8> ,
IValue8 <K9> ,
IValue9 <K10> ,
IValue10 <K11> ,
IValue11 <K12> ,
IValue12 <K13> ,
IValue13 <K14> ,
IValue14 <K15> ,
IValue15 <K16> ,
IValue16 <K17> ,
IValue17 <K18> ,
IValue18 <K19> ,
IValue19 <K20> ,
IValue20 <K21> ,
IValue21 <K22> ,
IValue22 <K23> ,
IValue23 <K24> ,
IValue24 <K25> ,
IValue25 <K26> ,
IValue26 <K27> ,
IValue27 <K28> ,
IValue28 <K29> ,
IValue29 <K30> {
private static final long serialVersionUID = -1607420937567707033L;
private final K1 val0;
private final K2 val1;
private final K3 val2;
private final K4 val3;
private final K5 val4;
private final K6 val5;
private final K7 val6;
private final K8 val7;
private final K9 val8;
private final K10 val9;
private final K11 val10;
private final K12 val11;
private final K13 val12;
private final K14 val13;
private final K15 val14;
private final K16 val15;
private final K17 val16;
private final K18 val17;
private final K19 val18;
private final K20 val19;
private final K21 val20;
private final K22 val21;
private final K23 val22;
private final K24 val23;
private final K25 val24;
private final K26 val25;
private final K27 val26;
private final K28 val27;
private final K29 val28;
private final K30 val29;
/**
* Creates a tuple with 30 elements. Pretty straightforward, isn't it?
*/
public static <K1,K2,K3,K4,K5,K6,K7,K8,K9,K10,K11,K12,K13,K14,K15,K16,K17,K18,K19,K20,K21,K22,K23,K24,K25,K26,K27,K28,K29,K30> Tuple30 <K1,K2,K3,K4,K5,K6,K7,K8,K9,K10,K11,K12,K13,K14,K15,K16,K17,K18,K19,K20,K21,K22,K23,K24,K25,K26,K27,K28,K29,K30> with(final K1 value0,
final K2 value1,
final K3 value2,
final K4 value3,
final K5 value4,
final K6 value5,
final K7 value6,
final K8 value7,
final K9 value8,
final K10 value9,
final K11 value10,
final K12 value11,
final K13 value12,
final K14 value13,
final K15 value14,
final K16 value15,
final K17 value16,
final K18 value17,
final K19 value18,
final K20 value19,
final K21 value20,
final K22 value21,
final K23 value22,
final K24 value23,
final K25 value24,
final K26 value25,
final K27 value26,
final K28 value27,
final K29 value28,
final K30 value29) {
return new Tuple30 <K1,K2,K3,K4,K5,K6,K7,K8,K9,K10,K11,K12,K13,K14,K15,K16,K17,K18,K19,K20,K21,K22,K23,K24,K25,K26,K27,K28,K29,K30> (value0,
value1,
value2,
value3,
value4,
value5,
value6,
value7,
value8,
value9,
value10,
value11,
value12,
value13,
value14,
value15,
value16,
value17,
value18,
value19,
value20,
value21,
value22,
value23,
value24,
value25,
value26,
value27,
value28,
value29);
}
/**
* Creates a tuple with 30 elements. Pretty straightforward, isn't it?
*/
public static <K1,K2,K3,K4,K5,K6,K7,K8,K9,K10,K11,K12,K13,K14,K15,K16,K17,K18,K19,K20,K21,K22,K23,K24,K25,K26,K27,K28,K29,K30> Tuple30 <K1,K2,K3,K4,K5,K6,K7,K8,K9,K10,K11,K12,K13,K14,K15,K16,K17,K18,K19,K20,K21,K22,K23,K24,K25,K26,K27,K28,K29,K30> of (final K1 value0,
final K2 value1,
final K3 value2,
final K4 value3,
final K5 value4,
final K6 value5,
final K7 value6,
final K8 value7,
final K9 value8,
final K10 value9,
final K11 value10,
final K12 value11,
final K13 value12,
final K14 value13,
final K15 value14,
final K16 value15,
final K17 value16,
final K18 value17,
final K19 value18,
final K20 value19,
final K21 value20,
final K22 value21,
final K23 value22,
final K24 value23,
final K25 value24,
final K26 value25,
final K27 value26,
final K28 value27,
final K29 value28,
final K30 value29) {
return new Tuple30 <K1,K2,K3,K4,K5,K6,K7,K8,K9,K10,K11,K12,K13,K14,K15,K16,K17,K18,K19,K20,K21,K22,K23,K24,K25,K26,K27,K28,K29,K30> (value0,
value1,
value2,
value3,
value4,
value5,
value6,
value7,
value8,
value9,
value10,
value11,
value12,
value13,
value14,
value15,
value16,
value17,
value18,
value19,
value20,
value21,
value22,
value23,
value24,
value25,
value26,
value27,
value28,
value29);
}
/**
* Create a tuple from an array. The array has to have exactly 30 elements.
*
* @param <X> the array element type
* @param array the array to be converted to a tuple
* @return the tuple
*/
public static <X> Tuple30 <X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X> fromArray(final X[] array) {
if(array == null) {
throw new IllegalArgumentException("Array cannot be null");
}
if(array.length != 30) {
throw new IllegalArgumentException("Array must have exactly 10 elements in order to create a Tuple30. Size is " + array.length);
}
return new Tuple30 <X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X> (
array[0],
array[1],
array[2],
array[3],
array[4],
array[5],
array[6],
array[7],
array[8],
array[9],
array[10],
array[11],
array[12],
array[13],
array[14],
array[15],
array[16],
array[17],
array[18],
array[19],
array[20],
array[21],
array[22],
array[23],
array[24],
array[25],
array[26],
array[27],
array[28],
array[29]
);
}
/**
* Create tuple from an iterable. It must have exactly 30 elements or less remaining.
*
* @param <X> the iterable component type
* @param iterable the iterable to be converted to a tuple
* @return the tuple
*/
public static <X> Tuple30 <X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X> fromIterable(final Iterable <X> iterable) {
return fromIterable(iterable.iterator());
}
private static <X> Tuple30 <X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X> fromIterable(final Iterator <X> iter) {
if(iter == null) {
throw new NullPointerException("Iterator cannot be null");
}
X element0 = null;
X element1 = null;
X element2 = null;
X element3 = null;
X element4 = null;
X element5 = null;
X element6 = null;
X element7 = null;
X element8 = null;
X element9 = null;
X element10 = null;
X element11 = null;
X element12 = null;
X element13 = null;
X element14 = null;
X element15 = null;
X element16 = null;
X element17 = null;
X element18 = null;
X element19 = null;
X element20 = null;
X element21 = null;
X element22 = null;
X element23 = null;
X element24 = null;
X element25 = null;
X element26 = null;
X element27 = null;
X element28 = null;
X element29 = null;
if(iter.hasNext()) {
element0 = iter.next();
}
if(iter.hasNext()) {
element1 = iter.next();
}
if(iter.hasNext()) {
element2 = iter.next();
}
if(iter.hasNext()) {
element3 = iter.next();
}
if(iter.hasNext()) {
element4 = iter.next();
}
if(iter.hasNext()) {
element5 = iter.next();
}
if(iter.hasNext()) {
element6 = iter.next();
}
if(iter.hasNext()) {
element7 = iter.next();
}
if(iter.hasNext()) {
element8 = iter.next();
}
if(iter.hasNext()) {
element9 = iter.next();
}
if(iter.hasNext()) {
element10 = iter.next();
}
if(iter.hasNext()) {
element11 = iter.next();
}
if(iter.hasNext()) {
element12 = iter.next();
}
if(iter.hasNext()) {
element13 = iter.next();
}
if(iter.hasNext()) {
element14 = iter.next();
}
if(iter.hasNext()) {
element15 = iter.next();
}
if(iter.hasNext()) {
element16 = iter.next();
}
if(iter.hasNext()) {
element17 = iter.next();
}
if(iter.hasNext()) {
element18 = iter.next();
}
if(iter.hasNext()) {
element19 = iter.next();
}
if(iter.hasNext()) {
element20 = iter.next();
}
if(iter.hasNext()) {
element21 = iter.next();
}
if(iter.hasNext()) {
element22 = iter.next();
}
if(iter.hasNext()) {
element23 = iter.next();
}
if(iter.hasNext()) {
element24 = iter.next();
}
if(iter.hasNext()) {
element25 = iter.next();
}
if(iter.hasNext()) {
element26 = iter.next();
}
if(iter.hasNext()) {
element27 = iter.next();
}
if(iter.hasNext()) {
element28 = iter.next();
}
if(iter.hasNext()) {
element29 = iter.next();
}
return new Tuple30 <X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X,X> (
element0,
element1,
element2,
element3,
element4,
element5,
element6,
element7,
element8,
element9,
element10,
element11,
element12,
element13,
element14,
element15,
element16,
element17,
element18,
element19,
element20,
element21,
element22,
element23,
element24,
element25,
element26,
element27,
element28,
element29
);
}
private Tuple30(
final K1 value0,
final K2 value1,
final K3 value2,
final K4 value3,
final K5 value4,
final K6 value5,
final K7 value6,
final K8 value7,
final K9 value8,
final K10 value9,
final K11 value10,
final K12 value11,
final K13 value12,
final K14 value13,
final K15 value14,
final K16 value15,
final K17 value16,
final K18 value17,
final K19 value18,
final K20 value19,
final K21 value20,
final K22 value21,
final K23 value22,
final K24 value23,
final K25 value24,
final K26 value25,
final K27 value26,
final K28 value27,
final K29 value28,
final K30 value29
) {
this.val0 = value0;
this.val1 = value1;
this.val2 = value2;
this.val3 = value3;
this.val4 = value4;
this.val5 = value5;
this.val6 = value6;
this.val7 = value7;
this.val8 = value8;
this.val9 = value9;
this.val10 = value10;
this.val11 = value11;
this.val12 = value12;
this.val13 = value13;
this.val14 = value14;
this.val15 = value15;
this.val16 = value16;
this.val17 = value17;
this.val18 = value18;
this.val19 = value19;
this.val20 = value20;
this.val21 = value21;
this.val22 = value22;
this.val23 = value23;
this.val24 = value24;
this.val25 = value25;
this.val26 = value26;
this.val27 = value27;
this.val28 = value28;
this.val29 = value29;
}
/**
* Gets the value at index 0.
* @return the value at index 0.
*/
@Override
public K1 getValue0() {
return this.val0;
}
/**
* Gets the value at index 0.
* @return the value at index 0.
*/
@Override
public K1 get0() {
return this.val0;
}
/**
* Gets the value at index 1.
* @return the value at index 1.
*/
@Override
public K2 getValue1() {
return this.val1;
}
/**
* Gets the value at index 1.
* @return the value at index 1.
*/
@Override
public K2 get1() {
return this.val1;
}
/**
* Gets the value at index 2.
* @return the value at index 2.
*/
@Override
public K3 getValue2() {
return this.val2;
}
/**
* Gets the value at index 2.
* @return the value at index 2.
*/
@Override
public K3 get2() {
return this.val2;
}
/**
* Gets the value at index 3.
* @return the value at index 3.
*/
@Override
public K4 getValue3() {
return this.val3;
}
/**
* Gets the value at index 3.
* @return the value at index 3.
*/
@Override
public K4 get3() {
return this.val3;
}
/**
* Gets the value at index 4.
* @return the value at index 4.
*/
@Override
public K5 getValue4() {
return this.val4;
}
/**
* Gets the value at index 4.
* @return the value at index 4.
*/
@Override
public K5 get4() {
return this.val4;
}
/**
* Gets the value at index 5.
* @return the value at index 5.
*/
@Override
public K6 getValue5() {
return this.val5;
}
/**
* Gets the value at index 5.
* @return the value at index 5.
*/
@Override
public K6 get5() {
return this.val5;
}
/**
* Gets the value at index 6.
* @return the value at index 6.
*/
@Override
public K7 getValue6() {
return this.val6;
}
/**
* Gets the value at index 6.
* @return the value at index 6.
*/
@Override
public K7 get6() {
return this.val6;
}
/**
* Gets the value at index 7.
* @return the value at index 7.
*/
@Override
public K8 getValue7() {
return this.val7;
}
/**
* Gets the value at index 7.
* @return the value at index 7.
*/
@Override
public K8 get7() {
return this.val7;
}
/**
* Gets the value at index 8.
* @return the value at index 8.
*/
@Override
public K9 getValue8() {
return this.val8;
}
/**
* Gets the value at index 8.
* @return the value at index 8.
*/
@Override
public K9 get8() {
return this.val8;
}
/**
* Gets the value at index 9.
* @return the value at index 9.
*/
@Override
public K10 getValue9() {
return this.val9;
}
/**
* Gets the value at index 9.
* @return the value at index 9.
*/
@Override
public K10 get9() {
return this.val9;
}
/**
* Gets the value at index 10.
* @return the value at index 10.
*/
@Override
public K11 getValue10() {
return this.val10;
}
/**
* Gets the value at index 10.
* @return the value at index 10.
*/
@Override
public K11 get10() {
return this.val10;
}
/**
* Gets the value at index 11.
* @return the value at index 11.
*/
@Override
public K12 getValue11() {
return this.val11;
}
/**
* Gets the value at index 11.
* @return the value at index 11.
*/
@Override
public K12 get11() {
return this.val11;
}
/**
* Gets the value at index 12.
* @return the value at index 12.
*/
@Override
public K13 getValue12() {
return this.val12;
}
/**
* Gets the value at index 12.
* @return the value at index 12.
*/
@Override
public K13 get12() {
return this.val12;
}
/**
* Gets the value at index 13.
* @return the value at index 13.
*/
@Override
public K14 getValue13() {
return this.val13;
}
/**
* Gets the value at index 13.
* @return the value at index 13.
*/
@Override
public K14 get13() {
return this.val13;
}
/**
* Gets the value at index 14.
* @return the value at index 14.
*/
@Override
public K15 getValue14() {
return this.val14;
}
/**
* Gets the value at index 14.
* @return the value at index 14.
*/
@Override
public K15 get14() {
return this.val14;
}
/**
* Gets the value at index 15.
* @return the value at index 15.
*/
@Override
public K16 getValue15() {
return this.val15;
}
/**
* Gets the value at index 15.
* @return the value at index 15.
*/
@Override
public K16 get15() {
return this.val15;
}
/**
* Gets the value at index 16.
* @return the value at index 16.
*/
@Override
public K17 getValue16() {
return this.val16;
}
/**
* Gets the value at index 16.
* @return the value at index 16.
*/
@Override
public K17 get16() {
return this.val16;
}
/**
* Gets the value at index 17.
* @return the value at index 17.
*/
@Override
public K18 getValue17() {
return this.val17;
}
/**
* Gets the value at index 17.
* @return the value at index 17.
*/
@Override
public K18 get17() {
return this.val17;
}
/**
* Gets the value at index 18.
* @return the value at index 18.
*/
@Override
public K19 getValue18() {
return this.val18;
}
/**
* Gets the value at index 18.
* @return the value at index 18.
*/
@Override
public K19 get18() {
return this.val18;
}
/**
* Gets the value at index 19.
* @return the value at index 19.
*/
@Override
public K20 getValue19() {
return this.val19;
}
/**
* Gets the value at index 19.
* @return the value at index 19.
*/
@Override
public K20 get19() {
return this.val19;
}
/**
* Gets the value at index 20.
* @return the value at index 20.
*/
@Override
public K21 getValue20() {
return this.val20;
}
/**
* Gets the value at index 20.
* @return the value at index 20.
*/
@Override
public K21 get20() {
return this.val20;
}
/**
* Gets the value at index 21.
* @return the value at index 21.
*/
@Override
public K22 getValue21() {
return this.val21;
}
/**
* Gets the value at index 21.
* @return the value at index 21.
*/
@Override
public K22 get21() {
return this.val21;
}
/**
* Gets the value at index 22.
* @return the value at index 22.
*/
@Override
public K23 getValue22() {
return this.val22;
}
/**
* Gets the value at index 22.
* @return the value at index 22.
*/
@Override
public K23 get22() {
return this.val22;
}
/**
* Gets the value at index 23.
* @return the value at index 23.
*/
@Override
public K24 getValue23() {
return this.val23;
}
/**
* Gets the value at index 23.
* @return the value at index 23.
*/
@Override
public K24 get23() {
return this.val23;
}
/**
* Gets the value at index 24.
* @return the value at index 24.
*/
@Override
public K25 getValue24() {
return this.val24;
}
/**
* Gets the value at index 24.
* @return the value at index 24.
*/
@Override
public K25 get24() {
return this.val24;
}
/**
* Gets the value at index 25.
* @return the value at index 25.
*/
@Override
public K26 getValue25() {
return this.val25;
}
/**
* Gets the value at index 25.
* @return the value at index 25.
*/
@Override
public K26 get25() {
return this.val25;
}
/**
* Gets the value at index 26.
* @return the value at index 26.
*/
@Override
public K27 getValue26() {
return this.val26;
}
/**
* Gets the value at index 26.
* @return the value at index 26.
*/
@Override
public K27 get26() {
return this.val26;
}
/**
* Gets the value at index 27.
* @return the value at index 27.
*/
@Override
public K28 getValue27() {
return this.val27;
}
/**
* Gets the value at index 27.
* @return the value at index 27.
*/
@Override
public K28 get27() {
return this.val27;
}
/**
* Gets the value at index 28.
* @return the value at index 28.
*/
@Override
public K29 getValue28() {
return this.val28;
}
/**
* Gets the value at index 28.
* @return the value at index 28.
*/
@Override
public K29 get28() {
return this.val28;
}
/**
* Gets the value at index 29.
* @return the value at index 29.
*/
@Override
public K30 getValue29() {
return this.val29;
}
/**
* Gets the value at index 29.
* @return the value at index 29.
*/
@Override
public K30 get29() {
return this.val29;
}
/**
* @return the first / leftmost element in this tuple.
*/
@Override
public K1 getLeft() {
return this.val0;
}
/**
* @return the last / rightmost element in this tuple.
*/
@Override
public K30 getRight() {
return this.val29;
}
/**
* @return a stream containing each element in this tuple in its current state.
*/
public Stream <Object> stream() {
return Arrays.stream(new Object[] {
val0,
val1,
val2,
val3,
val4,
val5,
val6,
val7,
val8,
val9,
val10,
val11,
val12,
val13,
val14,
val15,
val16,
val17,
val18,
val19,
val20,
val21,
val22,
val23,
val24,
val25,
val26,
val27,
val28,
val29
});
}
/**
* @return an array representation of this tuple.
*/
public Object[] toArray() {
return new Object[] {
val0,
val1,
val2,
val3,
val4,
val5,
val6,
val7,
val8,
val9,
val10,
val11,
val12,
val13,
val14,
val15,
val16,
val17,
val18,
val19,
val20,
val21,
val22,
val23,
val24,
val25,
val26,
val27,
val28,
val29
};
}
/**
* @return an array representation of this tuple.
*/
public String toString() {
return "Tuple30 [" + Arrays.toString(new Object[] {
val0,
val1,
val2,
val3,
val4,
val5,
val6,
val7,
val8,
val9,
val10,
val11,
val12,
val13,
val14,
val15,
val16,
val17,
val18,
val19,
val20,
val21,
val22,
val23,
val24,
val25,
val26,
val27,
val28,
val29
}) + "]";
}
@Override
public int getSize() {
return 30;
}
} | fallk/JFunktion | src/main/java/fallk/tuples/Tuple30.java | Java | mit | 31,234 |
package tonius.neiintegration;
import java.util.List;
import org.apache.logging.log4j.Logger;
import tonius.neiintegration.config.Config;
import tonius.neiintegration.mods.Integrations;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.relauncher.Side;
@Mod(modid = NEIIntegration.MODID, version = NEIIntegration.VERSION, acceptableRemoteVersions = NEIIntegration.ACCEPTABLE_REMOTE_VERSIONS, guiFactory = NEIIntegration.GUI_FACTORY)
public class NEIIntegration {
public static final String MODID = "neiintegration";
public static final String VERSION = "@VERSION@";
public static final String ACCEPTABLE_REMOTE_VERSIONS = "*";
public static final String GUI_FACTORY = "tonius.neiintegration.config.ConfigGuiFactory";
@Instance(MODID)
public static NEIIntegration instance;
public static Logger log;
public static List<IntegrationBase> integrations;
@EventHandler
public void preInit(FMLPreInitializationEvent evt) {
if (evt.getSide() != Side.CLIENT) {
return;
}
log = evt.getModLog();
log.info("Starting NEI Integration");
integrations = Integrations.getIntegrations();
Config.preInit(evt);
}
}
| Tonius/NEI-Integration | src/main/java/tonius/neiintegration/NEIIntegration.java | Java | mit | 1,389 |
package com.mapsindoors.stdapp.ui.splashscreen;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.Nullable;
import com.google.android.material.snackbar.Snackbar;
import androidx.core.view.ViewCompat;
import androidx.core.view.ViewPropertyAnimatorListener;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import com.mapsindoors.mapssdk.MapsIndoors;
import com.mapsindoors.stdapp.R;
import com.mapsindoors.stdapp.helpers.MapsIndoorsUtils;
import com.mapsindoors.stdapp.ui.activitymain.MapsIndoorsActivity;
import static com.mapsindoors.stdapp.helpers.MapsIndoorsUtils.isNetworkReachable;
/**
* SplashScreenActivity
* MapsIndoorsDemo
* <p>
* Created by Jose J Varó on 03/19/2017.
* Copyright © 2017 MapsPeople A/S. All rights reserved.
*/
public class SplashScreenActivity extends AppCompatActivity {
private static final String TAG = SplashScreenActivity.class.getSimpleName();
private ViewGroup mSplashMainLayout;
private ViewGroup mSplashMainView;
private ImageView mIconStatic, mIconDynamic;
private boolean mAnimIconDone, mAnimMainViewDone;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAnimIconDone = mAnimMainViewDone = false;
setContentView(R.layout.fragment_splashscreen);
mSplashMainLayout = findViewById(R.id.splash_layout);
mSplashMainView = findViewById(R.id.splash_main);
mIconStatic = mSplashMainLayout.findViewById(R.id.splash_icon);
mIconDynamic = mSplashMainLayout.findViewById(R.id.splash_icon_2);
if (!isNetworkReachable(this) && MapsIndoors.checkOfflineDataAvailability()) {
Snackbar.make(getWindow().getDecorView().getRootView()
, getResources().getString(R.string.no_internet_snackbar_message),
Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
mSplashMainLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
//Remove the listener before proceeding
mSplashMainLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int dstTop = mIconStatic.getTop();
int srcTop = mIconDynamic.getTop();
animateIcon(dstTop - srcTop);
}
});
}
void animateIcon(int toTopPos) {
ViewCompat.animate(mIconDynamic)
.translationY(toTopPos)
.setDuration(500)
//.setInterpolator( new DecelerateInterpolator() )
.setListener(new ViewPropertyAnimatorListener() {
@Override
public void onAnimationStart(View view) {
mAnimIconDone = false;
animateMainView(0);
}
@Override
public void onAnimationEnd(View view) {
mAnimIconDone = true;
view.setAlpha(1f);
continueToGooglePlayServicesCheck();
}
@Override
public void onAnimationCancel(View view) {
}
})
.setStartDelay(125);
}
void animateMainView(int initDelay) {
ViewCompat.animate(mSplashMainView)
.alpha(1f)
.setDuration(250)
.setListener(new ViewPropertyAnimatorListener() {
@Override
public void onAnimationStart(View view) {
mAnimMainViewDone = false;
}
@Override
public void onAnimationEnd(View view) {
mAnimMainViewDone = true;
view.setAlpha(1f);
continueToGooglePlayServicesCheck();
}
@Override
public void onAnimationCancel(View view) {
}
})
.setStartDelay(initDelay);
}
void continueToGooglePlayServicesCheck() {
if (mAnimIconDone && mAnimMainViewDone) {
if (MapsIndoorsUtils.CheckGooglePlayServices(this)) {
prepareNextActivity();
}
}
}
private void prepareNextActivity() {
// final long timeToWait = getSplashScreenDelay();
final long timeToWait = 0;
final Class clazz = MapsIndoorsActivity.class;
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(() -> startNextActivity(clazz), timeToWait);
}
void startNextActivity(Class clazz) {
Intent intent = new Intent(SplashScreenActivity.this, clazz);
startActivity(intent);
overridePendingTransition(0, 0);
finish();
}
}
| MapsIndoors/MapsIndoorsAndroid | app/src/main/java/com/mapsindoors/stdapp/ui/splashscreen/SplashScreenActivity.java | Java | mit | 5,213 |
package fr.lteconsulting.hexa.databinding.properties;
import fr.lteconsulting.hexa.classinfo.Clazz;
/**
* Utility class supporting the concept of Property.
*
* A Property on an object is a value that can be get and/or set through either
* a getter/setter or directly through the object's field.
*
* @author Arnaud Tournier (c) LTE Consulting - 2015 http://www.lteconsulting.fr
*
*/
public class Properties
{
private final static PropertyValues propertyValues = new PropertyValues();
private final static PropertyChanges propertyChanges = new PropertyChanges();
/**
* Returns the class of the property
*
* @param clazz
* @param name
* @return
*/
public static Class<?> getPropertyType( Clazz<?> clazz, String name )
{
return propertyValues.getPropertyType(clazz, name);
}
/**
* Gets the property's value from an object
*
* @param object
* The object
* @param name
* Property name
* @return
*/
public static <T> T getValue( Object object, String name )
{
return propertyValues.getValue(object, name);
}
/**
* Sets a value on an object's property
*
* @param object the object on which the property is set
* @param propertyName the name of the property value to be set
* @param value the new value of the property
*/
public static boolean setValue( Object object, String propertyName, Object value )
{
return propertyValues.setValue(object, propertyName, value);
}
/**
* Registers an handler for a specific property change on an object. The object
* itself does not need to implement anything. But at least it should call the
* {@link notify(Object, String)} method when its internal property changes.
*
* @param source The object from which one wants notifications
* @param propertyName The property subscribed. You can use "*" to subscribe to all properties in one time
* @param handler
* @return
*/
public static Object register( Object source, String propertyName, PropertyChangedHandler handler )
{
return propertyChanges.register(source, propertyName, handler);
}
/**
* Unregisters a handler, freeing associated resources
*
* @param handlerRegistration The object received after a call to {@link PropertyChanges}
*/
public static void removeHandler( Object handlerRegistration )
{
propertyChanges.removeHandler(handlerRegistration);
}
/**
* Notifies the Hexa event system of an object changing one of
* its properties.
*
* @param sender The object whom property changed
* @param propertyName The changed property name
*/
public static void notify( Object sender, String propertyName )
{
propertyChanges.notify( sender, propertyName );
}
/**
* Obtain useful information for debugging. That's useful
* to detect registration leaks.
*/
public static String getStatistics()
{
return propertyChanges.getStatistics();
}
/**
* Whether a getter or a field is available with that name
*
* @param clazz
* @param name
* @return
*/
public static boolean hasSomethingToGetField( Clazz<?> clazz, String name )
{
return propertyValues.hasSomethingToGetField(clazz, name);
}
/**
* Return the property getter type
*
* @param clazz
* @param name
* @return
*/
public static Class<?> getGetterPropertyType( Clazz<?> clazz, String name )
{
return propertyValues.getGetterPropertyType(clazz, name);
}
/**
* Whether there is a setter or a field to write this property
*/
public static boolean hasSomethingToSetField( Clazz<?> clazz, String name )
{
return propertyValues.hasSomethingToSetField(clazz, name);
}
/**
* Returns the class of the setter property. It can be the class of the first
* argument in the setter or the class of the field if no setter is found.
* If a virtual property is used, it returns null or the class of the current
* property's value
*/
public static Class<?> getSetterPropertyType( Clazz<?> clazz, String name )
{
return propertyValues.getSetterPropertyType(clazz, name);
}
/**
* Gets a dynamic property value on an object
*
* @param object the object from which one wants to get the property value
* @param propertyName the property name
*/
public static <T> T getObjectDynamicProperty( Object object, String propertyName )
{
return propertyValues.getObjectDynamicProperty(object, propertyName);
}
/**
* Whether a dynamic property value has already been set on this object
*/
public static boolean hasObjectDynamicProperty( Object object, String propertyName )
{
return propertyValues.hasObjectDynamicProperty(object, propertyName);
}
/**
* Sets a dynamic property value on an object.
*/
public static void setObjectDynamicProperty( Object object, String propertyName, Object value )
{
propertyValues.setObjectDynamicProperty(object, propertyName, value);
}
}
| ltearno/hexa.tools | hexa.binding/src/main/java/fr/lteconsulting/hexa/databinding/properties/Properties.java | Java | mit | 4,853 |
package com.softwareverde.http.server.servlet.request;
import com.softwareverde.http.HttpMethod;
import com.softwareverde.http.cookie.Cookie;
import com.softwareverde.http.form.MultiPartFormData;
import com.softwareverde.http.querystring.GetParameters;
import com.softwareverde.http.querystring.PostParameters;
import com.softwareverde.util.Util;
import java.util.ArrayList;
import java.util.List;
public class Request {
/**
* Returns true if the header is a WebSocket initialization header (aka: "Upgrade WebSocket").
*/
public static Boolean isWebSocketHeader(final String headerKey, final String headerValue) {
return (Util.areEqual("upgrade", Util.coalesce(headerKey).toLowerCase()) && Util.areEqual("websocket", Util.coalesce(headerValue).toLowerCase()));
}
protected HostInformation _remoteHost; // the client connecting to the server
protected HostInformation _localHost; // the server itself (e.x.: "softwareverde.com")
protected String _filePath; // The filepath of the request-url. (e.x.: "/index.html")
protected HttpMethod _method;
protected final Headers _headers = new Headers();
protected final List<Cookie> _cookies = new ArrayList<Cookie>();
protected GetParameters _getParameters;
protected PostParameters _postParameters;
protected MultiPartFormData _multiPartFormData;
protected String _rawQueryString; // (e.x. "?key=value")
protected byte[] _rawPostData;
public HostInformation getRemoteHostInformation() { return _remoteHost; }
public HostInformation getLocalHostInformation() { return _localHost; }
@Deprecated
public String resolveHostname() { return _localHost.resolveHostName(); }
@Deprecated
public String getHostname() { return _localHost.getHostInfo(); }
public String getFilePath() { return _filePath; }
public HttpMethod getMethod() { return _method; }
public GetParameters getGetParameters() { return _getParameters; }
public PostParameters getPostParameters() { return _postParameters; }
public Headers getHeaders() {
return new Headers(_headers);
}
public List<Cookie> getCookies() { return Util.copyList(_cookies); }
public Cookie getCookie(final String cookieName) {
for (final Cookie cookie : _cookies) {
final String cookieKey = cookie.getKey();
if (Util.areEqual(cookieName.toLowerCase(), cookieKey.toLowerCase())) {
return cookie;
}
}
return null;
}
public byte[] getRawPostData() { return _rawPostData; }
public String getQueryString() { return _rawQueryString; }
public MultiPartFormData getMultiPartFormData() { return _multiPartFormData; }
}
| SoftwareVerde/http-servlet | src/main/java/com/softwareverde/http/server/servlet/request/Request.java | Java | mit | 2,739 |
package ro.pub.cs.systems.eim.lab03.phonedialier;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
public class PhoneDialerActivity extends AppCompatActivity {
private class PhoneDiallerListener implements View.OnClickListener {
@Override
public void onClick(View v) {
Button b = (Button) v;
String value = b.getText().toString();
EditText et = (EditText) findViewById(R.id.number);
String nr = et.getText().toString();
if (b == findViewById(R.id.backspace))
et.setText("");
else
et.append(value);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_dialer);
PhoneDiallerListener pdl = new PhoneDiallerListener();
findViewById(R.id.key0).setOnClickListener(pdl);
findViewById(R.id.key1).setOnClickListener(pdl);
findViewById(R.id.key2).setOnClickListener(pdl);
findViewById(R.id.key3).setOnClickListener(pdl);
findViewById(R.id.key4).setOnClickListener(pdl);
findViewById(R.id.key5).setOnClickListener(pdl);
findViewById(R.id.key6).setOnClickListener(pdl);
findViewById(R.id.key7).setOnClickListener(pdl);
findViewById(R.id.key8).setOnClickListener(pdl);
findViewById(R.id.key9).setOnClickListener(pdl);
findViewById(R.id.keyA).setOnClickListener(pdl);
findViewById(R.id.keyH).setOnClickListener(pdl);
findViewById(R.id.backspace).setOnClickListener(pdl);
findViewById(R.id.call).setOnClickListener(pdl);
findViewById(R.id.hangup).setOnClickListener(pdl);
}
}
| darius-m/EIM | Laborator03/PhoneDialier/app/src/main/java/ro/pub/cs/systems/eim/lab03/phonedialier/PhoneDialerActivity.java | Java | mit | 1,824 |
package io.wia;
public class WiaSignupRequest {
private String fullName;
private String emailAddress;
private String password;
public WiaSignupRequest(String fullName, String emailAddress, String password) {
this.fullName = fullName;
this.emailAddress = emailAddress;
this.password = password;
}
}
| wiaio/wia-android-sdk | Wia/src/main/java/io/wia/WiaSignupRequest.java | Java | mit | 344 |
/**
* This package contains all the different utility classes.
*/
package com.tactfactory.harmony.utils;
| TACTfactory/harmony-core | src/com/tactfactory/harmony/utils/package-info.java | Java | mit | 108 |
package com.softniac.connectfour.core.model;
import static com.softniac.connectfour.core.model.GameTestDataPreparator.prepareGameWithOneMoreMoveNeededToHaveADraw;
import static com.softniac.connectfour.core.model.GameTestDataPreparator.prepareGameWithOneMoreMoveNeededToWin;
import static com.softniac.connectfour.core.model.GameTestDataPreparator.prepareGameWithPlayer1Turn;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class GameTest {
private Game game;
@Test
public void shouldSetGameWinnerAndUpdateGameResultAppropriatelyWhenGameIsWon() {
String winningMovePerformerPlayerName = "player1";
game = prepareGameWithOneMoreMoveNeededToWin();
int winningMove = 0;
game.makeMove(winningMove);
assertThat(game.getGameResult()).isEqualTo(GameResult.WINNER_EMERGED);
assertThat(game.getWinnerName()).isEqualTo(winningMovePerformerPlayerName);
}
@Test
public void shouldUpdateGameResultAsDrawWhenBoardIsFullAndNobodyWon() {
game = prepareGameWithOneMoreMoveNeededToHaveADraw();
int moveThatWillCauseADraw = 6;
game.makeMove(moveThatWillCauseADraw);
assertThat(game.getGameResult()).isEqualTo(GameResult.DRAW);
assertThat(game.getWinnerName()).isNull();
}
@Test
public void shouldSwitchTurnAfterPlayersMove() {
game = prepareGameWithPlayer1Turn();
int columnIndex = 0;
game.makeMove(columnIndex);
assertThat(game.getGameState().getCurrentTurn()).isEqualTo(PlayerTurn.PLAYER2);
}
}
| marcinleja/connect-four | connect-four-core/src/test/java/com/softniac/connectfour/core/model/GameTest.java | Java | mit | 1,487 |
package com.ychstudio.ai.astar;
import com.badlogic.gdx.ai.pfa.Connection;
import com.badlogic.gdx.ai.pfa.DefaultConnection;
import com.badlogic.gdx.ai.pfa.DefaultGraphPath;
import com.badlogic.gdx.ai.pfa.GraphPath;
import com.badlogic.gdx.ai.pfa.Heuristic;
import com.badlogic.gdx.ai.pfa.PathFinder;
import com.badlogic.gdx.ai.pfa.indexed.IndexedAStarPathFinder;
import com.badlogic.gdx.ai.pfa.indexed.IndexedGraph;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
public class AStartPathFinding {
public final AStarMap map;
private final PathFinder<Node> pathfinder;
private final Heuristic<Node> heuristic;
private final GraphPath<Connection<Node>> connectionPath;
public AStartPathFinding(AStarMap map) {
this.map = map;
this.pathfinder = new IndexedAStarPathFinder<Node>(createGraph(map));
this.connectionPath = new DefaultGraphPath<Connection<Node>>();
this.heuristic = new Heuristic<Node>() {
@Override
public float estimate (Node node, Node endNode) {
// Manhattan distance
return Math.abs(endNode.x - node.x) + Math.abs(endNode.y - node.y);
}
};
}
public Node findNextNode(Vector2 source, Vector2 target) {
int sourceX = MathUtils.floor(source.x);
int sourceY = MathUtils.floor(source.y);
int targetX = MathUtils.floor(target.x);
int targetY = MathUtils.floor(target.y);
if (map == null
|| sourceX < 0 || sourceX >= map.getWidth()
|| sourceY < 0 || sourceY >= map.getHeight()
|| targetX < 0 || targetX >= map.getWidth()
|| targetY < 0 || targetY >= map.getHeight()) {
return null;
}
Node sourceNode = map.getNodeAt(sourceX, sourceY);
Node targetNode = map.getNodeAt(targetX, targetY);
connectionPath.clear();
pathfinder.searchConnectionPath(sourceNode, targetNode, heuristic, connectionPath);
return connectionPath.getCount() == 0 ? null : connectionPath.get(0).getToNode();
}
private static final int[][] NEIGHBORHOOD = new int[][] {
new int[] {-1, 0},
new int[] { 0, -1},
new int[] { 0, 1},
new int[] { 1, 0}
};
public static MyGraph createGraph (AStarMap map) {
final int height = map.getHeight();
final int width = map.getWidth();
MyGraph graph = new MyGraph(map);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
Node node = map.getNodeAt(x, y);
if (node.isWall) {
continue;
}
// Add a connection for each valid neighbor
for (int offset = 0; offset < NEIGHBORHOOD.length; offset++) {
int neighborX = node.x + NEIGHBORHOOD[offset][0];
int neighborY = node.y + NEIGHBORHOOD[offset][1];
if (neighborX >= 0 && neighborX < width && neighborY >= 0 && neighborY < height) {
Node neighbor = map.getNodeAt(neighborX, neighborY);
if (!neighbor.isWall) {
// Add connection to walkable neighbor
node.getConnections().add(new DefaultConnection<Node>(node, neighbor));
}
}
}
node.getConnections().shuffle();
}
}
return graph;
}
private static class MyGraph implements IndexedGraph<Node> {
AStarMap map;
public MyGraph (AStarMap map) {
this.map = map;
}
@Override
public int getIndex(Node node) {
return node.getIndex();
}
@Override
public Array<Connection<Node>> getConnections(Node fromNode) {
return fromNode.getConnections();
}
@Override
public int getNodeCount() {
return map.getHeight() * map.getwidth();
}
}
}
| yichen0831/Pacman_libGdx | core/src/com/ychstudio/ai/astar/AStartPathFinding.java | Java | mit | 4,140 |
package org.lpw.ranch.dbtool.schema;
import com.alibaba.fastjson.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.lpw.tephra.ctrl.validate.Validators;
/**
* @author lpw
*/
public class SaveTest extends TestSupport {
@Test
public void save() {
mockHelper.reset();
mockHelper.getRequest().addParameter("id", "id value");
mockHelper.mock("/dbtool/schema/save");
JSONObject object = mockHelper.getResponse().asJson();
Assert.assertEquals(2301, object.getIntValue("code"));
Assert.assertEquals(message.get(Validators.PREFIX + "illegal-id", message.get(SchemaModel.NAME + ".id")), object.getString("message"));
mockHelper.reset();
mockHelper.getRequest().addParameter("group", "group value");
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(2302, object.getIntValue("code"));
Assert.assertEquals(message.get(Validators.PREFIX + "illegal-id", message.get(SchemaModel.NAME + ".group")), object.getString("message"));
mockHelper.reset();
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(2303, object.getIntValue("code"));
Assert.assertEquals(message.get(Validators.PREFIX + "empty", message.get(SchemaModel.NAME + ".key")), object.getString("message"));
mockHelper.reset();
mockHelper.getRequest().addParameter("key", generator.random(101));
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(2304, object.getIntValue("code"));
Assert.assertEquals(message.get(Validators.PREFIX + "over-max-length", message.get(SchemaModel.NAME + ".key"), 100), object.getString("message"));
mockHelper.reset();
mockHelper.getRequest().addParameter("key", "key value");
mockHelper.getRequest().addParameter("type", "type value");
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(2305, object.getIntValue("code"));
Assert.assertEquals(message.get(SchemaModel.NAME + ".illegal-type"), object.getString("message"));
mockHelper.reset();
mockHelper.getRequest().addParameter("key", "key value");
mockHelper.getRequest().addParameter("type", "mysql");
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(2306, object.getIntValue("code"));
Assert.assertEquals(message.get(Validators.PREFIX + "empty", message.get(SchemaModel.NAME + ".ip")), object.getString("message"));
mockHelper.reset();
mockHelper.getRequest().addParameter("key", "key value");
mockHelper.getRequest().addParameter("type", "mysql");
mockHelper.getRequest().addParameter("ip", generator.random(101));
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(2307, object.getIntValue("code"));
Assert.assertEquals(message.get(Validators.PREFIX + "over-max-length", message.get(SchemaModel.NAME + ".ip"), 100), object.getString("message"));
mockHelper.reset();
mockHelper.getRequest().addParameter("key", "key value");
mockHelper.getRequest().addParameter("type", "mysql");
mockHelper.getRequest().addParameter("ip", "ip value");
mockHelper.getRequest().addParameter("name", generator.random(101));
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(2308, object.getIntValue("code"));
Assert.assertEquals(message.get(Validators.PREFIX + "over-max-length", message.get(SchemaModel.NAME + ".name"), 100), object.getString("message"));
mockHelper.reset();
mockHelper.getRequest().addParameter("key", "key value");
mockHelper.getRequest().addParameter("type", "mysql");
mockHelper.getRequest().addParameter("ip", "ip value");
mockHelper.getRequest().addParameter("username", generator.random(101));
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(2309, object.getIntValue("code"));
Assert.assertEquals(message.get(Validators.PREFIX + "over-max-length", message.get(SchemaModel.NAME + ".username"), 100), object.getString("message"));
mockHelper.reset();
mockHelper.getRequest().addParameter("key", "key value");
mockHelper.getRequest().addParameter("type", "mysql");
mockHelper.getRequest().addParameter("ip", "ip value");
mockHelper.getRequest().addParameter("password", generator.random(101));
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(2310, object.getIntValue("code"));
Assert.assertEquals(message.get(Validators.PREFIX + "over-max-length", message.get(SchemaModel.NAME + ".password"), 100), object.getString("message"));
mockHelper.reset();
mockHelper.getRequest().addParameter("key", "key value");
mockHelper.getRequest().addParameter("type", "mysql");
mockHelper.getRequest().addParameter("ip", "ip value");
mockHelper.getRequest().addParameter("memo", generator.random(101));
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(2311, object.getIntValue("code"));
Assert.assertEquals(message.get(Validators.PREFIX + "over-max-length", message.get(SchemaModel.NAME + ".memo"), 100), object.getString("message"));
mockHelper.reset();
mockHelper.getRequest().addParameter("key", "key value");
mockHelper.getRequest().addParameter("type", "mysql");
mockHelper.getRequest().addParameter("ip", "ip value");
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(9995, object.getIntValue("code"));
Assert.assertEquals(message.get(Validators.PREFIX + "illegal-sign"), object.getString("message"));
mockHelper.reset();
mockHelper.getRequest().addParameter("id", generator.uuid());
mockHelper.getRequest().addParameter("key", "key value");
mockHelper.getRequest().addParameter("type", "mysql");
mockHelper.getRequest().addParameter("ip", "ip value");
sign.put(mockHelper.getRequest().getMap(), null);
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(2312, object.getIntValue("code"));
Assert.assertEquals(message.get(SchemaModel.NAME + ".not-exists"), object.getString("message"));
mockHelper.reset();
mockHelper.getRequest().addParameter("sort", "1");
mockHelper.getRequest().addParameter("key", "key value");
mockHelper.getRequest().addParameter("type", "mysql");
mockHelper.getRequest().addParameter("ip", "ip value");
mockHelper.getRequest().addParameter("tables", "5");
sign.put(mockHelper.getRequest().getMap(), null);
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(0, object.getIntValue("code"));
JSONObject data = object.getJSONObject("data");
Assert.assertEquals(6, data.size());
Assert.assertNotNull(data.getString("id"));
Assert.assertEquals(1, data.getIntValue("sort"));
Assert.assertEquals("key value", data.getString("key"));
Assert.assertEquals("mysql", data.getString("type"));
Assert.assertEquals("ip value", data.getString("ip"));
Assert.assertEquals(0, data.getIntValue("tables"));
SchemaModel schema = liteOrm.findById(SchemaModel.class, data.getString("id"));
Assert.assertNull(schema.getGroup());
Assert.assertEquals(1, schema.getSort());
Assert.assertEquals("key value", schema.getKey());
Assert.assertEquals("mysql", schema.getType());
Assert.assertEquals("ip value", schema.getIp());
Assert.assertNull(schema.getName());
Assert.assertNull(schema.getUsername());
Assert.assertNull(schema.getPassword());
Assert.assertNull(schema.getMemo());
Assert.assertEquals(0, schema.getTables());
mockHelper.reset();
mockHelper.getRequest().addParameter("key", "key value");
mockHelper.getRequest().addParameter("type", "mysql");
mockHelper.getRequest().addParameter("ip", "ip value");
mockHelper.getRequest().addParameter("tables", "5");
sign.put(mockHelper.getRequest().getMap(), null);
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(2313, object.getIntValue("code"));
Assert.assertEquals(message.get(SchemaModel.NAME + ".key.exists"), object.getString("message"));
String group = generator.uuid();
mockHelper.reset();
mockHelper.getRequest().addParameter("id", schema.getId());
mockHelper.getRequest().addParameter("sort", "2");
mockHelper.getRequest().addParameter("group", group);
mockHelper.getRequest().addParameter("key", "key value");
mockHelper.getRequest().addParameter("type", "mysql");
mockHelper.getRequest().addParameter("ip", "ip value 1");
mockHelper.getRequest().addParameter("name", "name value 1");
mockHelper.getRequest().addParameter("username", "username value 1");
mockHelper.getRequest().addParameter("password", "password value 1");
mockHelper.getRequest().addParameter("memo", "memo value 1");
mockHelper.getRequest().addParameter("tables", "5");
sign.put(mockHelper.getRequest().getMap(), null);
mockHelper.mock("/dbtool/schema/save");
object = mockHelper.getResponse().asJson();
Assert.assertEquals(0, object.getIntValue("code"));
data = object.getJSONObject("data");
Assert.assertEquals(11, data.size());
Assert.assertEquals(schema.getId(), data.getString("id"));
Assert.assertEquals(2, data.getIntValue("sort"));
Assert.assertEquals(group, data.getString("group"));
Assert.assertEquals("key value", data.getString("key"));
Assert.assertEquals("mysql", data.getString("type"));
Assert.assertEquals("ip value 1", data.getString("ip"));
Assert.assertEquals("name value 1", data.getString("name"));
Assert.assertEquals("username value 1", data.getString("username"));
Assert.assertEquals("password value 1", data.getString("password"));
Assert.assertEquals("memo value 1", data.getString("memo"));
Assert.assertEquals(0, data.getIntValue("tables"));
equals(liteOrm.findById(SchemaModel.class, schema.getId()), data);
}
}
| heisedebaise/ranch | ranch-dbtool/src/test/java/org/lpw/ranch/dbtool/schema/SaveTest.java | Java | mit | 11,052 |
package com.solambda.swiffer.examples;
import com.solambda.swiffer.api.ActivityType;
public class ActivityDefinitions {
@ActivityType(name = "ParseInteger", version = "1")
public static interface ParseInteger {
}
@ActivityType(name = "FailingActivity", version = "1")
public @interface FailingActivity {
}
}
| solambda/swiffer | swiffer-examples/src/main/java/com/solambda/swiffer/examples/ActivityDefinitions.java | Java | mit | 318 |
package test.tree;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
/**
* Created by samuel on 05/08/14.
*/
public class NodeTest {
/*
@Test
public void testEquals() throws Exception {
INode aNode = NodeFactory.getRandomNode(1);
INode copyNode= aNode.getDeepCopy();
assertFalse(aNode == copyNode);
assertEquals(copyNode, aNode);
}
@Test
public void testBinaryNodeEquals() throws Exception {
INode node = new AddOperationNode(new ConstantNode(1), new ConstantNode(2));
INode copy = node.getDeepCopy();
assertFalse(node == copy);
assertEquals(copy, node);
}
@Test
public void testConditionalNode() throws Exception {
INode node = new ConditionalNode(new ConstantNode(1), new ConstantNode(2), new ConstantNode(3));
INode copy = node.getDeepCopy();
assertFalse(node == copy);
assertEquals(copy, node);
}
@Test
public void testComputationalNode() throws Exception {
INode node = new EnemyStoneAtNode(new ConstantNode(1), new ConstantNode(2));
INode copy = node.getDeepCopy();
assertFalse(node == copy);
assertEquals(copy, node);
}
@Test
public void testConstantNode() throws Exception {
INode node = new ConstantNode(2);
INode copy = node.getDeepCopy();
assertFalse(node == copy);
assertEquals(copy, node);
}*/
}
| samuelsmal/gp_connect_four_java | src/test/test/tree/NodeTest.java | Java | mit | 1,481 |
package tonmoy71.github.io.pathsensedemo.main;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.pathsense.android.sdk.location.PathsenseLocationProviderApi;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import javax.inject.Inject;
import tonmoy71.github.io.pathsensedemo.location.LocationObservable;
import tonmoy71.github.io.pathsensedemo.location.LocationUpdateReceiver;
import tonmoy71.github.io.pathsensedemo.map.GoogleMapWrapper;
/**
* Created by Fahim on 05-Apr-17.
*/
public class MainPresenter implements Observer {
private static final int LOCATION_UPDATE_INTERVAL_SECONDS = 60;
private GoogleMapWrapper mMapWrapper;
private LocationObservable mObservable = LocationObservable.getInstance();
private MainView mView;
private PathsenseLocationProviderApi mLocationApi;
private List<LatLng> mPointList = new ArrayList<>();
@Inject public MainPresenter(GoogleMapWrapper wrapper) {
this.mMapWrapper = wrapper;
}
public void initializeView(MainView mView) {
this.mView = mView;
}
public void startLocationUpdate() {
mObservable.addObserver(this);
mLocationApi = PathsenseLocationProviderApi.getInstance(mView.getContext());
mLocationApi.requestInVehicleLocationUpdates(LOCATION_UPDATE_INTERVAL_SECONDS,
LocationUpdateReceiver.class);
}
public void stopLocationUpdate() {
mLocationApi.removeInVehicleLocationUpdates();
}
@Override public void update(Observable observable, Object data) {
mView.onLocationUpdate(mObservable.getLocation());
}
public void initializeMap(GoogleMap googleMap) {
mMapWrapper.initialize(googleMap);
}
public void showCurrentPosition(double latitude, double longitude) {
mMapWrapper.showCurrentLocationMarker(new LatLng(latitude, longitude));
}
public void showPath(double lat, double lng) {
mPointList.add(new LatLng(lat, lng));
mMapWrapper.drawPolyline(mPointList);
}
}
| tonmoy71/pathsense-demo | app/src/main/java/tonmoy71/github/io/pathsensedemo/main/MainPresenter.java | Java | mit | 2,027 |
package kvj.taskw.ui;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.ShareActionProvider;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.kvj.bravo7.form.FormController;
import org.kvj.bravo7.form.impl.ViewFinder;
import org.kvj.bravo7.form.impl.bundle.ListStringBundleAdapter;
import org.kvj.bravo7.form.impl.bundle.StringBundleAdapter;
import org.kvj.bravo7.form.impl.widget.TextViewCharSequenceAdapter;
import org.kvj.bravo7.form.impl.widget.TransientAdapter;
import org.kvj.bravo7.log.Logger;
import org.kvj.bravo7.util.Tasks;
import java.util.ArrayList;
import java.util.List;
import kvj.taskw.App;
import kvj.taskw.R;
import kvj.taskw.data.AccountController;
import kvj.taskw.data.Controller;
/**
* Created by vorobyev on 12/1/15.
*/
public class RunActivity extends AppCompatActivity {
FormController form = new FormController(new ViewFinder.ActivityViewFinder(this));
Controller controller = App.controller();
Logger logger = Logger.forInstance(this);
private AccountController ac = null;
private RunAdapter adapter = null;
private kvj.taskw.data.AccountController.TaskListener progressListener = null;
private ShareActionProvider mShareActionProvider = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
RecyclerView list = (RecyclerView) findViewById(R.id.run_output);
list.setLayoutManager(new LinearLayoutManager(this));
setSupportActionBar(toolbar);
form.add(new TransientAdapter<>(new StringBundleAdapter(), null), App.KEY_ACCOUNT);
form.add(new TransientAdapter<>(new ListStringBundleAdapter(), null), App.KEY_RUN_OUTPUT);
form.add(new TextViewCharSequenceAdapter(R.id.run_command, null), App.KEY_RUN_COMMAND);
form.load(this, savedInstanceState);
progressListener = MainActivity
.setupProgressListener(this, (ProgressBar) findViewById(R.id.progress));
ac = controller.accountController(form);
if (null == ac) {
controller.messageShort("Invalid arguments");
finish();
return;
}
adapter = new RunAdapter(form.getValue(App.KEY_RUN_OUTPUT, ArrayList.class));
list.setAdapter(adapter);
toolbar.setSubtitle(ac.name());
}
private void shareAll() {
CharSequence text = adapter.allText();
if (TextUtils.isEmpty(text)) { // Error
controller.messageShort("Nothing to share");
return;
}
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, text);
sendIntent.setType("text/plain");
if (null != mShareActionProvider) {
logger.d("Share provider set");
mShareActionProvider.setShareIntent(sendIntent);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_run, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_tb_run_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
// Return true to display menu
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_tb_run_run:
run();
return true;
case R.id.menu_tb_run_copy:
copyAll();
return true;
}
return super.onOptionsItemSelected(item);
}
private void copyAll() {
CharSequence text = adapter.allText();
if (TextUtils.isEmpty(text)) { // Error
controller.messageShort("Nothing to copy");
return;
}
controller.copyToClipboard(text);
}
private void run() {
final String input = form.getValue(App.KEY_RUN_COMMAND);
if (TextUtils.isEmpty(input)) {
controller.messageShort("Input is empty");
return;
}
adapter.clear();
final AccountController.ListAggregator out = new AccountController.ListAggregator();
final AccountController.ListAggregator err = new AccountController.ListAggregator();
new Tasks.ActivitySimpleTask<Boolean>(this) {
@Override
protected Boolean doInBackground() {
int result = ac.taskCustom(input, out, err);
return 0 == result;
}
@Override
public void finish(Boolean result) {
out.data().addAll(err.data());
adapter.addAll(out.data());
shareAll();
}
}.exec();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != adapter) {
form.setValue(App.KEY_RUN_OUTPUT, adapter.data);
}
form.save(outState);
}
@Override
protected void onResume() {
super.onResume();
ac.listeners().add(progressListener, true);
}
@Override
protected void onPause() {
super.onPause();
ac.listeners().remove(progressListener);
}
class RunAdapter extends RecyclerView.Adapter<RunAdapter.RunAdapterItem> {
ArrayList<String> data = new ArrayList<>();
public RunAdapter(ArrayList<String> data) {
if (null != data) {
this.data.addAll(data);
}
}
@Override
public RunAdapterItem onCreateViewHolder(ViewGroup parent, int viewType) {
return new RunAdapterItem(LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_run_output, parent, false));
}
@Override
public void onBindViewHolder(RunAdapterItem holder, int position) {
holder.text.setText(data.get(position));
}
@Override
public int getItemCount() {
return data.size();
}
void clear() {
notifyItemRangeRemoved(0, data.size());
data.clear();
}
public synchronized void addAll(List<String> data) {
int from = getItemCount();
this.data.addAll(data);
notifyItemRangeInserted(from, data.size());
}
public CharSequence allText() {
StringBuilder sb = new StringBuilder();
for (String line : data) { // Copy to
if (sb.length() > 0) {
sb.append('\n');
}
sb.append(line);
}
return sb;
}
class RunAdapterItem extends RecyclerView.ViewHolder implements View.OnLongClickListener {
private final TextView text;
public RunAdapterItem(View itemView) {
super(itemView);
itemView.setOnLongClickListener(this);
this.text = (TextView) itemView.findViewById(R.id.run_item_text);
}
@Override
public boolean onLongClick(View v) {
controller.copyToClipboard(data.get(getAdapterPosition()));
return true;
}
}
}
}
| Doctor-Andonuts/taskwarriorandroid | app/src/main/java/kvj/taskw/ui/RunActivity.java | Java | mit | 7,963 |
package com.lc.e;
import org.junit.Test;
import static org.junit.Assert.*;
public class SameTreeTest {
SameTree solution = new SameTree();
@Test
public void test() {
assertEquals(false, solution.nonrecursive(new TreeNode(0), new TreeNode(1)));
}
}
| xxmplus/algorithms | leetcode/tst/com/lc/e/SameTreeTest.java | Java | mit | 275 |
package com.davidgjm.idea.plugins;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.davidgjm.idea.plugins.ui.GenerateDialog;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public abstract class AbstractGeneratorAction extends AnAction {
private String dialogTitle;
public AbstractGeneratorAction(String text, String dialogTitle) {
super(text);
this.dialogTitle = dialogTitle;
}
public void actionPerformed(AnActionEvent e) {
PsiClass psiClass = getPsiClassFromContext(e);
GenerateDialog dlg = new GenerateDialog(psiClass, dialogTitle);
dlg.show();
if (dlg.isOK()) {
generate(psiClass, dlg.getFields());
}
}
abstract public void generate(@NotNull final PsiClass psiClass, @NotNull final List<PsiField> fields);
protected void setNewMethod(PsiClass psiClass, String newMethodBody, String methodName) {
PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiClass.getProject());
PsiMethod newEqualsMethod = elementFactory.createMethodFromText(newMethodBody, psiClass);
PsiElement method = addOrReplaceMethod(psiClass, newEqualsMethod, methodName);
JavaCodeStyleManager.getInstance(psiClass.getProject()).shortenClassReferences(method);
}
protected PsiElement addOrReplaceMethod(PsiClass psiClass, PsiMethod newEqualsMethod, String methodName) {
PsiMethod existingEqualsMethod = findMethod(psiClass, methodName);
PsiElement method;
if (existingEqualsMethod != null) {
method = existingEqualsMethod.replace(newEqualsMethod);
} else {
method = psiClass.add(newEqualsMethod);
}
return method;
}
protected PsiMethod findMethod(PsiClass psiClass, String methodName) {
PsiMethod[] allMethods = psiClass.getAllMethods();
for (PsiMethod method : allMethods) {
if (psiClass.getName().equals(method.getContainingClass().getName()) && methodName.equals(method.getName())) {
return method;
}
}
return null;
}
@Override
public void update(AnActionEvent e) {
PsiClass psiClass = getPsiClassFromContext(e);
e.getPresentation().setEnabled(psiClass != null);
}
private PsiClass getPsiClassFromContext(AnActionEvent e) {
PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
Editor editor = e.getData(PlatformDataKeys.EDITOR);
if (psiFile == null || editor == null) {
return null;
}
int offset = editor.getCaretModel().getOffset();
PsiElement elementAt = psiFile.findElementAt(offset);
return PsiTreeUtil.getParentOfType(elementAt, PsiClass.class);
}
}
| davidgjm/generators-intellij | src/main/java/com/davidgjm/idea/plugins/AbstractGeneratorAction.java | Java | mit | 3,120 |
package com.github.dreamhead.moco.handler;
import com.github.dreamhead.moco.HttpRequest;
import com.github.dreamhead.moco.MutableHttpResponse;
import com.github.dreamhead.moco.MutableResponse;
import com.github.dreamhead.moco.Request;
import com.github.dreamhead.moco.Response;
import com.github.dreamhead.moco.internal.SessionContext;
import com.github.dreamhead.moco.model.MessageContent;
import com.google.common.net.HttpHeaders;
import com.google.common.net.MediaType;
public abstract class AbstractContentResponseHandler extends AbstractResponseHandler {
private final HeaderDetector detector = new HeaderDetector();
protected abstract MessageContent responseContent(Request request);
protected abstract MediaType getContentType(HttpRequest request);
@Override
public final void writeToResponse(final SessionContext context) {
Request request = context.getRequest();
Response response = context.getResponse();
if (request instanceof HttpRequest && response instanceof MutableHttpResponse) {
HttpRequest httpRequest = (HttpRequest) request;
MutableHttpResponse httpResponse = (MutableHttpResponse) response;
doWriteToResponse(httpRequest, httpResponse);
return;
}
MutableResponse mutableResponse = (MutableResponse) response;
mutableResponse.setContent(requireResponseContent(request));
}
private void doWriteToResponse(final HttpRequest httpRequest, final MutableHttpResponse httpResponse) {
MessageContent content = requireResponseContent(httpRequest);
httpResponse.setContent(content);
httpResponse.addHeader(HttpHeaders.CONTENT_LENGTH, content.getContent().length);
if (!detector.hasContentType(httpResponse)) {
httpResponse.addHeader(HttpHeaders.CONTENT_TYPE, getContentType(httpRequest));
}
}
private MessageContent requireResponseContent(final Request request) {
MessageContent content = responseContent(request);
if (content == null) {
throw new IllegalStateException("Message content is expected. Please make sure responseContent method has been implemented correctly");
}
return content;
}
}
| dreamhead/moco | moco-core/src/main/java/com/github/dreamhead/moco/handler/AbstractContentResponseHandler.java | Java | mit | 2,247 |
/* Copyright (c) restSQL Project Contributors. Licensed under MIT. */
package org.restsql.core.impl;
import static junit.framework.Assert.assertEquals;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.restsql.core.Factory;
import org.restsql.core.InvalidRequestException;
import org.restsql.core.Request;
import org.restsql.core.RequestFactoryHelper;
import org.restsql.core.SqlResourceException;
import org.restsql.core.Factory.SqlResourceFactoryException;
public class SqlResourceFlatOneToOneWriteTest extends SqlResourceTestBase {
@Before
public void setUp() throws SQLException, SqlResourceException{
super.setUp();
final Statement statement = connection.createStatement();
statement
.execute("INSERT INTO film (film_id,title,release_year,language_id,rental_duration,rental_rate,replacement_cost)"
+ " VALUES (5000,'ESCAPE FROM TOMORROW',2011,1,0,0,0)");
statement
.execute("INSERT INTO film (film_id,title,release_year,language_id,rental_duration,rental_rate,replacement_cost)"
+ " VALUES (5001,'BLOOD PURPLE',2012,1,0,0,0)");
statement
.execute("INSERT INTO film (film_id,title,release_year,language_id,rental_duration,rental_rate,replacement_cost)"
+ " VALUES (5002,'THE DARKENING',2012,1,0,0,0)");
statement.execute("INSERT INTO film_rating (film_rating_id,film_id,stars) VALUES (1,5000,5)");
statement.execute("INSERT INTO film_rating (film_rating_id,film_id,stars) VALUES (2,5001,1)");
statement.execute("INSERT INTO film_rating (film_rating_id,film_id,stars) VALUES (3,5002,1)");
statement.close();
sqlResource = Factory.getSqlResource("FlatOneToOne");
}
@After
public void tearDown() throws SQLException {
super.tearDown();
final Statement statement = connection.createStatement();
statement.execute("DELETE FROM film_rating");
statement.execute("DELETE FROM film WHERE film_id between 5000 and 5500");
statement.close();
}
@Test
public void testExecDelete_Flat_MultiRow() throws SqlResourceFactoryException, SqlResourceException, InvalidRequestException {
// Delete test fixture
Request request = RequestFactoryHelper.getRequest(Request.Type.DELETE, sqlResource.getName(), null, new String[] { "year",
"2012" });
final int rowsAffected = sqlResource.write(request).getRowsAffected();
assertEquals(2, rowsAffected);
// Verify one preserved
request = RequestFactoryHelper.getRequest(Request.Type.SELECT, sqlResource.getName(), new String[] { "film_id", "5000" },
null);
final List<Map<String, Object>> results = sqlResource.read(request);
assertEquals(1, results.size());
}
@Test
public void testExecDelete_Flat_SingleRow() throws SqlResourceFactoryException, SqlResourceException, InvalidRequestException {
// Update test fixture
Request request = RequestFactoryHelper.getRequest(Request.Type.DELETE, sqlResource.getName(), new String[] { "film_id",
"5000" }, null);
final int rowsAffected = sqlResource.write(request).getRowsAffected();
assertEquals(2, rowsAffected);
// Verify updates
request = RequestFactoryHelper.getRequest(Request.Type.SELECT, sqlResource.getName(), new String[] { "film_id", "5000" },
null);
final List<Map<String, Object>> results = sqlResource.read(request);
assertEquals(0, results.size());
}
@Test
public void testExecInsert_Flat_SingleRow() throws SqlResourceFactoryException, SqlResourceException, InvalidRequestException {
// Update test fixture
Request request = RequestFactoryHelper.getRequest(Request.Type.INSERT, sqlResource.getName(), null, new String[] {
"film_id", "5003", "title", "BLESSED SUN", "year", "2011", "language_id", "1", "rental_duration", "0",
"rental_rate", "0", "replacement_cost", "0", "film_rating_id", "4", "stars", "5" });
final int rowsAffected = sqlResource.write(request).getRowsAffected();
assertEquals(2, rowsAffected);
// Verify updates
request = RequestFactoryHelper.getRequest(Request.Type.SELECT, sqlResource.getName(), new String[] { "film_id", "5003" },
null);
final List<Map<String, Object>> results = sqlResource.read(request);
assertEquals(1, results.size());
AssertionHelper.assertFilmRating(results.get(0), 5003, "BLESSED SUN", 2011, 4, 5);
}
@Test
public void testExecUpdate_Flat_MultiRow() throws SqlResourceFactoryException, SqlResourceException, InvalidRequestException {
// Update test fixture
Request request = RequestFactoryHelper.getRequest(Request.Type.UPDATE, sqlResource.getName(), new String[] { "year", "2012",
"stars", "1" }, new String[] { "year", "2013", "stars", "5" });
final int rowsAffected = sqlResource.write(request).getRowsAffected();
assertEquals(4, rowsAffected);
// Verify updates
request = RequestFactoryHelper.getRequest(Request.Type.SELECT, sqlResource.getName(), null, new String[] { "stars", "5" });
List<Map<String, Object>> results = sqlResource.read(request);
assertEquals(3, results.size());
AssertionHelper.assertFilmRating(results.get(0), 5000, "ESCAPE FROM TOMORROW", 2011, 1, 5);
AssertionHelper.assertFilmRating(results.get(1), 5001, "BLOOD PURPLE", 2013, 2, 5);
AssertionHelper.assertFilmRating(results.get(2), 5002, "THE DARKENING", 2013, 3, 5);
}
@Test
public void testExecUpdate_Flat_SingleRow() throws SqlResourceFactoryException, SqlResourceException, InvalidRequestException {
// Update test fixture
Request request = RequestFactoryHelper.getRequest(Request.Type.UPDATE, sqlResource.getName(), new String[] { "film_id",
"5000" }, new String[] { "year", "2010", "title", "ESCAPE FROM YESTERDAY", "stars", "2" });
final int rowsAffected = sqlResource.write(request).getRowsAffected();
assertEquals(2, rowsAffected);
// Verify updates
request = RequestFactoryHelper.getRequest(Request.Type.SELECT, sqlResource.getName(), new String[] { "film_id", "5000" },
null);
final List<Map<String, Object>> results = sqlResource.read(request);
assertEquals(1, results.size());
AssertionHelper.assertFilmRating(results.get(0), 5000, "ESCAPE FROM YESTERDAY", 2010, 1, 2);
}
}
| restsql/restsql-test | src/org/restsql/core/impl/SqlResourceFlatOneToOneWriteTest.java | Java | mit | 6,286 |
package io.github.exaberries.boa.show.playback;
public class PlaybackSource {
private String name;
public PlaybackSource(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} | ExaBerries/litan | src/main/java/io/github/exaberries/boa/show/playback/PlaybackSource.java | Java | mit | 271 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.11.30 at 08:24:17 PM JST
//
package uk.org.siri.siri;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* Type for Notify SITUATION to Tv.
*
* <p>Java class for PublishToTvActionStructure complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="PublishToTvActionStructure">
* <complexContent>
* <extension base="{http://www.siri.org.uk/siri}ParameterisedActionStructure">
* <sequence>
* <element name="Ceefax" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="Teletext" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PublishToTvActionStructure", propOrder = {
"ceefax",
"teletext"
})
public class PublishToTvActionStructure
extends ParameterisedActionStructure
{
@XmlElement(name = "Ceefax", defaultValue = "true")
protected Boolean ceefax;
@XmlElement(name = "Teletext", defaultValue = "true")
protected Boolean teletext;
/**
* Gets the value of the ceefax property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isCeefax() {
return ceefax;
}
/**
* Sets the value of the ceefax property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setCeefax(Boolean value) {
this.ceefax = value;
}
/**
* Gets the value of the teletext property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isTeletext() {
return teletext;
}
/**
* Sets the value of the teletext property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setTeletext(Boolean value) {
this.teletext = value;
}
}
| laidig/siri-20-java | src/uk/org/siri/siri/PublishToTvActionStructure.java | Java | mit | 2,607 |
package com.javarush.test.level11.lesson11.bonus01;
/* Нужно исправить программу, чтобы компилировалась и работала
Исправь наследование в классах: (классы Cat, Dog, Pat, House, Airplane).
*/
class Solution {
class Pet {
}
private class Cat extends Pet {
}
private class Dog extends Pet {
}
private class House {
}
private class Airplane {
}
}
| ailyenko/JavaRush | src/com/javarush/test/level11/lesson11/bonus01/Solution.java | Java | mit | 460 |
package com.myapos.clientmanager.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.*;
public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
public JWTLoginFilter(String url, AuthenticationManager authManager) {
super(new AntPathRequestMatcher(url));
setAuthenticationManager(authManager);
}
@Override
public Authentication attemptAuthentication(
HttpServletRequest req, HttpServletResponse res)
throws AuthenticationException, IOException, ServletException {
// System.out.println("req password !!!!!!!: "+req.getParameter("username")+
// "req object !!!!!!!: "+req.getParameter("password"));
// Enumeration headerNames = req.getHeaderNames();
// while(headerNames.hasMoreElements()) {
// String headerName = (String)headerNames.nextElement();
// System.out.println("Header Name - " + headerName + ", Value - " + req.getHeader(headerName));
// }
// Enumeration params = req.getParameterNames();
// while(params.hasMoreElements()){
// String paramName = (String)params.nextElement();
// System.out.println("Parameter Name - "+paramName+", Value - "+req.getParameter(paramName));
// }
String json = "{ \"username\" : \""+req.getParameter("username")+"\", \"password\" : \""+req.getParameter("password")+"\" }";
AccountCredentials creds = new ObjectMapper()
.readValue(json, AccountCredentials.class);
return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(
creds.getUsername(),
creds.getPassword(),
Collections.emptyList()
)
);
}
@Override
protected void successfulAuthentication(
HttpServletRequest req,
HttpServletResponse res, FilterChain chain,
Authentication auth) throws IOException, ServletException {
TokenAuthenticationService
.addAuthentication(res, auth.getName());
chain.doFilter(req,res);
}
} | myapos/ClientManagerSpringBoot | src/main/java/com/myapos/clientmanager/security/JWTLoginFilter.java | Java | mit | 2,982 |
// This file is automatically generated.
package adila.db;
/*
* Alcatel ONE TOUCH 7042D
*
* DEVICE: YARISXL
* MODEL: ALCATEL ONE TOUCH 7042D
*/
final class yarisxl_alcatel20one20touch207042d {
public static final String DATA = "Alcatel|ONE TOUCH 7042D|";
}
| karim/adila | database/src/main/java/adila/db/yarisxl_alcatel20one20touch207042d.java | Java | mit | 268 |
package takeanote.takeanote.activity.interaction;
import takeanote.takeanote.model.Document;
/**
* Created by linard_f on 5/3/16.
*/
public interface INoteInteraction {
void onNoteSelected(Document document);
}
| TakeANote/takeanote-android | app/src/main/java/takeanote/takeanote/activity/interaction/INoteInteraction.java | Java | mit | 221 |
package array._20171101;
import annotation.NaiveApproach;
import annotation.TimeComplexity;
import java.util.Arrays;
/**
* http://www.geeksforgeeks.org/find-four-numbers-with-sum-equal-to-given-sum/
* <p>
* Given an array of integers, find all combination of four elements in the array whose sum is equal to a given value X.
* For example, if the given array is {10, 2, 3, 4, 5, 9, 7, 8} and X = 23, then your function should print “3 5 7 8” (3 + 5 + 7 + 8 = 23).
*/
public class FindFourElements {
/**
* @param arr
* @param sum
* @author GeeksforGeeks
*/
@NaiveApproach
@TimeComplexity("O(n^4)")
public static void solution1(int[] arr, int sum) {
int n = arr.length;
for (int i = 0; i < n - 3; i++) {
for (int j = i + 1; j < n - 2; j++) {
for (int k = j + 1; k < n - 1; k++) {
for (int l = k + 1; l < n; l++) {
if (arr[i] + arr[j] + arr[k] + arr[l] == sum) {
System.out.println(arr[i] + " " + arr[j] + " " + arr[k] + " " + arr[l]);
}
}
}
}
}
}
/**
* @param arr
* @param sum
* @author GeeksforGeeks
*/
@NaiveApproach
@TimeComplexity("O(n³)")
public static void solution2(int[] arr, int sum) {
Arrays.sort(arr);
int n = arr.length;
for (int i = 0; i < n - 3; i++) {
for (int j = i + 1; j < n - 2; j++) {
int l = j + 1;
int r = n - 1;
while (l < r) {
if (arr[i] + arr[j] + arr[l] + arr[r] == sum) {
System.out.println(arr[i] + " " + arr[j] + " " + arr[l] + " " + arr[r]);
l++;
r--;
} else if (arr[i] + arr[j] + arr[l] + arr[r] < sum) {
l++;
} else {
r--;
}
}
}
}
}
/**
* @param arr
* @param sum
* @author GeesforGeeks
*/
@TimeComplexity("O(n²logn)")
public static void solution3(int[] arr, int sum) {
int n = arr.length;
int size = n * (n - 1) / 2;
PairSum[] pairSums = new PairSum[size];
int k = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
PairSum pairSum = new PairSum();
pairSum.first = i;
pairSum.sec = j;
pairSum.sum = arr[i] + arr[j];
pairSums[k++] = pairSum;
}
}
Arrays.sort(pairSums);
int i = 0, j = size - 1;
while (i < size && j >= 0) {
if (pairSums[i].sum + pairSums[j].sum == sum && pairSums[i].noCommon(pairSums[j])) {
System.out.println(arr[pairSums[i].first] + " " + arr[pairSums[i].sec] + " " + arr[pairSums[j].first] + " " + arr[pairSums[j].sec]);
return;
} else if (pairSums[i].sum + pairSums[j].sum < sum) {
i++;
} else {
j--;
}
}
}
static class PairSum implements Comparable<PairSum> {
int first;
int sec;
int sum;
boolean noCommon(PairSum pairSum) {
if (this.first == pairSum.first || this.sec == pairSum.sec || this.sum == pairSum.sum) {
return false;
}
return true;
}
@Override
public int compareTo(PairSum o) {
return this.sum - o.sum;
}
}
public static void main(String[] args) {
{
System.out.println("solution 1");
solution1(new int[]{10, 20, 30, 40, 1, 2}, 91);
}
{
System.out.println("\nsolution 2");
solution2(new int[]{10, 20, 30, 40, 1, 2}, 91);
}
{
System.out.println("\nsolution 3");
solution3(new int[]{10, 20, 30, 40, 1, 2}, 91);
}
}
}
| yangdd1205/data-structures | src/main/java/array/_20171101/FindFourElements.java | Java | mit | 4,113 |
package com.example.think.chatproject.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.think.chatproject.R;
public class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
}
}
| weizhizhanghao/ChatModule | ChatProject/app/src/main/java/com/example/think/chatproject/activity/BaseActivity.java | Java | mit | 392 |
package sk.upjs.ics.paz1c.fitnesscentrum.entity;
import java.time.LocalDateTime;
public class Rezervacia {
private Long id;
private Cvicenie cvicenie;
private Zakaznik zakaznik;
private LocalDateTime casRezervacie;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Cvicenie getCvicenie() {
return cvicenie;
}
public void setCvicenie(Cvicenie cvicenie) {
this.cvicenie = cvicenie;
}
public Zakaznik getZakaznik() {
return zakaznik;
}
public void setZakaznik(Zakaznik zakaznik) {
this.zakaznik = zakaznik;
}
public LocalDateTime getCasRezervacie() {
return casRezervacie;
}
public void setCasRezervacie(LocalDateTime casRezervacie) {
this.casRezervacie = casRezervacie;
}
}
| imdyske/FitnessCentrum | src/main/java/sk/upjs/ics/paz1c/fitnesscentrum/entity/Rezervacia.java | Java | mit | 865 |
package com.peterphi.std.guice.common.retry.retry.backoff;
import com.peterphi.std.threading.Timeout;
import org.junit.Test;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
public class ExponentialBackoffTest
{
public static final Timeout ONE_MILLISECOND = new Timeout(1, TimeUnit.MILLISECONDS);
@Test
public void testGetBackoff() throws Exception
{
ExponentialBackoff svc = new ExponentialBackoff(ONE_MILLISECOND, 2);
assertEquals("initial backoff for first attempt", 1, svc.getBackoff(1));
assertEquals(2, svc.getBackoff(2));
assertEquals(4, svc.getBackoff(3));
assertEquals(8, svc.getBackoff(4));
assertEquals(16, svc.getBackoff(5));
}
@Test
public void testGetLimitedBackoff() throws Exception
{
ExponentialBackoff svc = new ExponentialBackoff(ONE_MILLISECOND, 8, Timeout.ONE_SECOND);
assertEquals("initial backoff for first attempt", 1, svc.getBackoff(1));
assertEquals(8, svc.getBackoff(2));
assertEquals(64, svc.getBackoff(3));
assertEquals(512, svc.getBackoff(4));
// Test the maximum backoff is hit
assertEquals("max backoff at 5th attempt", 1000, svc.getBackoff(5));
assertEquals("max backoff still used for subsequent attempts", 1000, svc.getBackoff(5000000));
}
}
| petergeneric/stdlib | guice/common/src/test/java/com/peterphi/std/guice/common/retry/retry/backoff/ExponentialBackoffTest.java | Java | mit | 1,259 |
package com.manywho.microservices.reporting.entities;
import java.util.UUID;
public class UserEvent extends TenantEvent {
private UUID user;
public UUID getUser() {
return user;
}
}
| manywho/reporting | src/main/java/com/manywho/microservices/reporting/entities/UserEvent.java | Java | mit | 205 |
package networking;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* A client that is created whenever something needs to be sent to the other computer.
*
* @author Lawrence Lin
*
*/
public class Client {
private String serverIP;
private int serverPort;
private Socket socket;
public Client (String serverIP, int portNum, Object obj) throws UnknownHostException,
IOException {
this.serverIP = serverIP;
this.serverPort = portNum;
establishConnection();
try {
sendObjectToServer(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Establish connection with the destination server.
*
* @throws UnknownHostException
* @throws IOException
*/
private void establishConnection() throws UnknownHostException,
IOException {
socket = new Socket(serverIP, serverPort);
}
/**
* Send the object over to the other computer.
*
* @param obj: object to be sent
* @throws IOException
* @throws ClassNotFoundException
*/
private void sendObjectToServer (Object obj) throws IOException,
ClassNotFoundException {
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(obj);
out.flush();
}
}
| Chris-Dee/utilController | src/networking/Client.java | Java | mit | 1,476 |
package com.cekurte.comparator.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.codec.digest.DigestUtils;
import com.cekurte.comparator.builder.MetadataBuilder;
import com.cekurte.comparator.contract.HashFile;
import com.cekurte.comparator.contract.Metadata;
import com.cekurte.comparator.contract.PictureMetadata;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Tag;
import com.drew.metadata.file.FileMetadataDirectory;
import com.drew.metadata.gif.GifHeaderDirectory;
import com.drew.metadata.jpeg.JpegDirectory;
import com.drew.metadata.png.PngDirectory;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonPropertyOrder({
"path",
"name",
"parent",
"absolute",
"absoluteFile",
"absolutePath",
"directory",
"file",
"hidden",
"metadata"
})
@JsonIgnoreProperties({
"md5",
"canonicalPath",
"canonicalFile",
"freeSpace",
"parentFile",
"totalSpace",
"usableSpace"
})
public class ComparableFile extends File implements HashFile {
private MetadataBuilder builder;
public ComparableFile(File file) {
super(file.getAbsolutePath());
generateMetadata();
}
private void generateMetadata()
{
builder = new MetadataBuilder();
builder.addMeta(Metadata.MIMETYPE, URLConnection.getFileNameMap().getContentTypeFor(getName()));
try {
FileInputStream fis = new FileInputStream(this);
builder.addMeta(Metadata.MD5, DigestUtils.md5Hex(fis));
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
com.drew.metadata.Metadata meta = ImageMetadataReader.readMetadata(this);
for (Directory directory : meta.getDirectories()) {
if (directory instanceof JpegDirectory) {
builder.addMeta(Metadata.TYPE, "jpg");
}
if (directory instanceof PngDirectory) {
builder.addMeta(Metadata.TYPE, "png");
}
if (directory instanceof GifHeaderDirectory) {
builder.addMeta(Metadata.TYPE, "gif");
}
System.out.println(directory.getName());
for (Tag tag : directory.getTags()) {
System.out.println(tag);
String height = null;
String width = null;
if (directory instanceof JpegDirectory) {
height = directory.getTagName(JpegDirectory.TAG_IMAGE_HEIGHT);
width = directory.getTagName(JpegDirectory.TAG_IMAGE_WIDTH);
}
if (directory instanceof PngDirectory) {
height = directory.getTagName(PngDirectory.TAG_IMAGE_HEIGHT);
width = directory.getTagName(PngDirectory.TAG_IMAGE_WIDTH);
}
if (directory instanceof GifHeaderDirectory) {
height = directory.getTagName(GifHeaderDirectory.TAG_IMAGE_HEIGHT);
width = directory.getTagName(GifHeaderDirectory.TAG_IMAGE_WIDTH);
}
if (directory instanceof FileMetadataDirectory) {
if (tag.getTagName().equals(directory.getTagName(FileMetadataDirectory.TAG_FILE_SIZE))) {
Double size = Double.parseDouble(tag.getDescription().replace(" bytes", "")) / 1024;
NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
builder.addMeta(Metadata.SIZE, nf.format(size) + " KB");
}
}
if (tag.getTagName().equals(height)) {
builder.addMeta(PictureMetadata.HEIGHT, tag.getDescription().replace(" pixels", "px"));
}
if (tag.getTagName().equals(width)) {
builder.addMeta(PictureMetadata.WIDTH, tag.getDescription().replace(" pixels", "px"));
}
}
}
} catch (ImageProcessingException | IOException e) {
throw new RuntimeException(e);
}
}
public String getMd5()
{
return builder.getMetadata().get(Metadata.MD5);
}
public Map<String, String> getMetadata()
{
return builder.getMetadata();
}
}
| jpcercal/duplicated-files | src/main/java/com/cekurte/comparator/file/ComparableFile.java | Java | mit | 4,964 |
/**
* Copyright (c) 2016-2018 TypeFox and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0,
* or the Eclipse Distribution License v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.lsp4j;
import org.eclipse.lsp4j.DynamicRegistrationCapabilities;
import org.eclipse.xtext.xbase.lib.Pure;
import org.eclipse.xtext.xbase.lib.util.ToStringBuilder;
/**
* Capabilities specific to the `textDocument/references`
*/
@SuppressWarnings("all")
public class ReferencesCapabilities extends DynamicRegistrationCapabilities {
public ReferencesCapabilities() {
}
public ReferencesCapabilities(final Boolean dynamicRegistration) {
super(dynamicRegistration);
}
@Override
@Pure
public String toString() {
ToStringBuilder b = new ToStringBuilder(this);
b.add("dynamicRegistration", getDynamicRegistration());
return b.toString();
}
@Override
@Pure
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
if (!super.equals(obj))
return false;
return true;
}
@Override
@Pure
public int hashCode() {
return super.hashCode();
}
}
| smarr/SOMns-vscode | server/org.eclipse.lsp4j-gen/org/eclipse/lsp4j/ReferencesCapabilities.java | Java | mit | 1,474 |
package net.sf.esfinge.metadata.container.reading;
import static org.apache.commons.beanutils.PropertyUtils.setProperty;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import net.sf.esfinge.metadata.AnnotationReadingException;
import net.sf.esfinge.metadata.container.AnnotationReadingProcessor;
import net.sf.esfinge.metadata.container.ContainerTarget;
public class ReflectionReferenceReadingProcessor implements AnnotationReadingProcessor {
private String containerAnnotatedField;
private Field fieldAnn;
@Override
public void initAnnotation(Annotation an, AnnotatedElement elementWithMetadata) {
fieldAnn = (Field) elementWithMetadata;
containerAnnotatedField = fieldAnn.getName();
}
@Override
public void read(AnnotatedElement elementWithMetadata, Object container, ContainerTarget target) throws AnnotationReadingException {
try {
if(target == ContainerTarget.FIELDS)
{
Field field= (Field)elementWithMetadata;
setProperty(container, containerAnnotatedField,field);
}
else if (target == ContainerTarget.PARAMETER)
{
Parameter parameter=(Parameter) elementWithMetadata;
setProperty(container, containerAnnotatedField, parameter);
}
else if(target == ContainerTarget.TYPE) {
Class clazz= (Class)elementWithMetadata;
setProperty(container, containerAnnotatedField,clazz);
}
else
{
setProperty(container, containerAnnotatedField,elementWithMetadata);
}
} catch (Exception e) {
throw new AnnotationReadingException("Cannot read and record the file "+elementWithMetadata+"in "+containerAnnotatedField,e);
}
}
} | EsfingeFramework/metadata | src/main/java/net/sf/esfinge/metadata/container/reading/ReflectionReferenceReadingProcessor.java | Java | mit | 1,764 |
// Copyright (c) 2014 Richard Long & HexBeerium
//
// Released under the MIT license ( http://opensource.org/licenses/MIT )
//
package jsonbroker.library.server.http;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import jsonbroker.library.common.auxiliary.StreamUtilities;
import jsonbroker.library.common.exception.BaseException;
import jsonbroker.library.common.http.HttpStatus;
import jsonbroker.library.common.log.Log;
public class HttpDelegate implements ConnectionDelegate {
private static Log log = Log.getLog(HttpDelegate.class);
////////////////////////////////////////////////////////////////////////////
//
private RequestHandler _httpProcessor;
////////////////////////////////////////////////////////////////////////////
HttpDelegate( RequestHandler httpProcessor) {
_httpProcessor = httpProcessor;
}
private HttpRequest readRequest( InputStream inputStream )
{
HttpRequest answer = null;
try {
answer = HttpRequestReader.readRequest(inputStream);
} catch( Exception e ) {
log.warn( e );
}
return answer;
}
private HttpResponse processRequest(HttpRequest request) {
try {
return _httpProcessor.processRequest( request );
} catch( Throwable t ) {
if( t instanceof BaseException ) {
BaseException be = (BaseException)t;
String errorDomain = be.getErrorDomain();
if( HttpStatus.ErrorDomain.NOT_FOUND_404.equals( errorDomain ) ) {
log.warnFormat( "errorDomain = '%s'; t.getMessage() = '%s'", errorDomain, t.getMessage() );
} else {
log.warn( t );
}
} else {
log.warn( t );
}
return HttpErrorHelper.toHttpResponse( t );
}
}
private boolean writeResponse( Socket socket, OutputStream outputStream, HttpResponse response ) {
if( socket.isOutputShutdown() ) {
log.warn( "socket.isOutputShutdown()" );
return false;
}
if( socket.isClosed() ) {
log.warn( "socket.isClosed()" );
return false;
}
if( !socket.isConnected() ) {
log.warn( "!socket.isConnected()" );
return false;
}
try {
HttpResponseWriter.writeResponse(response,outputStream );
} catch( BaseException e ) {
if( e.getFaultCode() == StreamUtilities.IOEXCEPTION_ON_STREAM_WRITE ) {
log.warn("IOException raised while writing response (socket closed ?)");
return false;
} else {
log.warn( e );
return false;
}
} catch ( Throwable t ) {
log.warn( t );
return false;
}
return true;
}
private void logRequestResponse(HttpRequest request, HttpResponse response, boolean writeResponseSucceded) {
int statusCode = response.getStatus();
String requestUri = request.getRequestUri();
long contentLength = 0;
if( null != response.getEntity() ) {
contentLength = response.getEntity().getContentLength();
if (null != response.getRange())
{
contentLength = response.getRange().getContentLength(contentLength);
}
}
long timeTaken = System.currentTimeMillis() - request.getCreated();
String completed;
if (writeResponseSucceded)
{
completed = "true";
} else
{
completed = "false";
}
String rangeString;
{
if (null == response.getRange())
{
rangeString = "bytes";
}
else
{
rangeString = response.getRange().toContentRange(response.getEntity().getContentLength());
}
}
log.infoFormat("status:%d uri:%s content-length:%d time-taken:%d completed:%s range:%s", statusCode, requestUri, contentLength, timeTaken, completed, rangeString);
}
@Override
public ConnectionDelegate processRequest( Socket socket, InputStream inputStream, OutputStream outputStream ) {
// get the request ...
HttpRequest request = readRequest( inputStream );
if( null == request ) {
log.debug("null == request");
return null;
}
// process the request ...
HttpResponse response = processRequest(request);
ConnectionDelegate answer = this;
if( null != response._connectionDelegate ) {
answer = response._connectionDelegate;
}
// vvv http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.10
if( request.isCloseConnectionIndicated() ) {
answer = null;
}
// ^^^ http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.10
int statusCode = response.getStatus();
if ( statusCode > 399) {
answer = null;
}
if( answer == this ) {
response.putHeader( "Connection", "keep-alive" );
} else if( answer == null ) {
response.putHeader( "Connection", "close" );
}
// write the response ...
boolean writeResponseSucceded = writeResponse( socket, outputStream, response );
// do some logging ...
logRequestResponse(request, response, writeResponseSucceded);
if (!writeResponseSucceded)
{
answer = null;
}
// if the processing completed, we will permit more requests on this socket
return answer;
}
}
| rlong/java.jsonbroker.library | src/jsonbroker/library/server/http/HttpDelegate.java | Java | mit | 5,456 |
package org.testcontainers.junit;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.testcontainers.containers.BrowserWebDriverContainer;
/**
*
*/
public class FirefoxWebDriverContainerTest extends BaseWebDriverContainerTest {
@Rule
public BrowserWebDriverContainer firefox = new BrowserWebDriverContainer()
.withCapabilities(new FirefoxOptions());
@Before
public void checkBrowserIsIndeedFirefox() {
assertBrowserNameIs(firefox, "firefox");
}
@Test
public void simpleTest() {
doSimpleWebdriverTest(firefox);
}
@Test
public void simpleExploreTest() {
doSimpleExplore(firefox);
}
}
| rnorth/test-containers | modules/selenium/src/test/java/org/testcontainers/junit/FirefoxWebDriverContainerTest.java | Java | mit | 751 |
package net.cassite.daf4j.jpa;
import net.cassite.daf4j.Data;
import net.cassite.daf4j.DataComparable;
import net.cassite.daf4j.DataIterable;
import net.cassite.daf4j.DataUtils;
import javax.persistence.*;
import java.util.*;
@Entity
public class Patient {
public DataComparable<Integer> id = new DataComparable<Integer>(this);
public Data<String> sn = new Data<String>(this);
public Data<String> name = new Data<String>(this);
public Data<String> mn = new Data<String>(this);
public Data<String> gender = new Data<String>(this);
public DataComparable<Integer> age = new DataComparable<Integer>(this);
public Data<String> phone = new Data<String>(this);
public Data<String> address = new Data<String>(this);
public Data<String> qq = new Data<String>(this);
public DataComparable<Date> addtime = new DataComparable<Date>(this);
public Data<Clinic> clinic = new Data<Clinic>(this);
public DataIterable<Outpatient, Set<Outpatient>> outpatients = new DataIterable<Outpatient, Set<Outpatient>>(new HashSet<Outpatient>(), this);
public String getAddress() {
return address.get();
}
public void setAddress(String address) {
DataUtils.set(this.address, address);
}
public void setOutpatients(Set<Outpatient> outpatients) {
DataUtils.set(this.outpatients, outpatients);
}
@ManyToOne
public Clinic getClinic() {
return clinic.get();
}
public void setClinic(Clinic clinic) {
DataUtils.set(this.clinic, clinic);
}
@OneToMany(mappedBy = "patient")
public Set<Outpatient> getOutpatients() {
return outpatients.get();
}
public void setOutpatient(Set<Outpatient> outpatients) {
DataUtils.set(this.outpatients, outpatients);
}
@Id
@GeneratedValue
public Integer getId() {
return id.get();
}
public void setId(Integer id) {
DataUtils.set(this.id, id);
}
public String getSn() {
return sn.get();
}
public void setSn(String sn) {
DataUtils.set(this.sn, sn);
}
public String getName() {
return name.get();
}
public void setName(String name) {
DataUtils.set(this.name, name);
}
public String getMn() {
return mn.get();
}
public void setMn(String mn) {
DataUtils.set(this.mn, mn);
}
public String getGender() {
return gender.get();
}
public void setGender(String gender) {
DataUtils.set(this.gender, gender);
}
public Integer getAge() {
return age.get();
}
public void setAge(Integer age) {
DataUtils.set(this.age, age);
}
public String getPhone() {
return phone.get();
}
public void setPhone(String phone) {
DataUtils.set(this.phone, phone);
}
public String getQq() {
return qq.get();
}
public void setQq(String qq) {
DataUtils.set(this.qq, qq);
}
public Date getAddtime() {
return addtime.get();
}
public void setAddtime(Date addtime) {
DataUtils.set(this.addtime, addtime);
}
}
| wkgcass/common | DataFacadeJPA/src/test/java/net/cassite/daf4j/jpa/Patient.java | Java | mit | 3,285 |
package br.jus.trf2.balcaojus.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
* The persistent class for the sinal database table.
*
*/
@Entity
@Table(name = "padrao")
@NamedQueries({
// findPadroesDoUsuario
@NamedQuery(name = "Padrao.findPadroesDoUsuario", query = "select s from Padrao s where s.padrCdUsu = :usuario order by s.padrDfInclusao desc") })
public class Padrao implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "PADR_ID")
private Long padrId;
@ManyToOne
@JoinColumn(name = "SIST_ID", nullable = true)
private Sistema sistema;
@Column(name = "PADR_CD_PROC", nullable = true)
private String padrCdProc;
@Column(name = "PADR_CD_USU", nullable = false)
private String padrCdUsu;
@Column(name = "PADR_DF_INCLUSAO", nullable = false)
private Date padrDfInclusao;
@Column(name = "PADR_DF_MODIFICACAO", nullable = false)
private Date padrDfModificacao;
@Lob
@Column(name = "PADR_TX_CONTEUDO", nullable = false)
private String padrTxConteudo;
public Padrao() {
}
public Long getPadrId() {
return padrId;
}
public void setPadrId(Long padrId) {
this.padrId = padrId;
}
public Sistema getSistema() {
return sistema;
}
public void setSistema(Sistema sistema) {
this.sistema = sistema;
}
public String getPadrCdProc() {
return padrCdProc;
}
public void setPadrCdProc(String padrCdProc) {
this.padrCdProc = padrCdProc;
}
public String getPadrCdUsu() {
return padrCdUsu;
}
public void setPadrCdUsu(String padrCdUsu) {
this.padrCdUsu = padrCdUsu;
}
public Date getPadrDfInclusao() {
return padrDfInclusao;
}
public void setPadrDfInclusao(Date padrDfInclusao) {
this.padrDfInclusao = padrDfInclusao;
}
public Date getPadrDfModificacao() {
return padrDfModificacao;
}
public void setPadrDfModificacao(Date padrDfModificacao) {
this.padrDfModificacao = padrDfModificacao;
}
public String getPadrTxConteudo() {
return padrTxConteudo;
}
public void setPadrTxConteudo(String padrTxConteudo) {
this.padrTxConteudo = padrTxConteudo;
}
} | trf2-jus-br/balcaovirtual | src/main/java/br/jus/trf2/balcaojus/model/Padrao.java | Java | mit | 2,535 |
package com.ankymtan.couplechat.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import com.github.nkzawa.socketio.androidchat.R;
import java.util.ArrayList;
/**
* Created by ankym on 16/8/2015.
*/
public class AdapterPluginSetting extends ArrayAdapter{
Context context;
public AdapterPluginSetting(Context context){
super(context, R.layout.setting_row_style_1);
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.setting_row_style_1, parent, false);
viewHolder = new ViewHolder();
viewHolder.imIcon = (ImageView) convertView.findViewById(R.id.iv_setting_icon);
viewHolder.tvSettingName = (TextView) convertView.findViewById(R.id.tv_setting_name);
viewHolder.tvSettingDetail = (TextView) convertView.findViewById(R.id.tv_setting_detail);
viewHolder.settingSwitch = (Switch) convertView.findViewById(R.id.switch_setting);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
switch (position){
case 0:
viewHolder.setIcon(R.drawable.power);
viewHolder.setTvSettingName("Power");
viewHolder.setTvSettingDetail("Turn on/off the plugin");
viewHolder.showSwitch();
break;
case 1:
viewHolder.setIcon(R.drawable.add);
viewHolder.setTvSettingName("Choose affected friends");
viewHolder.setTvSettingDetail("Pick friends in your friend list to be applied this plugin");
viewHolder.hideSwitch();
break;
case 2:
viewHolder.setIcon(R.drawable.agent);
viewHolder.setTvSettingName("Choose Plugin");
viewHolder.setTvSettingDetail("Choose Plugin in the list");
viewHolder.hideSwitch();
break;
case 3:
viewHolder.setIcon(R.drawable.hello);
viewHolder.setTvSettingName("Say hello");
viewHolder.setTvSettingDetail("Say hello every period of time");
viewHolder.showSwitch();
break;
case 4:
viewHolder.setIcon(R.drawable.birthday);
viewHolder.setTvSettingName("Happy birthday");
viewHolder.setTvSettingDetail("Remind on friends' birthdays");
viewHolder.showSwitch();
break;
}
return convertView;
}
@Override
public int getCount() {
return 5;
}
private class ViewHolder {
ImageView imIcon;
TextView tvSettingName, tvSettingDetail;
Switch settingSwitch;
public void setIcon(int iconId){
imIcon.setImageResource(iconId);
}
public void setTvSettingName(String settingName){
tvSettingName.setText(settingName);
}
public void setTvSettingDetail(String settingDetail){
tvSettingDetail.setText(settingDetail);
}
public void hideSwitch(){
settingSwitch.setVisibility(View.INVISIBLE);
}
public void showSwitch(){
settingSwitch.setVisibility(View.VISIBLE);
}
}
}
| ankymtan/ChatApp | app/src/main/java/com/ankymtan/couplechat/adapter/AdapterPluginSetting.java | Java | mit | 3,808 |
package org.craft.spoonge.events.state;
import org.craft.*;
import org.spongepowered.api.event.state.*;
public class SpoongeServerAboutToStartEvent extends SpoongeStateEvent implements ServerAboutToStartEvent
{
public SpoongeServerAboutToStartEvent(OurCraftInstance game)
{
super(game);
}
@Override
public boolean isCancellable()
{
return false;
}
}
| OurCraft/Spoonge | src/main/java/org/craft/spoonge/events/state/SpoongeServerAboutToStartEvent.java | Java | mit | 399 |
package edu.nyu.mpgarate.pqs1;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import edu.nyu.mpgarate.pqs1.AddressBook;
import edu.nyu.mpgarate.pqs1.Contact;
import edu.nyu.mpgarate.pqs1.ContactBuilder;
public class AddressBookTest {
private AddressBook addressBook;
@Before
public void initialize() {
addressBook = new AddressBook();
}
@Test
public void createEmptyAddressBook() {
assertEquals(addressBook.size(), 0);
}
@Test
public void addAnEmptyContact() {
ContactBuilder builder = new ContactBuilder();
addressBook.add(builder.build());
assertEquals(addressBook.size(), 1);
}
@Test
public void removeAnEmptyContact() {
ContactBuilder builder = new ContactBuilder();
Contact contact = builder.build();
addressBook.add(contact);
assertEquals(addressBook.size(), 1);
addressBook.remove(contact.getUniqueId());
assertEquals(addressBook.size(), 0);
}
@Test
public void findAContact() {
ContactBuilder builder = new ContactBuilder();
Contact contact = builder.build();
addressBook.add(contact);
Contact foundContact = addressBook.find(contact.getUniqueId());
assertEquals(foundContact.getUniqueId(), contact.getUniqueId());
}
@Test
public void updateAnEmptyContact() {
Contact contact = new ContactBuilder().build();
addressBook.add(contact);
Contact foundContact = addressBook.find(contact.getUniqueId());
String newName = "John Doe";
Contact modifiedContact =
new ContactBuilder(foundContact).withName(newName).build();
addressBook.update(modifiedContact);
contact = addressBook.find(modifiedContact.getUniqueId());
assertEquals(newName, contact.getName());
}
@Test
public void contactsInAlphaNumericalOrderByName() {
addressBook.add(new ContactBuilder().withName("beth").build());
addressBook.add(new ContactBuilder().withName(":)").build());
addressBook.add(new ContactBuilder().withName("Zed").build());
addressBook.add(new ContactBuilder().withName("6").build());
addressBook.add(new ContactBuilder().withName("5").build());
addressBook.add(new ContactBuilder().withName("50").build());
addressBook.add(new ContactBuilder().withName("++").build());
addressBook.add(new ContactBuilder().withName("Anna").build());
List<Contact> contacts = addressBook.all();
assertEquals(contacts.get(0).getName(), ":)");
assertEquals(contacts.get(1).getName(), "++");
assertEquals(contacts.get(2).getName(), "5");
assertEquals(contacts.get(3).getName(), "50");
assertEquals(contacts.get(4).getName(), "6");
assertEquals(contacts.get(5).getName(), "Anna");
assertEquals(contacts.get(6).getName(), "beth");
assertEquals(contacts.get(7).getName(), "Zed");
}
}
| mpgarate/Production-Quality-Software | PS1_fa14/src/test/edu/nyu/mpgarate/pqs1/AddressBookTest.java | Java | mit | 2,952 |
package com.agilie.dribbblesdk.oAuth.oauth;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.util.Key;
import com.google.api.client.util.Preconditions;
public class OAuth10aResponseUrl extends GenericUrl {
/** Temporary access token issued by the authorization server. */
@Key("oauth_token")
private String token;
/** Verifier code issued by the authorization server. */
@Key("oauth_verifier")
private String verifier;
/** Error */
@Key("error")
private String error;
OAuth10aResponseUrl() {
super();
}
public OAuth10aResponseUrl(String encodedUrl) {
super(encodedUrl);
}
/** Returns the temporary access token issued by the authorization server. */
public final String getToken() {
return token;
}
/**
* Sets the temporary access token issued by the authorization server.
* <p>
* Overriding is only supported for the purpose of calling the super
* implementation and changing the return type, but nothing else.
* </p>
*/
public OAuth10aResponseUrl setToken(String token) {
this.token = Preconditions.checkNotNull(token);
return this;
}
public final String getVerifier() {
return verifier;
}
public OAuth10aResponseUrl setVerifier(String verifier) {
this.verifier = Preconditions.checkNotNull(verifier);
return this;
}
public final String getError() {
return error;
}
public OAuth10aResponseUrl setError(String error) {
this.error = error;
return this;
}
@Override
public OAuth10aResponseUrl set(String fieldName, Object value) {
return (OAuth10aResponseUrl) super.set(fieldName, value);
}
@Override
public OAuth10aResponseUrl clone() {
return (OAuth10aResponseUrl) super.clone();
}
}
| agilie/dribbble-android-sdk | dribbble-sdk-library/src/main/java/com/agilie/dribbblesdk/oAuth/oauth/OAuth10aResponseUrl.java | Java | mit | 1,894 |
package com.mattcorallo.relaynode;
import com.google.bitcoin.core.Sha256Hash;
import javax.annotation.Nonnull;
import java.io.ByteArrayOutputStream;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.util.Arrays;
public class QuarterHash {
// We transport transaction hashes as only 10 bytes instead of the full 32
// and assume a hash collision is rare enough that the P2P network will take over the slack if it happens
public byte[] bytes;
public static final int BYTE_LENGTH = 10;
QuarterHash(@Nonnull Sha256Hash hash) {
bytes = Arrays.copyOfRange(hash.getBytes(), 0, BYTE_LENGTH);
}
QuarterHash(@Nonnull ByteBuffer buff) throws BufferUnderflowException {
bytes = new byte[BYTE_LENGTH];
buff.get(bytes);
}
@Override
public int hashCode() {
return (((bytes[9] ^ bytes[5]) & 0xff) << 3*8) |
(((bytes[8] ^ bytes[4]) & 0xff) << 2*8) |
(((bytes[7] ^ bytes[3]) & 0xff) << 1*8) |
(((bytes[6] ^ bytes[2]) & 0xff) << 0*8);
}
@Override
public boolean equals(Object o) {
return o instanceof QuarterHash &&
Arrays.equals(this.bytes, ((QuarterHash) o).bytes);
}
public static void writeBytes(@Nonnull Sha256Hash hash, @Nonnull ByteArrayOutputStream buff) {
buff.write(hash.getBytes(), 0, BYTE_LENGTH);
}
}
| braiins/RelayNode | src/main/java/com/mattcorallo/relaynode/QuarterHash.java | Java | mit | 1,285 |
package com.clearbridgemobile.core.models;
public class GpsModel {
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
private String latitude;
private String longitude;
}
| ClearbridgeMobile/Android-Base-Project | corelibrary/src/main/java/com/clearbridgemobile/core/models/GpsModel.java | Java | mit | 443 |
/**
* Copyright (c) 2005-2012 springside.org.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.greatsec.demo.common.mapper;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.namespace.QName;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.util.Assert;
import com.greatsec.demo.common.utils.Exceptions;
import com.greatsec.demo.common.utils.Reflections;
/**
* 使用Jaxb2.0实现XML<->Java Object的Mapper.
*
* 在创建时需要设定所有需要序列化的Root对象的Class.
* 特别支持Root对象是Collection的情形.
*
* @author calvin
* @version 2013-01-15
*/
@SuppressWarnings("rawtypes")
public class JaxbMapper {
private static ConcurrentMap<Class, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class, JAXBContext>();
/**
* Java Object->Xml without encoding.
*/
public static String toXml(Object root) {
Class clazz = Reflections.getUserClass(root);
return toXml(root, clazz, null);
}
/**
* Java Object->Xml with encoding.
*/
public static String toXml(Object root, String encoding) {
Class clazz = Reflections.getUserClass(root);
return toXml(root, clazz, encoding);
}
/**
* Java Object->Xml with encoding.
*/
public static String toXml(Object root, Class clazz, String encoding) {
try {
StringWriter writer = new StringWriter();
createMarshaller(clazz, encoding).marshal(root, writer);
return writer.toString();
} catch (JAXBException e) {
throw Exceptions.unchecked(e);
}
}
/**
* Java Collection->Xml without encoding, 特别支持Root Element是Collection的情形.
*/
public static String toXml(Collection<?> root, String rootName, Class clazz) {
return toXml(root, rootName, clazz, null);
}
/**
* Java Collection->Xml with encoding, 特别支持Root Element是Collection的情形.
*/
public static String toXml(Collection<?> root, String rootName, Class clazz, String encoding) {
try {
CollectionWrapper wrapper = new CollectionWrapper();
wrapper.collection = root;
JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(new QName(rootName),
CollectionWrapper.class, wrapper);
StringWriter writer = new StringWriter();
createMarshaller(clazz, encoding).marshal(wrapperElement, writer);
return writer.toString();
} catch (JAXBException e) {
throw Exceptions.unchecked(e);
}
}
/**
* Xml->Java Object.
*/
@SuppressWarnings("unchecked")
public static <T> T fromXml(String xml, Class<T> clazz) {
try {
StringReader reader = new StringReader(xml);
return (T) createUnmarshaller(clazz).unmarshal(reader);
} catch (JAXBException e) {
throw Exceptions.unchecked(e);
}
}
/**
* 创建Marshaller并设定encoding(可为null).
* 线程不安全,需要每次创建或pooling。
*/
public static Marshaller createMarshaller(Class clazz, String encoding) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
if (StringUtils.isNotBlank(encoding)) {
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
}
return marshaller;
} catch (JAXBException e) {
throw Exceptions.unchecked(e);
}
}
/**
* 创建UnMarshaller.
* 线程不安全,需要每次创建或pooling。
*/
public static Unmarshaller createUnmarshaller(Class clazz) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
return jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
throw Exceptions.unchecked(e);
}
}
protected static JAXBContext getJaxbContext(Class clazz) {
Assert.notNull(clazz, "'clazz' must not be null");
JAXBContext jaxbContext = jaxbContexts.get(clazz);
if (jaxbContext == null) {
try {
jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
jaxbContexts.putIfAbsent(clazz, jaxbContext);
} catch (JAXBException ex) {
throw new HttpMessageConversionException("Could not instantiate JAXBContext for class [" + clazz
+ "]: " + ex.getMessage(), ex);
}
}
return jaxbContext;
}
/**
* 封装Root Element 是 Collection的情况.
*/
public static class CollectionWrapper {
@XmlAnyElement
protected Collection<?> collection;
}
}
| greatsec/newbie-training | java/demo/src/main/java/com/greatsec/demo/common/mapper/JaxbMapper.java | Java | mit | 4,779 |
/**
* 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.mediaservices.v2018_30_30_preview;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonSubTypes;
/**
* Describes the properties for an output image file.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@odata.type")
@JsonTypeName("#Microsoft.Media.ImageFormat")
@JsonSubTypes({
@JsonSubTypes.Type(name = "#Microsoft.Media.JpgFormat", value = JpgFormat.class),
@JsonSubTypes.Type(name = "#Microsoft.Media.PngFormat", value = PngFormat.class)
})
public class ImageFormat extends Format {
}
| hovsepm/azure-sdk-for-java | mediaservices/resource-manager/v2018_30_30_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_30_30_preview/ImageFormat.java | Java | mit | 916 |
package org.tristanles.results;
public class DrawResult implements LotteryResult {
public DrawResult() {
}
public void display() {
System.out.println("Tirage effectué");
}
}
| tristanles/lottery | src/main/java/org/tristanles/results/DrawResult.java | Java | mit | 187 |
/*
* Copyright (c) 2015 Abe Jellinek
*
* 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 me.abje.lingua.interpreter.obj;
import com.google.common.base.Joiner;
import me.abje.lingua.interpreter.Bridge;
import java.util.ArrayList;
import java.util.List;
/**
* A Lingua character string.
*/
public class StringObj extends Obj {
public static final ClassObj SYNTHETIC = bridgeClass(StringObj.class);
private static Joiner joiner = Joiner.on("");
/**
* This String's internal value.
*/
private String value;
/**
* Creates a new String with the given value.
*
* @param value The value.
*/
public StringObj(String value) {
super(SYNTHETIC);
this.value = value;
}
/**
* Returns this String's value.
*/
public String getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StringObj stringObj = (StringObj) o;
return value.equals(stringObj.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public String toString() {
return value;
}
@Bridge
public static StringObj init(Obj obj) {
return new StringObj(obj.toString());
}
@Bridge(anyLength = true)
public static StringObj init(Obj... objs) {
return new StringObj(joiner.join(objs));
}
@Bridge
public ListObj split(Obj delimiter) {
ListObj list = new ListObj(new ArrayList<>());
for (String s : value.split(delimiter.toString())) {
list.add(new StringObj(s));
}
return list;
}
@Bridge
public StringObj trim() {
return new StringObj(value.trim());
}
@Bridge
public CharObj charAt(NumberObj index) {
// todo cache this
return CharObj.of(value.charAt((int) index.getValue()));
}
@Bridge
public ListObj chars() {
char[] charArr = value.toCharArray();
List<Obj> charList = new ArrayList<>();
for (char c : charArr) {
charList.add(CharObj.of(c));
}
return new ListObj(charList);
}
@Bridge
public StringObj replace(StringObj from, StringObj to) {
return new StringObj(value.replace(from.getValue(), to.getValue()));
}
@Bridge
public NumberObj length() {
return NumberObj.of(value.length());
}
}
| Aiybe/Lingua | src/main/java/me/abje/lingua/interpreter/obj/StringObj.java | Java | mit | 3,557 |
/**
* Copyright (c) 2004-2011 Wang Jinbao(Julian Wong), http://www.ralasafe.com
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/
package org.ralasafe.db.sql;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class ExpressionGroup implements Expression {
public static final String AND = "AND";
public static final String OR = "OR";
private String linker = AND;
private Collection expressions = new ArrayList();
public String toSQL() {
Iterator itr = expressions.iterator();
if (!itr.hasNext())
return "";
StringBuffer buf = new StringBuffer();
// first Expression
Expression expression = (Expression) itr.next();
buf.append(" (");
buf.append(expression.toSQL());
while (itr.hasNext()) {
// link other Expressions with linker
expression = (Expression) itr.next();
buf.append(" ").append(linker).append(" ").append(
expression.toSQL());
}
buf.append(") ");
return buf.toString();
}
public Collection getExpressions() {
return expressions;
}
public void setExpressions(Collection expressions) {
this.expressions = expressions;
}
public String getLinker() {
return linker;
}
public void setLinker(String linker) {
this.linker = linker;
}
}
| colddew/ralasafe | ralasafe-engine/src/main/java/org/ralasafe/db/sql/ExpressionGroup.java | Java | mit | 1,287 |
/**
*/
package psdstructure.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
import org.eclipse.emf.edit.provider.ViewerNotification;
import psdstructure.BackgroundImage;
import psdstructure.PsdstructureFactory;
import psdstructure.PsdstructurePackage;
/**
* This is the item provider adapter for a {@link psdstructure.BackgroundImage} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class BackgroundImageItemProvider
extends ItemProviderAdapter
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BackgroundImageItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addImagePropertyDescriptor(object);
addSizePropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Image feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addImagePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_BackgroundImage_image_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_BackgroundImage_image_feature", "_UI_BackgroundImage_type"),
PsdstructurePackage.Literals.BACKGROUND_IMAGE__IMAGE,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Size feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addSizePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_BackgroundImage_size_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_BackgroundImage_size_feature", "_UI_BackgroundImage_type"),
PsdstructurePackage.Literals.BACKGROUND_IMAGE__SIZE,
true,
false,
false,
null,
null,
null));
}
/**
* This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
* {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
* {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
if (childrenFeatures == null) {
super.getChildrenFeatures(object);
childrenFeatures.add(PsdstructurePackage.Literals.BACKGROUND_IMAGE__POS);
}
return childrenFeatures;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EStructuralFeature getChildFeature(Object object, Object child) {
// Check the type of the specified child object and return the proper feature to use for
// adding (see {@link AddCommand}) it as a child.
return super.getChildFeature(object, child);
}
/**
* This returns BackgroundImage.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/BackgroundImage"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((BackgroundImage)object).getImage();
return label == null || label.length() == 0 ?
getString("_UI_BackgroundImage_type") :
getString("_UI_BackgroundImage_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(BackgroundImage.class)) {
case PsdstructurePackage.BACKGROUND_IMAGE__IMAGE:
case PsdstructurePackage.BACKGROUND_IMAGE__SIZE:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
case PsdstructurePackage.BACKGROUND_IMAGE__POS:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
newChildDescriptors.add
(createChildParameter
(PsdstructurePackage.Literals.BACKGROUND_IMAGE__POS,
PsdstructureFactory.eINSTANCE.createVector()));
}
/**
* Return the resource locator for this item provider's resources.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ResourceLocator getResourceLocator() {
return PsdstructureEditPlugin.INSTANCE;
}
}
| glovas/psd-ui-generator | hu.bme.mit.mobilgen.psdprocessor.model.edit/src/psdstructure/provider/BackgroundImageItemProvider.java | Java | mit | 6,806 |
package fr.v3d.elasticsearch.search.aggregations.metric.multiplemetric;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.junit.Test;
import fr.v3d.elasticsearch.plugin.multiplemetric.MultipleMetricAggregationTestCase;
public class MultipleMetricParserTest extends MultipleMetricAggregationTestCase {
@Test(expected=SearchPhaseExecutionException.class)
public void assertMissingFieldOrScript() throws Exception {
String indexName = "index0";
int numberOfShards = 1;
createIndex(numberOfShards, indexName);
client().prepareSearch("index0").setAggregations(JsonXContent.contentBuilder()
.startObject()
.startObject("metrics")
.startObject("value1")
.startObject("sum")
.field("nofield", "field")
.endObject()
.endObject()
.endObject()
.endObject()).execute().actionGet();
}
@Test(expected=SearchPhaseExecutionException.class)
public void assertMissingOperator() throws Exception {
String indexName = "index1";
int numberOfShards = 1;
createIndex(numberOfShards, indexName);
client().prepareSearch("index1").setAggregations(JsonXContent.contentBuilder()
.startObject()
.startObject("metrics")
.startObject("value1")
.startObject("bad-aggregator")
.field("field", "a")
.endObject()
.endObject()
.endObject()
.endObject()).execute().actionGet();
}
}
| eliep/elasticsearch-multiple-metric-aggregation | src/test/java/fr/v3d/elasticsearch/search/aggregations/metric/multiplemetric/MultipleMetricParserTest.java | Java | mit | 1,758 |
package com.villevalta.thingspeakclient.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.villevalta.thingspeakclient.model.ListStatusObject;
import com.villevalta.thingspeakclient.network.ApiClient;
import com.villevalta.thingspeakclient.network.PaginatedChannelResponce;
import com.villevalta.thingspeakclient.ui.adapters.ListContentProvider;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
/**
* Created by villevalta on 26.3.2015.
*/
public class PublicChannelsFragment extends RecyclerListFragment{
boolean isLoading;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mListContentProvider = new ListContentProvider();
loadMore(mListContentProvider.getPagination() != null ? mListContentProvider.getPagination().getCurrent_page() + 1 : 1);
super.setLoadMoreOnScroll(7);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = super.onCreateView(inflater, container, savedInstanceState);
if(isLoading) setStatus(new ListStatusObject(true,"Loading..."));
return v;
}
private void loadMore(int page){
if(isLoading) return;
isLoading = true;
ApiClient.getInstance().getPublicChannels(page, new Callback<PaginatedChannelResponce>() {
@Override
public void success(PaginatedChannelResponce channels, Response response) {
mListContentProvider.setPagination(channels.getPagination());
mListContentProvider.addAll(channels.getObjects());
onDone();
}
@Override
public void failure(RetrofitError error) {
error.printStackTrace();
onDone();
}
});
}
private void onDone(){
isLoading = false;
super.hideRefreshing();
if(mListContentProvider.getPagination().isLastPage()){
setStatus(new ListStatusObject(false,"~ end ~"));
}else{
setStatus(new ListStatusObject(false,null));
}
}
@Override
public void onRefresh(){
mListContentProvider.clear();
loadMore(1); // TODO Cancel other requests
}
@Override
public void onThresholdOverScrolled() {
if(!mListContentProvider.getPagination().isLastPage()){
int nextPage = mListContentProvider.getPagination().getCurrent_page() + 1;
setStatus(new ListStatusObject(true,"Loading page "+nextPage+"..."));
loadMore(nextPage);
}
}
}
| vetoketju/ThingSpeak-client-android | app/src/main/java/com/villevalta/thingspeakclient/fragments/PublicChannelsFragment.java | Java | mit | 2,426 |
public class InsertionSort {
// O(n^2) runtime and O(1) space complexities.
// Stable sort
public static int[] insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) { // i is the first unsorted index
int currentElement = arr[i], j = i;
while (j > 0 && currentElement < arr[j-1]) {
arr[j] = arr[j-1];
j--;
}
arr[j] = currentElement;
}
return arr;
}
public static void swap(int[] arr, int i, int j) {
if (i == j) {
return;
}
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static String print(int[] arr) {
String result = "[";
int n = arr.length;
for (int i = 0; i < n-1; i++) {
result += arr[i] + ", ";
}
if (n > 0) {
result += arr[n-1];
}
result += "]";
return result;
}
public static void main(String[] args) {
int[] arr = new int[] {7, 3, -2, 8, 2, -1, 0};
System.out.println("Before sorting, arr = " + print(arr));
int[] sortedArr = insertionSort(arr);
System.out.println("After sorting, arr = " + print(sortedArr));
}
}
| AmadouSallah/Programming-Interview-Questions | Data_Structures_And_Algorithms/SortingAndSearch/InsertionSort.java | Java | mit | 1,137 |
package com.acl.ax.datasource.mapsdk.infatypes;
public class PowerCenterCompatibilityFactory
{
public synchronized void setCompatibilityVersion(int major, int minor, int patch)
{
//For future use when we upgrade to new version
}
public PowerCenterCompatibility getPowerCenterCompatibilityInstance()
{
return instance;
}
public static PowerCenterCompatibilityFactory getInstance()
{
return inst;
}
private PowerCenterCompatibilityFactory()
{
instance = new PowerCenter85Compatibility();
}
private final PowerCenterCompatibility instance;
private static PowerCenterCompatibilityFactory inst = new PowerCenterCompatibilityFactory();
}
| acl-services/ax-datasource-connector | MainSource/plugins/com.acl.ax.datasource.mapsdk/src/com/acl/ax/datasource/mapsdk/infatypes/PowerCenterCompatibilityFactory.java | Java | mit | 758 |
package com.myrippleapps.mynotes.app;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.MaterialDialog.Builder;
import com.anjlab.android.iab.v3.BillingProcessor;
import com.anjlab.android.iab.v3.TransactionDetails;
import com.blunderer.materialdesignlibrary.activities.Activity;
import com.blunderer.materialdesignlibrary.handlers.ActionBarDefaultHandler;
import com.blunderer.materialdesignlibrary.handlers.ActionBarHandler;
//import com.google.android.gms.appindexing.Action;
//import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.myrippleapps.mynotes.app.database.DatabaseSQLHelper;
import com.myrippleapps.mynotes.app.database.NoteDataSource;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
//import com.nispok.snackbar.*;
//import com.nispok.snackbar.enums.*;
public class SettingActivity extends Activity {
private final String MULTI_COLUMN_VIEW;
private final String NEWEST;
private final String OLDEST;
private final String SINGLE_COLUMN_VIEW;
// private final String sharedPreferencesMaxLines;
// private final String sharedPreferencesNotesLayout;
// private final String sharedPreferencesSortBy;
private final String sharedPreferencesNotes;
private final NoteDataSource noteDataSource;
private final String notesLayoutKey;
private final String sortByKey;
private FileChannel dst;
private FileChannel src;
private String maxLinesKey;
private TextView max_lines;
private TextView newest_oldest;
private TextView notes_layout_textview;
private TextView on_off;
private SharedPreferences sharedPreferences;
private BillingProcessor bp;
private Boolean readyToPurchase;
public SettingActivity() {
noteDataSource = new NoteDataSource(this);
// sharedPreferencesMaxLines = "maxLinesSharedPreferences";
// sharedPreferencesNotesLayout = "notesLayoutSharedPreferences";
// sharedPreferencesSortBy = "sortBySharedPreferences";
sharedPreferencesNotes = "mPreferences";
maxLinesKey = "maxLinesKey";
notesLayoutKey = "notesLayoutKey";
sortByKey = "sortByKey";
SINGLE_COLUMN_VIEW = "single";
MULTI_COLUMN_VIEW = "mutli";
NEWEST = "newest";
OLDEST = "oldest";
readyToPurchase = false;
}
private void checkIsPinSet() {
noteDataSource.open();
if (noteDataSource.isPincodeSet()) {
on_off.setText(getString(R.string.on).toUpperCase());
on_off.setTextColor(R.color.primary_color);
return;
}
on_off.setText(getString(R.string.off).toUpperCase());
on_off.setTextColor(R.color.divider_color);
}
// --Commented out by Inspection START (25-Dec-15 8:43 AM):
public void toggleLock(View view) {
if (on_off.getText().equals((getString(R.string.on)).toUpperCase())) {
new MaterialDialog.Builder(this)
.content(R.string.confirm_pin)
.inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)
.inputRangeRes(4, 4, R.color.material_red_500)
.autoDismiss(false)
.input(getString(R.string.hint_pin), "", false, new MaterialDialog.InputCallback() {
@Override
public void onInput(@NonNull MaterialDialog mDialog, CharSequence charSequence) {
if (charSequence.length() == 4) {
noteDataSource.open();
if (noteDataSource.getPIN().equals(charSequence.toString())) {
turnOffPincode();
mDialog.dismiss();
return;
}
mDialog.getInputEditText().setText("");
Toast.makeText(mDialog.getContext(), R.string.pin_incorrect, Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(mDialog.getContext(), getString(R.string.four_digit_hint), Toast.LENGTH_SHORT).show();
}
}).show();
return;
}
new MaterialDialog.Builder(this)
.content(R.string.new_pincode)
.inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)
.inputRangeRes(4, 4, R.color.material_red_500)
.autoDismiss(false)
.input(getString(R.string.hint_pin), "", new MaterialDialog.InputCallback() {
@Override
public void onInput(@NonNull MaterialDialog mDialog, CharSequence charSequence) {
if (charSequence.length() == 4) {
setPincode(charSequence.toString());
mDialog.dismiss();
return;
}
Toast.makeText(mDialog.getContext(), getString(R.string.four_digit_hint), Toast.LENGTH_SHORT).show();
}
}).show();
}
// --Commented out by Inspection STOP (25-Dec-15 8:43 AM)
private void setPincode(String string) {
noteDataSource.insertPincode(string);
on_off.setText(getString(R.string.on).toUpperCase());
on_off.setTextColor(R.color.primary_color);
showSnackBar(getString(R.string.pincode_has_been_set));//2131558518
}
private void turnOffPincode() {
noteDataSource.removePIN();
noteDataSource.unlockALlNotes();
on_off.setText(getString(R.string.off).toUpperCase());
on_off.setTextColor(R.color.divider_color);
showSnackBar(getString(R.string.pincode_removed));
}
// --Commented out by Inspection START (25-Dec-15 8:43 AM):
public void exportNotes(View view) {
File storage = Environment.getExternalStorageDirectory();
File appData = Environment.getDataDirectory();
File getFolder = new File(String.format("%s%s", storage, getString(R.string.folder_name)));
getFolder.mkdir();
new MaterialDialog.Builder(this)
.title(getString(R.string.export_notes) + "?")
.content(getString(R.string.export_notes_warning) + ".")
.positiveText(R.string.export_word)
.negativeText(getString(R.string.cancel))
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
File currentDB = new File(getApplicationContext().getDatabasePath(DatabaseSQLHelper.DATABASE_NAME).getPath());
File backupDB = new File(sd, "/mynotes/Mynotes.db");
src = new FileInputStream(currentDB).getChannel();
dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
showMultiLineSnackBar(getString(R.string.notes_exported_to) + " " + backupDB.toString());
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
})
.onNegative(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
dialog.dismiss();
}
}).show();
}
// --Commented out by Inspection STOP (25-Dec-15 8:43 AM)
// --Commented out by Inspection START (25-Dec-15 8:43 AM):
public void importNotes(View view) {
new MaterialDialog.Builder(this)
.title(R.string.import_notes)
.content(R.string.import_notes_warning)
.positiveText(R.string.import_word)
.negativeText(R.string.cancel)
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
File backupDB = new File(getApplicationContext().getDatabasePath(DatabaseSQLHelper.DATABASE_NAME).getPath());
File currentDB = new File(sd, "/mynotes/Mynotes.db");
src = new FileInputStream(currentDB).getChannel();
dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
checkIsPinSet();
showSnackBar(getString(R.string.notes_restored));
}
} catch (IOException ex) {
String str = ex.getClass() + "";
int obj = -1;
switch (str.hashCode()) {
case -1710146240:
if (str.equals("class java.io.FileNotFoundException")) {
obj = -1;
break;
}
break;
}
switch (obj) {
//case R.styleable.FloatingActionButton_fab_colorPressed /*0*/:
case 0:
showSnackBar(getString(R.string.no_backup_notes));
return;
default:
}
}
}
})
.onNegative(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
dialog.dismiss();
}
})
.show();
}
// --Commented out by Inspection STOP (25-Dec-15 8:43 AM)
@Override
public void onBackPressed() {
Intent intent = new Intent();//
intent.setClass(getApplicationContext(), MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//(268468224);
startActivity(intent);
finish();
}
@Override
protected ActionBarHandler getActionBarHandler() {
// TODO: Implement this method
return new ActionBarDefaultHandler(this);
}
@Override
protected int getContentView() {
// TODO: Implement this method
return R.layout.activity_setting;
}
@Override
protected boolean enableActionBarShadow() {
// TODO: Implement this method
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!bp.handleActivityResult(requestCode, resultCode, data))
super.onActivityResult(requestCode, resultCode, data);
//getSupportFragmentManager().findFragmentById(R.id.fragment_container).onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout freeLayout = (LinearLayout) findViewById(R.id.freeLayout);
LinearLayout proLayout = (LinearLayout) findViewById(R.id.proLayout);
sharedPreferences = getSharedPreferences(sharedPreferencesNotes, 0);
String isPurchased = "isPurchased";
if (!sharedPreferences.getBoolean(isPurchased, false)) {
freeLayout.setVisibility(View.VISIBLE);
proLayout.setVisibility(View.VISIBLE);
//MyAppListener.track(findViewById(R.id.adView), savedInstanceState);
} else {
proLayout.setVisibility(View.VISIBLE);
freeLayout.setVisibility(View.GONE);
}
on_off = (TextView) findViewById(R.id.on_off);
max_lines = (TextView) findViewById(R.id.maxLines);
notes_layout_textview = (TextView) findViewById(R.id.notes_layout_textview);
newest_oldest = (TextView) findViewById(R.id.newest_oldest);
// final Drawable upArrow;
// upArrow = getResources().getDrawable(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_mtrl_am_alpha);
// upArrow.setColorFilter(android.R.color.white, PorterDuff.Mode.SRC_ATOP);
//
// getSupportActionBar().setHomeAsUpIndicator(upArrow);
// getSupportActionBar().setHomeButtonEnabled(true);
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
// setTranslucentStatus(true);
SystemBarTintManager systemBarTintManager = new SystemBarTintManager(this);
systemBarTintManager.setStatusBarTintEnabled(true);
systemBarTintManager.setNavigationBarTintEnabled(true);
}
sharedPreferences = getSharedPreferences(sharedPreferencesNotes, 0);
//PreferenceManager.getDefaultSharedPreferences(getBaseContext());//getSharedPreferences(sharedPreferencesMaxLines, 0);
if (sharedPreferences.contains(maxLinesKey)) {
int maxLines = sharedPreferences.getInt(maxLinesKey, 0);
if (maxLines == 0) {
max_lines.setText(getString(R.string.no_limit));
} else {
max_lines.setText(String.format("%d %s", maxLines, getString(R.string.lines)));
}
} else {
max_lines.setText(getString(R.string.no_limit));
}
sharedPreferences = getSharedPreferences(sharedPreferencesNotes, 0);
//PreferenceManager.getDefaultSharedPreferences(getBaseContext());//getSharedPreferences(sharedPreferencesNotesLayout, 0);
if (sharedPreferences.contains(notesLayoutKey)) {
String layout = sharedPreferences.getString(notesLayoutKey, "");
if (layout.equals("") || layout.equals(SINGLE_COLUMN_VIEW)) {
notes_layout_textview.setText(getString(R.string.layout_list));
} else if (layout.equals(MULTI_COLUMN_VIEW)) {
notes_layout_textview.setText(getString(R.string.layout_grid));
}
} else {
notes_layout_textview.setText(getString(R.string.layout_list));//(2131558531));
}
sharedPreferences = getSharedPreferences(sharedPreferencesNotes, 0);
//PreferenceManager.getDefaultSharedPreferences(getBaseContext());//sharedPreferences = getSharedPreferences(sharedPreferencesSortBy, 0);
if (sharedPreferences.contains(sortByKey)) {
String sortBy = sharedPreferences.getString(sortByKey, "");
if (sortBy.equals("") || sortBy.equals(NEWEST)) {
newest_oldest.setText(getString(R.string.newest_first));
} else if (sortBy.equals(OLDEST)) {
newest_oldest.setText(getString(R.string.oldest_first));
}
} else {
newest_oldest.setText(getString(R.string.newest_first));
}
checkIsPinSet();
iabInit();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
// client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void iabInit() {
if (!BillingProcessor.isIabServiceAvailable(this)) {
Constant.showMaterialDialog(this,
getString(R.string.play_service_error),
getString(R.string.play_service_error_desc),
null,
null,
null,
null,
getString(R.string.ok),
new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
dialog.dismiss();
}
}
);
//showToast("In-app billing service is unavailable, please upgrade Android Market/Play to version >= 3.9.16");
}
bp = new BillingProcessor(this, Constant.LICENSE_KEY, Constant.MERCHANT_ID, new BillingProcessor.IBillingHandler() {
@Override
public void onProductPurchased(String productId, TransactionDetails details) {
Log.i(Constant.LOG_IAB, "onProductPurchased: " + productId);
//updateAppTitle();
startActivity(new Intent(getApplicationContext(), SettingActivity.class));
}
@Override
public void onBillingError(int errorCode, Throwable error) {
Log.i(Constant.LOG_IAB, "onBillingError load: Error= " + Integer.toString(errorCode));
Constant.showMaterialDialog(
SettingActivity.this,
"Purchased failed",
"Error while purchasing. Please check your network connection and try again. Error Code= " + Integer.toString(errorCode),
"Try Again",
new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
bp.purchase(SettingActivity.this, Constant.PRODUCT_ID);
}
},
getString(R.string.cancel),
new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
dialog.dismiss();
}
},
null,
null
);
//showToast("Purchase failed!");
}
@Override
public void onBillingInitialized() {
Log.i(Constant.LOG_IAB, "InAppBilling Initialized!");
readyToPurchase = true;
//updateAppTitle();
}
@Override
public void onPurchaseHistoryRestored() {
Constant.showToast(getApplicationContext());
for (String sku : bp.listOwnedProducts())
Log.d(Constant.LOG_IAB, "Owned Managed Product: " + sku);
for (String sku : bp.listOwnedSubscriptions())
Log.d(Constant.LOG_IAB, "Owned Subscription: " + sku);
//updateAppTitle();
}
});
}
// --Commented out by Inspection START (25-Dec-15 8:43 AM):
@TargetApi(19)
private void setTranslucentStatus(boolean on) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
// --Commented out by Inspection STOP (25-Dec-15 8:43 AM)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_setting, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
Intent intent = new Intent(this, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
return super.onOptionsItemSelected(menuItem);
}
@Override
public void onDestroy() {
if (bp != null)
bp.release();
super.onDestroy();
}
// --Commented out by Inspection START (25-Dec-15 8:43 AM):
public void setMaxLines(View view) {
new Builder(this)
.items(getResources().getStringArray(R.array.lines_list))
.itemsCallback(new MaterialDialog.ListCallback() {
@Override
public void onSelection(MaterialDialog materialDialog, View view, int n, CharSequence charSequence) {
sharedPreferences = getSharedPreferences(sharedPreferencesNotes, 0);
//PreferenceManager.getDefaultSharedPreferences(getBaseContext());//getSharedPreferences(sharedPreferencesMaxLines, 0);
switch (n) {
case 0: {
max_lines.setText(getString(R.string.no_limit));
sharedPreferences.edit().putInt(maxLinesKey, 0).apply();
return;
}
case 1: {
max_lines.setText(String.format(getString(R.string.lines_5), getString(R.string.lines)));
sharedPreferences.edit().putInt(maxLinesKey, 5).apply();
return;
}
case 2: {
max_lines.setText(String.format(getString(R.string.lines_6), getString(R.string.lines)));
sharedPreferences.edit().putInt(maxLinesKey, 6).apply();
return;
}
case 3: {
max_lines.setText(String.format(getString(R.string.lines_7), getString(R.string.lines)));
sharedPreferences.edit().putInt(maxLinesKey, 7).apply();
return;
}
case 4: {
max_lines.setText(String.format(getString(R.string.lines_8), getString(R.string.lines)));
sharedPreferences.edit().putInt(maxLinesKey, 8).apply();
return;
}
case 5: {
max_lines.setText(String.format(getString(R.string.lines_9), getString(R.string.lines)));
sharedPreferences.edit().putInt(maxLinesKey, 9).apply();
return;
}
case 6: {
max_lines.setText(String.format(getString(R.string.lines_10), getString(R.string.lines)));
sharedPreferences.edit().putInt(maxLinesKey, 10).apply();
return;
}
default: {
max_lines.setText(String.format(getString(R.string.lines_5), getString(R.string.lines)));
sharedPreferences.edit().putInt(maxLinesKey, 5).apply();
}
// case 7:
}
}
}).show();
}
// --Commented out by Inspection STOP (25-Dec-15 8:43 AM)
// --Commented out by Inspection START (25-Dec-15 8:43 AM):
public void setNotesLayout(View view) {
new MaterialDialog.Builder(this)
.items(getResources().getStringArray(R.array.layout_list))
.itemsCallback(new MaterialDialog.ListCallback() {
@Override
public void onSelection(MaterialDialog materialDialog, View view, int n, CharSequence charSequence) {
sharedPreferences = getSharedPreferences(sharedPreferencesNotes, 0);
//PreferenceManager.getDefaultSharedPreferences(getBaseContext());//getSharedPreferences(sharedPreferencesNotesLayout, 0);
if (n == 0) {
notes_layout_textview.setText(getString(R.string.layout_list));
sharedPreferences.edit().putString(notesLayoutKey, SINGLE_COLUMN_VIEW).apply();
} else {
if (n != 1) return;
{
notes_layout_textview.setText(getString(R.string.layout_grid));
sharedPreferences.edit().putString(notesLayoutKey, MULTI_COLUMN_VIEW).apply();
}
}
}
}).show();
}
// --Commented out by Inspection STOP (25-Dec-15 8:43 AM)
// --Commented out by Inspection START (25-Dec-15 8:43 AM):
public void setSortBy(View view) {
new MaterialDialog.Builder(this)
.items(getResources().getStringArray(R.array.sort_list))
.itemsCallback(new MaterialDialog.ListCallback() {
@Override
public void onSelection(MaterialDialog materialDialog, View view, int n, CharSequence charSequence) {
newest_oldest.setText(getString(R.string.oldest_first));
switch (n) {
default: {
return;
}
case 0: {
newest_oldest.setText(getString(R.string.newest_first));
sharedPreferences.edit().putString(sortByKey, NEWEST).apply();
return;
}
case 1:
}
newest_oldest.setText(getString(R.string.oldest_first));
sharedPreferences.edit().putString(sortByKey, OLDEST).apply();
}
}).show();
}
// --Commented out by Inspection STOP (25-Dec-15 8:43 AM)
//@Override
private void showMultiLineSnackBar(String string) {
Snackbar.make(findViewById(R.id.root_layout), string, Snackbar.LENGTH_LONG).show();
// .setAction("Undo", mOnClickListener)
// .setActionTextColor(Color.RED)).show()
}
//@Override
private void showSnackBar(String string) {
Snackbar.make(findViewById(R.id.root_layout), string, Snackbar.LENGTH_LONG).show();
}
// --Commented out by Inspection START (25-Dec-15 8:43 AM):
public void toAbout(View view) {
startActivity(new Intent(this, AboutActivity.class));
}
// --Commented out by Inspection STOP (25-Dec-15 8:43 AM)
// --Commented out by Inspection START (25-Dec-15 8:43 AM):
public void toOpenSource(View view) {
startActivity(new Intent(this, OpenSourceLibraries.class));
}
// --Commented out by Inspection STOP (25-Dec-15 8:43 AM)
// --Commented out by Inspection START (25-Dec-15 8:43 AM):
public void purchaseNotes(View view) {
if (readyToPurchase)
bp.purchase(SettingActivity.this, Constant.PRODUCT_ID);
}
// --Commented out by Inspection STOP (25-Dec-15 8:43 AM)
// --Commented out by Inspection START (25-Dec-15 8:43 AM):
public void proNotes(View view) {
if (readyToPurchase)
bp.loadOwnedPurchasesFromGoogle();
}
// --Commented out by Inspection STOP (25-Dec-15 8:43 AM)
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
}
| avantgarde280/mynotes | app/src/main/java/com/myrippleapps/mynotes/app/SettingActivity.java | Java | mit | 29,488 |
package com.adrian.hackmyphone.databinders;
import com.adrian.hackmyphone.R;
/**
* Created by adrian on 3/11/16.
*/
public class SimpleCardDataBinder extends SimpleTextDataBinder {
@Override
protected int getLayoutResId() {
return R.layout.simple_card_item;
}
}
| adik993/hackmyphone | app/src/main/java/com/adrian/hackmyphone/databinders/SimpleCardDataBinder.java | Java | mit | 287 |
package Encapsulation.Exercise.P03ShoppingSpree;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String command = "";
List<Person> customers = new ArrayList<>();
List<Product> products = new ArrayList<>();
boolean noException = true;
for (int i = 0; i < 2; i++) {
String[] items = scanner.nextLine().split(";");
if (i == 0) {
for (String item : items) {
String[] tokens = item.split("=");
String name = tokens[0];
int money = Integer.parseInt(tokens[1]);
try {
Person currentPerson = new Person(name, money);
customers.add(currentPerson);
} catch (IllegalStateException e) {
noException = false;
System.out.println(e.getMessage());
break;
}
}
} else {
for (String item : items) {
String[] tokens = item.split("=");
String name = tokens[0];
double cost = Double.parseDouble(tokens[1]);
try {
Product currentProduct = new Product(name, cost);
products.add(currentProduct);
} catch (IllegalStateException e) {
noException = false;
System.out.println(e.getMessage());
break;
}
}
}
}
if (noException) {
while (!"END".equals(command = scanner.nextLine())) {
String[] tokens = command.split("\\s+");
String customerName = tokens[0];
String productName = tokens[1];
for (Person customer : customers) {
if (customer.getName().equals(customerName)) {
for (Product product : products) {
if (product.getName().equals(productName)) {
try {
customer.buyProduct(product);
}catch (IllegalStateException e){
System.out.println(e.getMessage());
}
}
}
}
}
}
for (Person customer : customers) {
System.out.printf("%s - %s%n",
customer.getName(),
customer.getProducts().size() > 0 ? customer.getProducts().stream()
.map(Product::getName)
.collect(Collectors.joining(", "))
: "Nothing bought");
}
}
}
}
| lmarinov/Exercise-repo | Java_OOP_2021/src/Encapsulation/Exercise/P03ShoppingSpree/Main.java | Java | mit | 3,123 |
/**
*
* Funf: Open Sensing Framework
* Copyright (C) 2010-2011 Nadav Aharony, Wei Pan, Alex Pentland.
* Acknowledgments: Alan Gardner
* Contact: [email protected]
*
* This file is part of Funf.
*
* Funf is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* Funf is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Funf. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.example.javagmm;
public class Window
{
public double[] window;
public int n;
public Window(int windowSize)
{
n = windowSize;
// Make a Hamming window
window = new double[n];
for(int i = 0; i < n; i++)
{
window[i] = 0.54 - 0.46*Math.cos(2*Math.PI*(double)i/((double)n-1));
}
}
public void applyWindow(double[] buffer)
{
for (int i = 0; i < n; i ++)
{
buffer[i] *= window[i];
}
}
}
| wahibhaq/android-speaker-audioanalysis | Android/VoiceRecognizerSP/src/com/example/javagmm/Window.java | Java | mit | 1,292 |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* Class for use in the 2015 AQA COMP1 exam for students using Java.
*
*
* There are 2 constructors
* 1. no parameters - creates an instance of AQAReadTextFile2015
* 2. one parameter - filename, this will open the file for reading
*
* There is one openFile method, which matches 2 above.
*
* There is one readLine method, which reads a line of text from an open file.
*
* There is one read method, which reads one character from an open file.
*
* There is a closeFile method.
*
*/
public class AQAReadTextFile2015 {
//The global variable link to the open file
private BufferedReader textFileReader;
/**
* A constructor for AQAReadTextFile2015, but no file is opened
* until openTextFile is called with a valid filename/path
*/
public AQAReadTextFile2015() {
} // end constructor AQAReadTextFile2015
/**
* A constructor that opens a text file for reading.
* @param filename the filename/path of a text file to be opened.
*/
public AQAReadTextFile2015(String filename) {
openTextFile(filename);
} // end constructor AQAReadTextFile2015
/**
* A method to open a text file.
* @param filename the filename/path of a text file to be opened
*/
public void openTextFile(String filename) {
try {
textFileReader = new BufferedReader(new FileReader(filename));
} catch (IOException e) {
e.printStackTrace();
closeFile();
} // end try/catch
} // end openTextFile
/**
* returns the next character in the file.
* returns '\u0000' only for the EOF or there is an error in reading.
*/
public char readChar() {
char c = '\u0000';
try {
c = (char) textFileReader.read();
} catch (IOException e) {
e.printStackTrace();
closeFile();
} // end catch
return c;
} // end readChar
/**
* returns the content of a line MINUS the newline.
* returns null only for the EOF.
* returns an empty String if two newlines appear in a row.
* Moves to the next line after reading this line.
* @return line the current line in the file.
* this will not include any line termination characters.
* null is returned if the EOF marker has been reached or
* there is an error in reading.
*/
public String readLine() {
String line = null;
try {
line = textFileReader.readLine();
} catch (IOException e) {
e.printStackTrace();
closeFile();
} // end catch
return line;
} // end readNextLine
/**
* Closes the file
*/
public void closeFile() {
try {
textFileReader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
} // end catch close exception
} // end closeFile
} // end AQAReadTextFile2015 | blueish4/eclipse-workspace | comp1-2015/src/AQAReadTextFile2015.java | Java | mit | 2,968 |
package voatApi.Responses.Data;
import voatApi.Enums.MessageType;
public class DataMessage {
private String subverse, recipient, sender, subject, typeName, content, formattedContent;
private int id, commentID, submissionID;
private boolean unread;
private MessageType type;
public int getId() {
return id;
}
public void setId(int _id) {
id = _id;
}
public int getCommentID() {
return commentID;
}
public void setCommentID(int _commentID) {
commentID = _commentID;
}
public int getSubmissionID() {
return submissionID;
}
public void setSubmissionID(int _submissionID) {
submissionID = _submissionID;
}
public String getSubverse() {
return subverse;
}
public void setSubverse(String _subverse) {
subverse = _subverse;
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String _recipient) {
recipient = _recipient;
}
public String getSender() {
return sender;
}
public void setSender(String _sender) {
sender = _sender;
}
public String getSubject() {
return subject;
}
public void setSubject(String _subject) {
subject = _subject;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String _typeName) {
typeName = _typeName;
}
public String getContent() {
return content;
}
public void setContent(String _content) {
content = _content;
}
public String getFormattedContent() {
return formattedContent;
}
public void setFormattedContent(String _formattedContent) {
formattedContent = _formattedContent;
}
public boolean isUnread() {
return unread;
}
public void setUnread(boolean _unread) {
unread = _unread;
}
public MessageType getType() {
return type;
}
public void setType(MessageType _type) {
type = _type;
}
}
| M3gaFr3ak/voatJavaApi | src/main/java/voatApi/Responses/Data/DataMessage.java | Java | mit | 2,088 |
package io.github.takzhanov.umbrella.hw07;
import io.github.takzhanov.umbrella.hw06.Atm;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class AtmDepartmentEmulator implements AtmDepartment {
List<Atm> atms = new ArrayList<>();
@Override
public void addAtm(@NotNull Atm atm) {
atms.add(atm);
}
@Override
public void resetAllAtms() {
atms.forEach(Atm::reset);
}
@Override
public Integer getDepartmentBalance() {
return atms.stream().map(Atm::getAtmBalance).mapToInt(Integer::intValue).sum();
}
}
| takzhanov/otus-java-2017-10-takzhanov-yury | hw07-atm-department/src/main/java/io/github/takzhanov/umbrella/hw07/AtmDepartmentEmulator.java | Java | mit | 617 |
package br.org.piblimeira.enuns;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author Regiane
*/
public enum EnumStatus {
ATIVO("A", "Ativo"),
INATIVO("I","Inativo");
private String codigo;
private String label;
private static final Map<String, EnumStatus> LOOKUP = new HashMap<String, EnumStatus>();
private static final Map<String, EnumStatus> LOOKUPDESC = new HashMap<String, EnumStatus>();
static {
for (EnumStatus item : EnumStatus.values()) {
LOOKUP.put(item.codigo, item);
}
for (EnumStatus item : EnumStatus.values()) {
LOOKUPDESC.put(item.label, item);
}
}
/**
* Construtor
* @param String - codigo
* @param String - label
*/
private EnumStatus(final String codigo, final String label) {
this.codigo = codigo;
this.label = label;
}
public String getCodigo() {
return codigo;
}
public String getLabel() {
return label;
}
public static EnumStatus getByCodigo(final String codigo) {
return LOOKUP.get(codigo);
}
public static EnumStatus getByDescricao(final String desc) {
return LOOKUPDESC.get(desc);
}
public static List<String> listarStatus(){
List<String> listaStatus = new ArrayList<>();
for (EnumStatus item : EnumStatus.values()) {
listaStatus.add(item.getLabel());
}
return listaStatus;
}
} | regianemsms/pib | src/main/java/br/org/piblimeira/enuns/EnumStatus.java | Java | mit | 1,477 |
package jp.glassmoon.app.amqpspawn;
import java.io.IOException;
import com.beust.jcommander.JCommander;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
public class App
{
static final String EXECUTABLE_NAME = "amqpspawn";
public static void main( String[] args )
{
Option opt = new Option();
JCommander jc = new JCommander(opt, args);
jc.setProgramName(EXECUTABLE_NAME);
if(opt.isHelp()) {
jc.usage();
System.exit(0);
}
ConnectionFactory factory = null;
Connection conn = null;
try {
factory = new ConnectionFactory();
factory.setUri(opt.getUri());
conn = factory.newConnection();
final Channel channel = conn.createChannel();
String queueName = opt.getQueue();
String exchangeName = opt.getExchange();
String routingKey = opt.getRoutingKey();
String consumerTag = opt.getConsumerTag();
if(!opt.isPassive()) {
channel.queueDeclare(queueName, true, false, false, null);
channel.queueBind(queueName, exchangeName, routingKey);
System.out.println("Queue created: " + queueName);
}
if(opt.isNoSpawn()) {
return;
}
channel.basicConsume(queueName, false, consumerTag,
new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag,
Envelope envelope, BasicProperties properties,
byte[] body) throws IOException {
// TODO Auto-generated method stub
super.handleDelivery(consumerTag, envelope, properties, body);
String routingKey = envelope.getRoutingKey();
long deliveryTag = envelope.getDeliveryTag();
String eventBody = new String(body, "UTF-8");
System.out.println("Received: [" + routingKey + "] " + eventBody);
channel.basicAck(deliveryTag, false);
}
});
if(opt.isPassive()) {
System.out.printf("Connect: Queue[%s]\n", opt.getQueue());
}
else {
System.out.printf("Connect: Queue[%s] binding to Exchange[%s], Routingkey[%s]\n",
opt.getQueue(), opt.getExchange(),opt.getRoutingKey());
}
} catch(Exception e) {
System.out.println();
}
}
}
| rinrinne/amqpspawn | src/main/java/jp/glassmoon/app/amqpspawn/App.java | Java | mit | 2,674 |
package edu.javacourse.spring.ws.client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author Artem Pronchakov <[email protected]>
*/
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
SimpleWebServieClient client = context.getBean("client", SimpleWebServieClient.class);
String response = client.sayHello("Vasiliy");
log.debug("Response name: {}", response);
}
}
| java-course-ee/java-course-ee | Spring/WS/Spring-WS-Client/src/main/java/edu/javacourse/spring/ws/client/Main.java | Java | mit | 705 |
package com.github.steveice10.mc.protocol.packet.ingame.server.world;
import com.github.steveice10.mc.protocol.data.MagicValues;
import com.github.steveice10.mc.protocol.data.game.world.map.MapData;
import com.github.steveice10.mc.protocol.data.game.world.map.MapIcon;
import com.github.steveice10.mc.protocol.data.game.world.map.MapIconType;
import com.github.steveice10.mc.protocol.packet.MinecraftPacket;
import com.github.steveice10.packetlib.io.NetInput;
import com.github.steveice10.packetlib.io.NetOutput;
import java.io.IOException;
public class ServerMapDataPacket extends MinecraftPacket {
private int mapId;
private byte scale;
private boolean trackingPosition;
private MapIcon icons[];
private MapData data;
@SuppressWarnings("unused")
private ServerMapDataPacket() {
}
public ServerMapDataPacket(int mapId, byte scale, boolean trackingPosition, MapIcon icons[]) {
this(mapId, scale, trackingPosition, icons, null);
}
public ServerMapDataPacket(int mapId, byte scale, boolean trackingPosition, MapIcon icons[], MapData data) {
this.mapId = mapId;
this.scale = scale;
this.trackingPosition = trackingPosition;
this.icons = icons;
this.data = data;
}
public int getMapId() {
return this.mapId;
}
public byte getScale() {
return this.scale;
}
public boolean getTrackingPosition() {
return this.trackingPosition;
}
public MapIcon[] getIcons() {
return this.icons;
}
public MapData getData() {
return this.data;
}
@Override
public void read(NetInput in) throws IOException {
this.mapId = in.readVarInt();
this.scale = in.readByte();
this.trackingPosition = in.readBoolean();
this.icons = new MapIcon[in.readVarInt()];
for(int index = 0; index < this.icons.length; index++) {
int data = in.readUnsignedByte();
int type = (data >> 4) & 15;
int rotation = data & 15;
int x = in.readUnsignedByte();
int z = in.readUnsignedByte();
this.icons[index] = new MapIcon(x, z, MagicValues.key(MapIconType.class, type), rotation);
}
int columns = in.readUnsignedByte();
if(columns > 0) {
int rows = in.readUnsignedByte();
int x = in.readUnsignedByte();
int y = in.readUnsignedByte();
byte data[] = in.readBytes(in.readVarInt());
this.data = new MapData(columns, rows, x, y, data);
}
}
@Override
public void write(NetOutput out) throws IOException {
out.writeVarInt(this.mapId);
out.writeByte(this.scale);
out.writeBoolean(this.trackingPosition);
out.writeVarInt(this.icons.length);
for(int index = 0; index < this.icons.length; index++) {
MapIcon icon = this.icons[index];
int type = MagicValues.value(Integer.class, icon.getIconType());
out.writeByte((type & 15) << 4 | icon.getIconRotation() & 15);
out.writeByte(icon.getCenterX());
out.writeByte(icon.getCenterZ());
}
if(this.data != null && this.data.getColumns() != 0) {
out.writeByte(this.data.getColumns());
out.writeByte(this.data.getRows());
out.writeByte(this.data.getX());
out.writeByte(this.data.getY());
out.writeVarInt(this.data.getData().length);
out.writeBytes(this.data.getData());
} else {
out.writeByte(0);
}
}
}
| P0ke55/specbot | src/main/java/com/github/steveice10/mc/protocol/packet/ingame/server/world/ServerMapDataPacket.java | Java | mit | 3,611 |
package com.github.ddth.dao.qnd;
import com.github.ddth.dao.BaseJsonBo;
public class QndBoAttrsMap {
public static void main(String[] args) {
BaseJsonBo myBo = new BaseJsonBo();
myBo.setSubAttr("name", "first", "Thanh");
myBo.setSubAttr("name", "last", "Nguyen");
myBo.setSubAttr("addr", "number", 123);
myBo.setSubAttr("addr", "street", "Abc");
myBo.setSubAttr("addr", "surburb", "X");
System.out.println(myBo.getAttributes());
System.out.println(myBo.getSubAttr("addr", "number"));
myBo.removeSubAttr("name", "last");
myBo.removeSubAttr("addr", "surburb");
System.out.println(myBo.getAttributes());
}
}
| DDTH/ddth-dao | ddth-dao-core/src/test/java/com/github/ddth/dao/qnd/QndBoAttrsMap.java | Java | mit | 706 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Carlos Andres Jimenez <[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 co.carlosandresjimenez.gotit.backend.beans;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.common.base.Objects;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
/**
* Created by carlosjimenez on 10/27/15.
*/
@PersistenceCapable
public class Following {
@NotPersistent
public static final int PENDING = 0;
@NotPersistent
public static final int APPROVED = 1;
@NotPersistent
public static final int REJECTED = 2;
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key followingId;
@Persistent
private String userEmail;
@Persistent
private String followingUserEmail;
@Persistent
private int approvedStatus;
public Following() {
}
public Following(String userEmail, String followingUserEmail, int approvedStatus) {
super();
setFollowingId(userEmail, followingUserEmail);
this.userEmail = userEmail;
this.followingUserEmail = followingUserEmail;
this.approvedStatus = approvedStatus;
}
@Override
public String toString() {
return "Following{" +
"userEmail=" + userEmail +
", followingUserEmail='" + followingUserEmail + '\'' +
", followingId='" + followingId + '\'' +
", approvedStatus='" + approvedStatus + '\'' +
'}';
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Following) {
Following other = (Following) obj;
// Google Guava provides great utilities for equals too!
return Objects.equal(followingId, other.followingId);
} else {
return false;
}
}
public static Key getKey(String userEmail, String followingUserEmail) {
Key keyFollowingId = null;
String strFollowingId = userEmail + followingUserEmail;
if (strFollowingId != null && !strFollowingId.equals(""))
keyFollowingId = KeyFactory.createKey(Following.class.getSimpleName(), strFollowingId);
return keyFollowingId;
}
public String getFollowingId() {
return this.followingId != null ? KeyFactory.keyToString(this.followingId) : null;
}
public void setFollowingId(String userEmail, String followingUserEmail) {
this.followingId = getKey(userEmail, followingUserEmail);
}
public String getFollowingUserEmail() {
return followingUserEmail;
}
public void setFollowingUserEmail(String followingUserEmail) {
this.followingUserEmail = followingUserEmail;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public int getApprovedStatus() {
return approvedStatus;
}
public void setApprovedStatus(int approvedStatus) {
this.approvedStatus = approvedStatus;
}
} | crlsndrsjmnz/GotIt | backend/src/main/java/co/carlosandresjimenez/gotit/backend/beans/Following.java | Java | mit | 4,378 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 - 2017 PayinTech
*
* 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.payintech.smoney.entity;
import java.io.Serializable;
/**
* CompanyEntity.
*
* @author Jean-Pierre Boudic
* @author Thibault Meyer
* @version 16.02
* @since 15.11.01
*/
public class CompanyEntity implements Serializable {
/**
* Company name.
*
* @since 15.11.01
*/
public String Name;
/**
* Legal registration number: SIRET or RNA.
*
* @since 15.11.01
*/
public String Siret;
}
| payintech/smoney-java-client | src/main/java/com/payintech/smoney/entity/CompanyEntity.java | Java | mit | 1,606 |
package msp.game.network;
import framework.GDB;
import framework.GResource;
import java.net.Socket;
public class ServerClient implements Runnable {
TCPConnector connector;
Server server;
public ServerClient(Socket socket,Server server) throws Exception{
this.server=server;
connector=new TCPConnector();
connector.listeners.add(new TCPConnectorListener() {
@Override
public void onCommandReceived(String command, String[] args) {
ServerClient.this.onCommandRecieved(command, args);
}
});
connector.connect(socket);
}
void onCommandRecieved(String command, String[] args) {
if (command.equals("handshake")) {
GDB.i("Client handshake with name :"+args[0]);
}
}
@Override
public void run() {
GDB.i("New client connected!");
}
public void requestJoin() {
connector.sendCommand("start",server.getPlayerID()+"", GResource.instance.getMap(server.mapName).toJson());
}
}
| pi0/MSP | src/msp/game/network/ServerClient.java | Java | mit | 1,104 |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002, 2014 Oracle and/or its affiliates. All rights reserved.
*
*/
package com.sleepycat.je.rep.util;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;
import com.sleepycat.je.rep.ReplicatedEnvironment;
import com.sleepycat.je.rep.impl.RepGroupImpl;
import com.sleepycat.je.rep.impl.RepNodeImpl;
import com.sleepycat.je.rep.utilint.HostPortPair;
import com.sleepycat.je.utilint.CmdUtil;
import com.sleepycat.je.utilint.PropUtil;
/**
* DbGroupAdmin supplies the functionality of the administrative class {@link
* ReplicationGroupAdmin} in a convenient command line utility. For example, it
* can be used to display replication group information, or to remove a node
* from the replication group.
* <p>
* Note: This utility does not handle security and authorization. It is left
* to the user to ensure that the utility is invoked with proper authorization.
* <p>
* See {@link DbGroupAdmin#main} for a full description of the command line
* arguments.
*/
public class DbGroupAdmin {
enum Command { DUMP, REMOVE, TRANSFER_MASTER, UPDATE_ADDRESS };
private String groupName;
private Set<InetSocketAddress> helperSockets;
private String nodeName;
private String newHostName;
private int newPort;
private String timeout;
private boolean forceFlag;
private ReplicationGroupAdmin groupAdmin;
private final ArrayList<Command> actions = new ArrayList<Command>();
private static final String usageString =
"Usage: " + CmdUtil.getJavaCommand(DbGroupAdmin.class) + "\n" +
" -groupName <group name> # name of replication group\n" +
" -helperHosts <host:port> # identifier for one or more members\n" +
" # of the replication group which can\n"+
" # be contacted for group information,\n"+
" # in this format:\n" +
" # hostname[:port][,hostname[:port]]\n" +
" -dumpGroup # dump group information\n" +
" -removeMember <node name> # node to be removed\n" +
" -updateAddress <node name> <new host:port>\n" +
" # update the network address for a\n " +
" # specified node. The node should not\n" +
" # be alive when updating the address\n" +
" -transferMaster [-force] <node1,node2,...> <timeout>\n" +
" # transfer master role to one of the\n" +
" # specified nodes.";
/**
* Usage:
* <pre>
* java {com.sleepycat.je.rep.util.DbGroupAdmin |
* -jar je-<version>.jar DbGroupAdmin}
* -groupName <group name> # name of replication group
* -helperHosts <host:port> # identifier for one or more members
* # of the replication group which can be
* # contacted for group information, in
* # this format:
* # hostname[:port][,hostname[:port]]*
* -dumpGroup # dump group information
* -removeMember <node name># node to be removed
* -updateAddress <node name> <new host:port>
* # update the network address for a specified
* # node. The node should not be alive when
* # updating address
* -transferMaster [-force] <node1,node2,...> <timeout>
* </pre>
*/
public static void main(String... args)
throws Exception {
DbGroupAdmin admin = new DbGroupAdmin();
admin.parseArgs(args);
admin.run();
}
/**
* Print usage information for this utility.
*
* @param message
*/
private void printUsage(String msg) {
if (msg != null) {
System.out.println(msg);
}
System.out.println(usageString);
System.exit(-1);
}
/**
* Parse the command line parameters.
*
* @param argv Input command line parameters.
*/
private void parseArgs(String argv[]) {
int argc = 0;
int nArgs = argv.length;
if (nArgs == 0) {
printUsage(null);
System.exit(0);
}
while (argc < nArgs) {
String thisArg = argv[argc++];
if (thisArg.equals("-groupName")) {
if (argc < nArgs) {
groupName = argv[argc++];
} else {
printUsage("-groupName requires an argument");
}
} else if (thisArg.equals("-helperHosts")) {
if (argc < nArgs) {
helperSockets = HostPortPair.getSockets(argv[argc++]);
} else {
printUsage("-helperHosts requires an argument");
}
} else if (thisArg.equals("-dumpGroup")) {
actions.add(Command.DUMP);
} else if (thisArg.equals("-removeMember")) {
if (argc < nArgs) {
nodeName = argv[argc++];
actions.add(Command.REMOVE);
} else {
printUsage("-removeMember requires an argument");
}
} else if (thisArg.equals("-updateAddress")) {
if (argc < nArgs) {
nodeName = argv[argc++];
if (argc < nArgs) {
String hostPort = argv[argc++];
int index = hostPort.indexOf(":");
if (index < 0) {
printUsage("Host port pair format must be " +
"<host name>:<port number>");
}
newHostName = hostPort.substring(0, index);
newPort = Integer.parseInt
(hostPort.substring(index + 1, hostPort.length()));
} else {
printUsage("-updateAddress requires a " +
"<host name>:<port number> argument");
}
actions.add(Command.UPDATE_ADDRESS);
} else {
printUsage
("-updateAddress requires the node name argument");
}
} else if (thisArg.equals("-transferMaster")) {
// TODO: it wouldn't be too hard to allow "-force" as a
// node name.
//
if (argc < nArgs && "-force".equals(argv[argc])) {
forceFlag = true;
argc++;
}
if (argc + 1 < nArgs) {
nodeName = argv[argc++];
/*
* Allow either
* -transferMaster mercury,venus 900 ms
* or
* -transferMaster mercury,venus "900 ms"
*/
if (argc + 1 < nArgs && argv[argc + 1].charAt(0) != '-') {
timeout = argv[argc] + " " + argv[argc + 1];
argc += 2;
} else {
timeout = argv[argc++];
}
actions.add(Command.TRANSFER_MASTER);
} else {
printUsage
("-transferMaster requires at least two arguments");
}
} else {
printUsage(thisArg + " is not a valid argument");
}
}
}
/* Execute commands */
private void run()
throws Exception {
createGroupAdmin();
if (actions.size() == 0) {
return;
}
for (Command action : actions) {
/* Dump the group information. */
if (action == Command.DUMP) {
dumpGroup();
}
/* Remove a member. */
if (action == Command.REMOVE) {
removeMember(nodeName);
}
/* Transfer the current mastership to a specified node. */
if (action == Command.TRANSFER_MASTER) {
transferMaster(nodeName, timeout);
}
/* Update the network address of a specified node. */
if (action == Command.UPDATE_ADDRESS) {
updateAddress(nodeName, newHostName, newPort);
}
}
}
private DbGroupAdmin() {
}
/**
* Create a DbGroupAdmin instance for programmatic use.
*
* @param groupName replication group name
* @param helperSockets set of host and port pairs for group members which
* can be queried to obtain group information.
*/
public DbGroupAdmin(String groupName,
Set<InetSocketAddress> helperSockets) {
this.groupName = groupName;
this.helperSockets = helperSockets;
createGroupAdmin();
}
/* Create the ReplicationGroupAdmin object. */
private void createGroupAdmin() {
if (groupName == null) {
printUsage("Group name must be specified");
}
if ((helperSockets == null) || (helperSockets.size() == 0)) {
printUsage("Host and ports of helper nodes must be specified");
}
groupAdmin = new ReplicationGroupAdmin(groupName, helperSockets);
}
/**
* Display group information. Lists all members and the group master. Can
* be used when reviewing the <a
* href="http://www.oracle.com/technetwork/database/berkeleydb/je-faq-096044.html#HAChecklist">group configuration. </a>
*/
public void dumpGroup() {
System.out.println(getFormattedOutput());
}
/**
* Remove a node from the replication group. Once removed, a
* node cannot be added again to the group under the same node name.
*
* @param name name of the node to be removed
*
* @see ReplicationGroupAdmin#removeMember
*/
public void removeMember(String name) {
if (name == null) {
printUsage("Node name must be specified");
}
groupAdmin.removeMember(name);
}
/**
* Update the network address for a specified node. When updating the
* address of a node, the node cannot be alive. See {@link
* ReplicationGroupAdmin#updateAddress} for more information.
*
* @param nodeName the name of the node whose address will be updated
* @param newHostName the new host name of the node
* @param newPort the new port number of the node
*/
public void updateAddress(String nodeName,
String newHostName,
int newPort) {
if (nodeName == null || newHostName == null) {
printUsage("Node name and new host name must be specified");
}
if (newPort <= 0) {
printUsage("Port of the new network address must be specified");
}
groupAdmin.updateAddress(nodeName, newHostName, newPort);
}
/**
* Transfers the master role from the current master to one of the
* electable replicas specified in the argument list.
*
* @param nodeList comma-separated list of nodes
* @param timeout in <a href="../../EnvironmentConfig.html#timeDuration">
* same form</a> as accepted by duration config params
*
* @see ReplicatedEnvironment#transferMaster
*/
public void transferMaster(String nodeList, String timeout) {
String result =
groupAdmin.transferMaster(parseNodes(nodeList),
PropUtil.parseDuration(timeout),
TimeUnit.MILLISECONDS,
forceFlag);
System.out.println("The new master is: " + result);
}
private Set<String> parseNodes(String nodes) {
if (nodes == null) {
throw new IllegalArgumentException("node list may not be null");
}
StringTokenizer st = new StringTokenizer(nodes, ",");
Set<String> set = new HashSet<String>();
while (st.hasMoreElements()) {
set.add(st.nextToken());
}
return set;
}
/*
* This method presents group information in a user friendly way. Internal
* fields are hidden.
*/
private String getFormattedOutput() {
StringBuilder sb = new StringBuilder();
RepGroupImpl repGroupImpl = groupAdmin.getGroup().getRepGroupImpl();
/* Get the master node name. */
String masterName = groupAdmin.getMasterNodeName();
/* Get the electable nodes information. */
sb.append("\nGroup: " + repGroupImpl.getName() + "\n");
sb.append("Electable Members:\n");
Set<RepNodeImpl> nodes = repGroupImpl.getAllElectableMembers();
if (nodes.size() == 0) {
sb.append(" No electable members\n");
} else {
for (RepNodeImpl node : nodes) {
String type =
masterName.equals(node.getName()) ? "master, " : "";
sb.append(" " + node.getName() + " (" + type +
node.getHostName() + ":" + node.getPort() + ", " +
node.getBarrierState() + ")\n");
}
}
/* Get the monitors information. */
sb.append("\nMonitor Members:\n");
nodes = repGroupImpl.getMonitorNodes();
if (nodes.size() == 0) {
sb.append(" No monitors\n");
} else {
for (RepNodeImpl node : nodes) {
sb.append(" " + node.getName() + " (" + node.getHostName() +
":" + node.getPort() + ")\n");
}
}
return sb.toString();
}
}
| prat0318/dbms | mini_dbms/je-5.0.103/src/com/sleepycat/je/rep/util/DbGroupAdmin.java | Java | mit | 14,298 |
package com.banckle.chat.api;
import com.banckle.client.ApiException;
import com.banckle.client.ApiInvoker;
import com.sun.jersey.multipart.FormDataMultiPart;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.util.*;
public class OperatorsApi {
String basePath = "https://chat.banckle.com/v3";
ApiInvoker apiInvoker = ApiInvoker.getInstance();
public ApiInvoker getInvoker() {
return apiInvoker;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getBasePath() {
return basePath;
}
public String getOperators (Boolean online) throws ApiException {
Object postBody = null;
// verify required params are set
if(online == null ) {
throw new ApiException(400, "missing required params");
}
// create path and map variables
String path = "/operators?online={online}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "online" + "\\}", apiInvoker.escapeString(online.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
"application/json"};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return (String) ApiInvoker.deserialize(response, "", String.class);
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return null;
}
else {
throw ex;
}
}
}
public String getOperator (String operatorId) throws ApiException {
Object postBody = null;
// verify required params are set
if(operatorId == null ) {
throw new ApiException(400, "missing required params");
}
// create path and map variables
String path = "/operators/{operatorId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "operatorId" + "\\}", apiInvoker.escapeString(operatorId.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
String[] contentTypes = {
"application/json"};
String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType);
if(response != null){
return (String) ApiInvoker.deserialize(response, "", String.class);
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.getCode() == 404) {
return null;
}
else {
throw ex;
}
}
}
}
| BanckleMarketplace/Banckle.Chat-SDK-For-Java | src/com/banckle/chat/api/OperatorsApi.java | Java | mit | 3,507 |
package re.agiledesign.mp2.util;
public interface Func<R, A> {
public R invoke(final A aArgument);
}
| gcnew/MP2 | src/re/agiledesign/mp2/util/Func.java | Java | mit | 108 |
package p02_OneLevShop.Abstract;
import p02_OneLevShop.Interfaces.Buyable;
import java.time.LocalDate;
public abstract class ElectronicsProduct extends Product {
protected LocalDate warranty;
protected ElectronicsProduct(String name, double price, int quantity, String purchaseDate) {
super(name, price, quantity);
this.setWarranty(LocalDate.parse(purchaseDate, dateFormat));
}
protected static String warrantyDate(String purchaseDate, int warrantyMonths) {
return LocalDate.parse(purchaseDate, dateFormat)
.plusMonths(warrantyMonths)
.format(dateFormat);
}
public LocalDate getWarranty() {
return warranty;
}
public void setWarranty(LocalDate warranty) {
this.warranty = warranty;
}
}
| HouseBreaker/Java-Fundamentals | 05. OOP in Java/src/p02_OneLevShop/Abstract/ElectronicsProduct.java | Java | mit | 720 |
package com.jjmrive.ludify.visit;
import java.io.Serializable;
import java.util.ArrayList;
public class Collection implements Serializable {
private int idCollection;
private String name;
private ArrayList<CollectionItem> items;
private String urlPhoto;
private int total;
private int prize;
private boolean result;
public Collection(int idCollection, String name, String urlPhoto, int total, int prize){
this.idCollection = idCollection;
this.name = name;
this.items = new ArrayList<>();
this.urlPhoto = urlPhoto;
this.total = total;
this.prize = prize;
this.result = false;
}
public void addItem(CollectionItem item){
items.add(item);
}
public int getIdCollection(){
return idCollection;
}
public String getName(){
return name;
}
public String getUrlPhoto(){
return urlPhoto;
}
public int getTotal(){
return total;
}
public ArrayList<CollectionItem> getItems(){
return items;
}
public int getItemNumber(){
return items.size();
}
public int getPrize(){
return prize;
}
public boolean getResult(){
if (items.size() == total){
result = true;
}
return result;
}
@Override
public boolean equals(Object o){
boolean eq = false;
Collection col = (Collection) o;
if (col.idCollection == this.idCollection){
eq = true;
}
return eq;
}
}
| jjmrive/Ludify | app/src/main/java/com/jjmrive/ludify/visit/Collection.java | Java | mit | 1,573 |
/*
* 2007-2016 [PagSeguro Internet Ltda.]
*
* NOTICE OF LICENSE
*
* 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.
*
* Copyright: 2007-2016 PagSeguro Internet Ltda.
* Licence: http://www.apache.org/licenses/LICENSE-2.0
*/
package br.com.uol.pagseguro.api.common.domain.converter;
import br.com.uol.pagseguro.api.common.domain.Bank;
import br.com.uol.pagseguro.api.utils.AbstractMapConverter;
import br.com.uol.pagseguro.api.utils.RequestMap;
/**
* Converter for bank. Used in version 3.
* Used to convert attributes of bank in request map.
*
* @author PagSeguro Internet Ltda.
*/
public class BankV3MapConverter extends AbstractMapConverter<Bank> {
/**
* Convert attributes of bank in request map
*
* @param requestMap Request Map used to pass params to api
* @param bank The interface of bank
* @see RequestMap
* @see Bank
* @see AbstractMapConverter#convert(Object)
*/
@Override
protected void convert(RequestMap requestMap, Bank bank) {
requestMap.putString("bank.name", bank.getBankName().getStringName());
}
}
| girinoboy/lojacasamento | pagseguro-api/src/main/java/br/com/uol/pagseguro/api/common/domain/converter/BankV3MapConverter.java | Java | mit | 1,581 |
package com.mnubo.java.sdk.client.mapper;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.type.MapType;
import com.fasterxml.jackson.databind.type.SimpleType;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import org.joda.time.format.DateTimeParser;
import java.util.*;
import static java.lang.String.format;
import static org.joda.time.DateTimeZone.UTC;
abstract class MapperUtils {
static final String TEXT_TYPE = "TEXT";
static final String UUID_TYPE = "UUID";
static final String DATETIME_TYPE = "DATETIME";
private static final String OWNER_INSTANCE_TYPE = "OWNER";
static final String OBJECT_INSTANCE_TYPE = "SMARTOBJECT";
private static final List<String> DATETIME_PATTERNS = Arrays.asList(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
"yyyy-MM-dd'T'HH:mm:ss.SSS",
"yyyy-MM-dd'T'HH:mm:ssZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ");
private static final DateTimeParser[] dateTimeParsers;
static {
dateTimeParsers = new DateTimeParser[DATETIME_PATTERNS.size()];
for(int point = 0; point < DATETIME_PATTERNS.size(); point++) {
dateTimeParsers[point] = DateTimeFormat.forPattern(DATETIME_PATTERNS.get(point)).getParser();
}
}
private static final DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder().append(null,
dateTimeParsers).toFormatter();
static <V, T> Map<V, T> readValuesAsMap(JsonParser parser, Class<V> keyType, Class<T> valueType)
throws IllegalStateException {
try {
MapType stringMapTypew = MapType.construct(HashMap.class, SimpleType.construct(keyType),
SimpleType.construct(valueType));
return (HashMap<V, T>) ObjectMapperConfig.genericObjectMapper.readValue(parser, stringMapTypew);
}
catch (Exception e) {
throw new IllegalStateException("reading json content", e.getCause());
}
}
static void throwIfNotProperType(String name, Object value, String type) {
if(value != null ) {
switch (type) {
case TEXT_TYPE:
if (!(value instanceof String)) {
throwIllegalArgument(name, value.toString(), type);
}
break;
case DATETIME_TYPE:
try {
dateTimeFormatter.parseDateTime(value.toString());
} catch (Exception ex) {
throw new IllegalArgumentException(
format("Field '%s' value '%s' does not match TYPE '%s' pattern supported", name, value,
type));
}
break;
case UUID_TYPE:
try {
UUID.fromString(value.toString());
} catch (Exception ex) {
throw new IllegalArgumentException("UUID has to be represented by the standard 36-char representation");
}
break;
case OWNER_INSTANCE_TYPE:
if (!(value instanceof Map)) {
throwIllegalArgument(name, value.toString(), type);
}
break;
case OBJECT_INSTANCE_TYPE:
if (!(value instanceof Map)) {
throwIllegalArgument(name, value.toString(), type);
}
break;
}
}
}
private static void throwIllegalArgument(String name, String value, String type) {
throw new IllegalArgumentException(format("Field '%s' value '%s' does not match TYPE '%s'", name, value, type));
}
static String convertToString(Object value) {
if(value == null) {
return null;
} else {
return value.toString();
}
}
static UUID convertToUUID(Object value) {
if(value == null) {
return null;
} else {
return UUID.fromString(value.toString());
}
}
static DateTime convertToDatetime(Object value) {
if(value == null) {
return null;
} else {
return DateTime.parse(value.toString()).withZone(UTC);
}
}
}
| mnubo/mnubo-java-sdk | src/main/java/com/mnubo/java/sdk/client/mapper/MapperUtils.java | Java | mit | 4,526 |
package com.teamcenter.TcLoadSimulate.Core.Exceptions;
import com.teamcenter.soa.client.model.ErrorStack;
/**
* Exception class that wraps the Teamcenter SOA partial error structure.
*
*/
public class PartialErrorException extends Exception {
private static final long serialVersionUID = 1L;
/**
* The errorstack retrieved from Teamcenter.
*/
private ErrorStack[] errorStack;
public PartialErrorException(ErrorStack[] errorStack) {
this.errorStack = errorStack;
}
public PartialErrorException(String message, ErrorStack[] errorStack) {
super(message);
this.errorStack = errorStack;
}
public ErrorStack[] getErrorStack() {
return errorStack;
}
public void setErrorStack(ErrorStack[] errorStack) {
this.errorStack = errorStack;
}
}
| mjonsson/TcLoadSimulate | TcLoadSimulate/src/com/teamcenter/TcLoadSimulate/Core/Exceptions/PartialErrorException.java | Java | mit | 799 |
package com.firefly.utils;
import org.apache.log4j.Logger;
public class LogUtil {
public static void info(Logger log, String msg) {
if (log.isInfoEnabled()) {
log.info(msg);
}
}
public static void info(Logger log, String msg, Object... data) {
if (log.isInfoEnabled()) {
StringBuffer sb = new StringBuffer(msg);
sb.append(":");
appendData(sb, data);
log.info(sb.toString());
}
}
public static void warn(Logger log, String msg, Object... data) {
StringBuffer sb = new StringBuffer(msg);
sb.append(":");
appendData(sb, data);
log.warn(sb.toString());
}
public static void debug(Logger log, String msg) {
if (log.isDebugEnabled()) {
log.debug(msg);
}
}
public static void debug(Logger log, String msg, Object... data) {
if (log.isDebugEnabled()) {
StringBuffer sb = new StringBuffer(msg);
sb.append(":");
appendData(sb, data);
log.debug(sb.toString());
}
}
public static void error(Logger log, String msg, Throwable t, Object... data) {
StringBuffer sb = new StringBuffer(msg);
sb.append(":");
appendData(sb, data);
log.error(sb.toString(), t);
}
public static void error(Logger log, String msg, Throwable t) {
log.error(msg, t);
}
public static void error(Logger log, String msg) {
log.error(msg);
}
private static void appendData(StringBuffer sb, Object... datas) {
for (int i = 0; i < datas.length; i++) {
sb.append(datas[i].toString());
if (i != datas.length - 1) {
sb.append("_");
}
}
}
}
| talentstrong/fireflyEnglish | common/src/main/java/com/firefly/utils/LogUtil.java | Java | mit | 1,875 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.