repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
rdmwfs/dobroreader-mod
src/org/anonymous/dobrochan/widget/DobroHomeItemView.java
1497
package org.anonymous.dobrochan.widget; import org.anonymous.dobrochan.DobroHomeItem; import org.anonymous.dobrochan.reader.R; import greendroid.widget.AsyncImageView; import greendroid.widget.itemview.ItemView; import greendroid.widget.item.Item; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.TextView; public class DobroHomeItemView extends LinearLayout implements ItemView { private TextView mTextView; private AsyncImageView mImageView; public DobroHomeItemView(Context context) { this(context, null); } public DobroHomeItemView(Context context, AttributeSet attrs) { super(context, attrs); } public void prepareItemView() { mTextView = (TextView) findViewById(R.id.gd_text); mImageView = (AsyncImageView) findViewById(R.id.gd_drawable); mImageView.setImageURI(null); mImageView.setScaleType(ScaleType.FIT_START); mImageView.setDefaultImageResource(R.drawable.banner); } public void setObject(Item object) { final DobroHomeItem item = (DobroHomeItem) object; mTextView.setText(item.text); final String uri = item.image_uri; if (uri == null) { mImageView.setVisibility(View.GONE); } else { mImageView.setVisibility(View.VISIBLE); mImageView.setUrl(uri); } } }
gpl-3.0
OlafLee/RankSys
RankSys-novelty/src/main/java/es/uam/eps/ir/ranksys/novelty/unexp/reranking/package-info.java
858
/* * Copyright (C) 2015 Information Retrieval Group at Universidad Autonoma * de Madrid, http://ir.ii.uam.es * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Unexpectedness re-rankers. */ package es.uam.eps.ir.ranksys.novelty.unexp.reranking;
gpl-3.0
chvink/kilomek
megamek/src/megamek/common/weapons/CLStreakSRM6Prototype.java
1568
/** * MegaMek - Copyright (C) 2005 Ben Mazur (bmazur@sev.org) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program 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 General Public License * for more details. */ package megamek.common.weapons; import megamek.common.TechConstants; /** * @author Sebastian Brocks */ public class CLStreakSRM6Prototype extends CLPrototypeStreakSRMWeapon { /** * */ private static final long serialVersionUID = -2234544642223178737L; /** * */ public CLStreakSRM6Prototype() { super(); techLevel.put(3071, TechConstants.T_CLAN_EXPERIMENTAL); name = "Streak SRM 6 (CP)"; setInternalName("CLStreakSRM6Prototype"); heat = 4; rackSize = 6; shortRange = 3; mediumRange = 6; longRange = 9; extremeRange = 12; tonnage = 4.5f; criticals = 2; bv = 59; cost = 80000; shortAV = 8; maxRange = RANGE_SHORT; introDate = 2820; extinctDate = 2825; availRating = new int[] { RATING_X, RATING_F, RATING_X }; techRating = RATING_E; techLevel.put(2820, techLevel.get(3071)); } }
gpl-3.0
imyelmo/relod.net
reload/Link/TCP/TCPClient.java
2241
/******************************************************************************* * <relod.net: GPLv3 beta software implementing RELOAD - draft-ietf-p2psip-base-26 > * Copyright (C) <2013> <Marcos Lopez-Samaniego, Isaias Martinez-Yelmo, Roberto Gonzalez-Sanchez> Contact: isaias.martinezy@uah.es * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * This program 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 General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *******************************************************************************/ package reload.Link.TCP; import java.io.*; import java.net.*; import reload.Common.*; public class TCPClient extends TCP{ private Socket socket; private DataOutputStream out; private DataInputStream in; public TCPClient(IpAddressPort ip) throws Exception{ socket = new Socket(ip.getAddress(), ip.getPort()); out = new DataOutputStream(socket.getOutputStream()); in = new DataInputStream(socket.getInputStream()); } public void send(byte[] data) throws IOException{ send(data, out); // Super } public byte[] receive() throws IOException{ return receive(in); // Super } public void close() throws IOException{ in.close(); out.close(); socket.close(); } public InetAddress getInetAddress(){ return socket.getInetAddress(); } }
gpl-3.0
shelllbw/workcraft
PetrifyPlugin/src/org/workcraft/plugins/petrify/tasks/SynthesisResult.java
845
package org.workcraft.plugins.petrify.tasks; public class SynthesisResult { private final String equations; private final String verilog; private final String log; private final String stdout; private final String stderr; public SynthesisResult(String equations, String verilog, String log, String stdout, String stderr) { this.equations = equations; this.verilog = verilog; this.log = log; this.stdout = stdout; this.stderr = stderr; } public String getEquation() { return this.equations; } public String getVerilog() { return this.verilog; } public String getLog() { return this.log; } public String getStdout() { return this.stdout; } public String getStderr() { return this.stderr; } }
gpl-3.0
Nianna/Karedi
src/main/java/com/github/nianna/karedi/parser/BaseParser.java
1940
package main.java.com.github.nianna.karedi.parser; import main.java.com.github.nianna.karedi.parser.element.InvalidSongElementException; import main.java.com.github.nianna.karedi.parser.element.VisitableSongElement; import main.java.com.github.nianna.karedi.parser.elementparser.EndOfSongParser; import main.java.com.github.nianna.karedi.parser.elementparser.LineBreakParser; import main.java.com.github.nianna.karedi.parser.elementparser.NoteParser; import main.java.com.github.nianna.karedi.parser.elementparser.SongElementParser; import main.java.com.github.nianna.karedi.parser.elementparser.TagParser; import main.java.com.github.nianna.karedi.parser.elementparser.TrackParser; /** * Creates appropriate {@link VisitableSongElement}s from their string representations. * <p> * Uses provided chain of parsers or the default one, which consists of a * {@link TagParser}, {@link NoteParser}, {@link LineBreakParser}, * {@link TrackParser} and {@link EndOfSongParser} (in this order). * <p> * The default parsers recognize only valid input, otherwise * {@link InvalidSongElementException} is thrown. */ public class BaseParser implements Parser { private SongElementParser parserChain; public static SongElementParser getDefaultParserChain() { SongElementParser chain = new TagParser(); chain.addNext(new NoteParser()); chain.addNext(new LineBreakParser()); chain.addNext(new TrackParser()); chain.addNext(new EndOfSongParser()); return chain; } public BaseParser(SongElementParser parserChain) { this.parserChain = parserChain; } public BaseParser() { this(getDefaultParserChain()); } @Override public VisitableSongElement parse(String fileLine) throws InvalidSongElementException { return parserChain.parse(fileLine); } public void setParserChain(SongElementParser parserChain) { this.parserChain = parserChain; } public SongElementParser getParserChain() { return parserChain; } }
gpl-3.0
devjn/Android-Map-KotlinSample
ios/src/main/java/org/moe/googlemaps/GMSPanoramaCamera.java
5514
package org.moe.googlemaps; import apple.NSObject; import apple.foundation.NSArray; import apple.foundation.NSMethodSignature; import apple.foundation.NSSet; import org.moe.googlemaps.struct.GMSOrientation; import org.moe.natj.c.ann.FunctionPtr; import org.moe.natj.general.NatJ; import org.moe.natj.general.Pointer; import org.moe.natj.general.ann.ByValue; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Mapped; import org.moe.natj.general.ann.MappedReturn; import org.moe.natj.general.ann.NInt; import org.moe.natj.general.ann.NUInt; import org.moe.natj.general.ann.Owned; import org.moe.natj.general.ann.Runtime; import org.moe.natj.general.ptr.VoidPtr; import org.moe.natj.objc.Class; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.SEL; import org.moe.natj.objc.ann.ObjCClassBinding; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper; @Generated @Library("GoogleMaps") @Runtime(ObjCRuntime.class) @ObjCClassBinding public class GMSPanoramaCamera extends NSObject { static { NatJ.register(); } @Generated protected GMSPanoramaCamera(Pointer peer) { super(peer); } @Generated @Selector("FOV") public native double FOV(); @Generated @Selector("accessInstanceVariablesDirectly") public static native boolean accessInstanceVariablesDirectly(); @Generated @Owned @Selector("alloc") public static native GMSPanoramaCamera alloc(); @Generated @Selector("allocWithZone:") @MappedReturn(ObjCObjectMapper.class) public static native Object allocWithZone(VoidPtr zone); @Generated @Selector("automaticallyNotifiesObserversForKey:") public static native boolean automaticallyNotifiesObserversForKey(String key); @Generated @Selector("cameraWithHeading:pitch:zoom:") public static native GMSPanoramaCamera cameraWithHeadingPitchZoom( double heading, double pitch, float zoom); @Generated @Selector("cameraWithHeading:pitch:zoom:FOV:") public static native GMSPanoramaCamera cameraWithHeadingPitchZoomFOV( double heading, double pitch, float zoom, double FOV); @Generated @Selector("cameraWithOrientation:zoom:") public static native GMSPanoramaCamera cameraWithOrientationZoom( @ByValue GMSOrientation orientation, float zoom); @Generated @Selector("cameraWithOrientation:zoom:FOV:") public static native GMSPanoramaCamera cameraWithOrientationZoomFOV( @ByValue GMSOrientation orientation, float zoom, double FOV); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:") public static native void cancelPreviousPerformRequestsWithTarget( @Mapped(ObjCObjectMapper.class) Object aTarget); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:") public static native void cancelPreviousPerformRequestsWithTargetSelectorObject( @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector, @Mapped(ObjCObjectMapper.class) Object anArgument); @Generated @Selector("class") public static native Class class_objc_static(); @Generated @Selector("classFallbacksForKeyedArchiver") public static native NSArray<String> classFallbacksForKeyedArchiver(); @Generated @Selector("classForKeyedUnarchiver") public static native Class classForKeyedUnarchiver(); @Generated @Selector("debugDescription") public static native String debugDescription_static(); @Generated @Selector("description") public static native String description_static(); @Generated @Selector("hash") @NUInt public static native long hash_static(); @Generated @Selector("init") public native GMSPanoramaCamera init(); @Generated @Selector("initWithOrientation:zoom:FOV:") public native GMSPanoramaCamera initWithOrientationZoomFOV( @ByValue GMSOrientation orientation, float zoom, double FOV); @Generated @Selector("initialize") public static native void initialize(); @Generated @Selector("instanceMethodForSelector:") @FunctionPtr(name = "call_instanceMethodForSelector_ret") public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector( SEL aSelector); @Generated @Selector("instanceMethodSignatureForSelector:") public static native NSMethodSignature instanceMethodSignatureForSelector( SEL aSelector); @Generated @Selector("instancesRespondToSelector:") public static native boolean instancesRespondToSelector(SEL aSelector); @Generated @Selector("isSubclassOfClass:") public static native boolean isSubclassOfClass(Class aClass); @Generated @Selector("keyPathsForValuesAffectingValueForKey:") public static native NSSet<String> keyPathsForValuesAffectingValueForKey( String key); @Generated @Selector("load") public static native void load_objc_static(); @Generated @Owned @Selector("new") @MappedReturn(ObjCObjectMapper.class) public static native Object new_objc(); @Generated @Selector("orientation") @ByValue public native GMSOrientation orientation(); @Generated @Selector("resolveClassMethod:") public static native boolean resolveClassMethod(SEL sel); @Generated @Selector("resolveInstanceMethod:") public static native boolean resolveInstanceMethod(SEL sel); @Generated @Selector("setVersion:") public static native void setVersion(@NInt long aVersion); @Generated @Selector("superclass") public static native Class superclass_static(); @Generated @Selector("version") @NInt public static native long version_static(); @Generated @Selector("zoom") public native float zoom(); }
gpl-3.0
sunitamdol/SysPro
src/in/witsolapur/adapter/TextViewAdapterCompiler.java
4140
package in.witsolapur.adapter; import in.witsolapur.sysproapp.R; import java.util.ArrayList; import java.util.HashMap; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.Toast; public class TextViewAdapterCompiler extends BaseAdapter { private static final String TAG = null; private ArrayList<Integer> nos; private HashMap<Integer, String> data; private int rows, columns; private Context context; private HashMap<Integer, String> chData; public TextViewAdapterCompiler(Context context, int[] nos,String chars[], int rows, int columns) { this.nos = new ArrayList<Integer>(); data = new HashMap<Integer, String>(); chData=new HashMap<Integer, String>(); for (int i=0;i<nos.length;i++) { this.nos.add(nos[i]); chData.put(nos[i], chars[i]); //Log.i(TAG, "Addining : " + nos[i]); // data.put(x, ""); } this.rows = rows; this.columns = columns; this.context = context; } public int getCount() { // TODO Auto-generated method stub return rows * columns; } public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } ViewHolder holder; public View getView(final int position, View convertView, ViewGroup arg2) { // TODO Auto-generated method stub holder = new ViewHolder(); if (convertView == null) { // Toast.makeText(context, "New Holder at : " + position, // 1000).show(); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.view_textview, null); holder.txtChar = (EditText) convertView.findViewById(R.id.txtChar); // Log.i(TAG, "control at : "+position+" created"); convertView.setTag(holder); } else { // Log.i(TAG, "control at : "+position+" used"); holder = (ViewHolder) convertView.getTag(); holder.txtChar.setText(data.get(position)); //Log.i(TAG, "Using control at " + position + " seting value " //+ data.get(position)); } holder.txtChar.setBackgroundResource(R.drawable.text_border); if (nos.contains(position)) { holder.txtChar.setVisibility(View.VISIBLE); holder.txtChar.setText(data.get(position)); int id = R.drawable.text_border; switch (position) { case 7: id = R.drawable.one; break; case 26: id = R.drawable.two; break; case 28: id = R.drawable.three; break; case 33: id = R.drawable.four; break; case 59: id = R.drawable.five; break; case 98: id = R.drawable.six; break; case 103: id = R.drawable.seven; break; case 127: id = R.drawable.eight; break; case 162: id = R.drawable.nine; break; case 172: id = R.drawable.ten; break; } holder.txtChar.setBackgroundResource(id); } else { holder.txtChar.setVisibility(View.INVISIBLE); } holder.txtChar.setOnFocusChangeListener(new OnFocusChangeListener() { public void onFocusChange(View view, boolean arg1) { if (arg1) { Log.i(TAG, "Got focus " + position); } else { String text = ((EditText) view).getText().toString(); data.put(position, text); Log.i(TAG, "Lost focus " + position + " storing value " + text); Log.i(TAG,"position : "+position+" entered text : "+text+" correct text: "+chData.get(position)); if(!chData.get(position).equals(text)){ Toast.makeText(context, "Incorrect character",Toast.LENGTH_LONG).show(); } else { Toast.makeText(context, "Correct character",Toast.LENGTH_LONG).show(); } } } }); return convertView; } static class ViewHolder { EditText txtChar; } }
gpl-3.0
Olyol95/Saga
src/org/saga/settlements/Settlement.java
25915
package org.saga.settlements; import org.bukkit.event.player.PlayerQuitEvent; import org.saga.Clock; import org.saga.Clock.DaytimeTicker; import org.saga.Clock.MinuteTicker; import org.saga.Saga; import org.saga.SagaLogger; import org.saga.buildings.Building; import org.saga.buildings.BuildingDefinition; import org.saga.buildings.production.ProductionBuilding; import org.saga.config.*; import org.saga.config.ProficiencyConfiguration.InvalidProficiencyException; import org.saga.dependencies.EconomyDependency; import org.saga.factions.Faction; import org.saga.factions.SiegeManager; import org.saga.listeners.events.SagaBuildEvent; import org.saga.listeners.events.SagaBuildEvent.BuildOverride; import org.saga.messages.EconomyMessages; import org.saga.messages.SettlementMessages; import org.saga.messages.colours.Colour; import org.saga.player.Proficiency; import org.saga.player.ProficiencyDefinition; import org.saga.player.SagaPlayer; import org.saga.statistics.StatisticsManager; import java.util.*; /** * @author andf * */ public class Settlement extends Bundle implements MinuteTicker, DaytimeTicker { /** * Settlement level. */ private Integer level; // TODO: Remove unused settlement level. /** * Claims. */ private Double claims; /** * Build points. */ private Double buildPoints; /** * Coins banked. */ private Double coins; /** * Player roles. */ private Hashtable<String, Proficiency> playerRoles; /** * Player last seen dates. */ private Hashtable<String, Date> lastSeen; /** * Work points for different roles. */ private Hashtable<String, Double> workPoints; /** * Settlement wages. */ private Hashtable<String, Double> wages; // Initialisation: /** * Sets name. * * @param name * name */ public Settlement(String name) { super(name); level = 0; claims = SettlementConfiguration.config().getInitialClaims() .doubleValue(); buildPoints = SettlementConfiguration.config().getInitialBuildPoints() .doubleValue(); coins = 0.0; playerRoles = new Hashtable<>(); lastSeen = new Hashtable<>(); workPoints = new Hashtable<>(); wages = new Hashtable<>(); } /* * (non-Javadoc) * * @see org.saga.chunkGroups.ChunkBundle#completeExtended() */ @Override public void complete() { super.complete(); if (level == null) { SagaLogger.nullField(this, "level"); level = 0; } // TODO: Remove claims conversion: if (claims == null && level != null) { int maxLevel = 50; claims = SettlementConfiguration.config().getMaxClaims() .doubleValue() * level.doubleValue() / maxLevel; SagaLogger.nullField(this, "claims"); } // TODO: Remove building points conversion: if (buildPoints == null) { buildPoints = SettlementConfiguration.config() .getBuildPoints(getSize()).doubleValue(); } if (claims == null) { SagaLogger.nullField(this, "claims"); buildPoints = 0.0; } if (buildPoints == null) { SagaLogger.nullField(this, "buildPoints"); buildPoints = 0.0; } if (coins == null) { SagaLogger.nullField(this, "coins"); coins = 0.0; } if (lastSeen == null) { SagaLogger.nullField(this, "lastSeen"); lastSeen = new Hashtable<>(); } if (playerRoles == null) { SagaLogger.nullField(this, "playerRoles"); playerRoles = new Hashtable<>(); } if (workPoints == null) { SagaLogger.nullField(this, "workPoints"); workPoints = new Hashtable<>(); } if (wages == null) { SagaLogger.nullField(this, "wages"); wages = new Hashtable<>(); } Enumeration<String> playerNames = playerRoles.keys(); while (playerNames.hasMoreElements()) { String playerName; Proficiency proficiency = null; playerName = playerNames.nextElement(); try { proficiency = playerRoles.get(playerName); proficiency.complete(); } catch (InvalidProficiencyException e) { SagaLogger.severe(this, "tried to add an invalid " + proficiency + " role:" + e.getMessage()); playerRoles.remove(playerName); } catch (NullPointerException e) { SagaLogger.severe(this, "tried to add an null proficiency"); playerRoles.remove(playerName); } } // Fix roles: try { ArrayList<String> members = getMembers(); for (String member : members) { if (getRole(member) != null) continue; Proficiency role = ProficiencyConfiguration.config() .createProficiency( SettlementConfiguration.config() .getDefaultRole()); playerRoles.put(member, role); } } catch (InvalidProficiencyException e) { SagaLogger.severe(this, "failed to set " + SettlementConfiguration.config().getDefaultRole() + " role, because the role name is invalid"); } } /* * (non-Javadoc) * * @see org.saga.chunkGroups.ChunkBundle#delete() */ @Override public void delete() { super.delete(); // Clear roles: playerRoles.clear(); } /* * (non-Javadoc) * * @see org.saga.chunkGroups.ChunkBundle#enable() */ @Override public void enable() { super.enable(); Clock.clock().enableMinuteTick(this); Clock.clock().enableDaytimeTicking(this); } /* * (non-Javadoc) * * @see org.saga.settlements.Bundle#disable() */ @Override public void disable() { super.disable(); } /** * Adds a new settlement. * * @param settlement * settlement * @param owner * owner */ public static void create(Settlement settlement, SagaPlayer owner) { // Forward: Bundle.create(settlement, owner); // // Set owners role: // try { // Proficiency role = // ProficiencyConfiguration.config().createProficiency(settlement.getDefinition().ownerRole); // settlement.setRole(owner, role); // } catch (InvalidProficiencyException e) { // SagaLogger.severe(settlement, "failed to set " + // settlement.getDefinition().ownerRole + // " role, because the role name is invalid"); // } } // Player management: /* * (non-Javadoc) * * @see org.saga.chunkGroups.ChunkBundle#addPlayer3(org.saga.SagaPlayer) */ @Override public void addMember(SagaPlayer sagaPlayer) { super.addMember(sagaPlayer); // Set default role: try { Proficiency role = ProficiencyConfiguration.config() .createProficiency( SettlementConfiguration.config().getDefaultRole()); setRole(sagaPlayer, role); } catch (InvalidProficiencyException e) { SagaLogger.severe(this, "failed to set " + SettlementConfiguration.config().getDefaultRole() + " role, because the role name is invalid"); } // Last seen: lastSeen.put(sagaPlayer.getName(), Calendar.getInstance().getTime()); } /* * (non-Javadoc) * * @see org.saga.chunkGroups.ChunkBundle#removePlayer3(org.saga.SagaPlayer) */ @Override public void removeMember(SagaPlayer sagaPlayer) { // Clear role: clearRole(sagaPlayer); // Forward: super.removeMember(sagaPlayer); // Last seen: lastSeen.remove(sagaPlayer.getName()); } // Roles: /** * Gets a player role. * * @param playerName * player name * @return player role. null if none */ public Proficiency getRole(String playerName) { return playerRoles.get(playerName); } /** * Adds a role to the player. * * @param sagaPlayer * saga player * @param role * role */ public void setRole(SagaPlayer sagaPlayer, Proficiency role) { // Clear previous role: if (playerRoles.get(sagaPlayer.getName()) != null) { clearRole(sagaPlayer); } // Add to settlement: playerRoles.put(sagaPlayer.getName(), role); // Update: sagaPlayer.update(); } /** * Clears a role from the player. * * @param sagaPlayer * sga player */ public void clearRole(SagaPlayer sagaPlayer) { // Check role: Proficiency role = playerRoles.get(sagaPlayer.getName()); if (role == null) { return; } // Remove from settlement: playerRoles.remove(sagaPlayer.getName()); // Update: sagaPlayer.update(); } /** * Gets the amount of roles used. * * @param roleName * role name * @return amount of roles used */ public Integer getUsedRoles(String roleName) { Integer total = 0; Collection<Proficiency> roles = playerRoles.values(); for (Proficiency role : roles) { if (role.getName().equals(roleName)) total++; } return total; } /** * Gets the amount of roles available. * * @param roleName * role name * @return amount of roles available */ public Integer getAvailableRoles(String roleName) { Double count = 0.0; ArrayList<Building> buildings = getBuildings(); for (Building building : buildings) { count += building.getDefinition().getRoles(roleName); } return count.intValue(); } /** * Gets the amount of roles remaining. * * @param roleName * role name * @return amount of roles remaining */ public Integer getRemainingRoles(String roleName) { return getAvailableRoles(roleName) - getUsedRoles(roleName); } /** * Checks if the given role is available. * * @param hierarchy * role hierarchy level * @return true if available */ public boolean isRoleAvailable(String roleName) { ProficiencyDefinition role = ProficiencyConfiguration.config() .getDefinition(roleName); if (role == null) return false; return role.getHierarchyLevel() == FactionConfiguration.config().getHierarchyMin() || getRemainingRoles(roleName) > 0; } /** * Gets members with the given role. * * @param roleName * role name * @return members with the given role */ public ArrayList<String> getMembersForRoles(String roleName) { ArrayList<String> filtMembers = new ArrayList<>(); ArrayList<String> allMembers = getMembers(); for (String member : allMembers) { Proficiency role = getRole(member); if (role != null && role.getName().equals(roleName)) filtMembers.add(member); } return filtMembers; } // Work points: /** * Gets the work points for the given role. * * @param roleName * role name * @return work points */ public Double getWorkPoints(String roleName) { Double points = workPoints.get(roleName); if (points == null) points = 0.0; return points; } /** * Takes work points. * * @param roleName * role name * @param requested * requested amount * @return work points taken */ public Double takeWorkPoints(String roleName, Double requested) { Double available = getWorkPoints(roleName); if (available - requested < 0) requested = available; if (available - requested > 0) workPoints.put(roleName, available - requested); else workPoints.remove(roleName); return requested; } // Wages: /** * Handles wages. * */ private void handleWages() { if (!EconomyConfiguration.config().isEnabled()) return; // Pay online members: Collection<SagaPlayer> online = getOnlineMembers(); for (SagaPlayer sagaPlayer : online) { Double wage = getWage(sagaPlayer.getName()); if (wage == 0.0) continue; // Pay: EconomyDependency.addCoins(sagaPlayer, wage); // Reset: resetWage(sagaPlayer.getName()); // Inform: information(EconomyMessages.gotPaid(this, wage), sagaPlayer); // Statistics: StatisticsManager.manager().addWages(this, wage); } } /** * Distributes wages. * * @param paid * total amount paid */ public void distribWages(Double paid) { if (!EconomyConfiguration.config().isEnabled()) return; Collection<SagaPlayer> online = getOnlineMembers(); double[] wageWeigths = new double[online.size()]; String[] names = new String[online.size()]; double total = 0.0; // Percentages: int i = 0; for (SagaPlayer member : online) { wageWeigths[i] = EconomyConfiguration.config().getWageWeigth(this, member); names[i] = member.getName(); total += wageWeigths[i]; i++; } // Add wages: if (total != 0) { for (int j = 0; j < names.length; j++) { Double wage = getWage(names[j]); wage += wageWeigths[j] / total * paid; this.wages.put(names[j], wage); } } } /** * Gets members wage. * * @param memberName * member name * @return wage */ public Double getWage(String memberName) { Double wage = wages.get(memberName); if (wage == null) return 0.0; return wage; } /** * Resets members wage. * * @param memberName * member name */ public void resetWage(String memberName) { wages.remove(memberName); } // Claims: /** * Gets the amount of claims. * * @return amount of claims */ public Double getClaims() { return claims; } /** * Sets the amount of claims. * * @param claims * amount of claims */ public void setClaims(Double claims) { this.claims = claims; } /** * Modifies the amount of claims. * * @param amount * amount to modify by */ public void modClaims(Double amount) { claims += amount; } /** * Gets used claims. * * @return used claims */ public Integer getUsedClaims() { return getSize(); } /** * Gets total claims. * * @return total claims. */ public Integer getTotalClaims() { if (claims > SettlementConfiguration.config().getMaxClaims()) return SettlementConfiguration.config().getMaxClaims(); return claims.intValue(); } /** * Gets available claims. * * @return available claims */ public Integer getAvailableClaims() { return getTotalClaims() - getUsedClaims(); } /** * Check if there is a claim available. * * @return true if available */ public boolean isClaimsAvailable() { return getAvailableClaims() > 0 || isOptionEnabled(BundleToggleable.UNLIMITED_CLAIMS); } /** * Gets the claim progress. * * @return claim progress, values 0.0 - 1.0 */ public Double getClaimProgress() { return claims - claims.intValue(); } // Building points: /** * Gets the amount of buildPoints. * * @return amount of buildPoints */ public Double getBuildPoints() { return buildPoints; } /** * Sets the amount of buildPoints. * * @param buildPoints * amount of buildPoints */ public void setBuildPoints(Double buildPoints) { this.buildPoints = buildPoints; } /** * Modifies the amount of building points. * * @param amount * amount to modify by */ public void modBuildPoints(Double amount) { buildPoints += amount; } /** * Gets the amount of building points available. * * @return amount building points available */ public Integer getAvailableBuildPoints() { return buildPoints.intValue(); } /** * Gets the amount of building points used. * * @return amount of building points used */ public Integer getUsedBuildPoints() { Integer total = 0; ArrayList<Building> buildings = getBuildings(); for (Building building : buildings) { total += building.getDefinition().getBuildPoints(); } return total; } /** * Gets the amount of building points remaining. * * @return amount of building points remaining */ public Integer getRemainingBuildPoints() { return getAvailableBuildPoints() - getUsedBuildPoints(); } /** * Checks if there are building points are available. * * @param building * building * @return true if building points available */ public boolean isBuildPointsAvailable(Building building) { return isOptionEnabled(BundleToggleable.UNLIMITED_BUILDINGS) || getRemainingBuildPoints() >= building.getDefinition().getBuildPoints(); } /** * Gets the building point progress. * * @return building point progress, values 0.0 - 1.0 */ public Double getBuildPointsProgress() { return buildPoints - buildPoints.intValue(); } // Bank: /** * Gets the amount of coins banked. * * @return coins banked */ public Double getCoins() { return coins; } /** * Pays coins. * * @param amount * amount to pay */ public void payCoins(Double amount) { Double settlementShare = amount * EconomyConfiguration.config().getSettlementPercent(); Double factionShare = amount * EconomyConfiguration.config().getSettlementFactionPercent(); Double membersShare = amount * EconomyConfiguration.config().getSettlementMemberPercent(); // Members: distribWages(membersShare); // Settlement: coins += settlementShare; // Faction: Faction owningFaction = SiegeManager.manager() .getOwningFaction(getId()); if (owningFaction != null) owningFaction.payCoins(factionShare); } /** * Requests coins. * * @param request * amount request */ public Double requestCoins(Double request) { Double given = request; if (given > coins) given = coins; coins -= given; return given; } /** * Modifies the amount of coins. * * @param amount * amount to modify by */ public void modCoins(Double amount) { coins += amount; } // Buildings: /* * (non-Javadoc) * * @see org.saga.chunkGroups.ChunkBundle#getTotalBuildings(java.lang.String) */ @Override public Integer getAvailableBuildings(String buildingName) { BuildingDefinition definition = BuildingConfiguration.config() .getBuildingDefinition(buildingName); if (definition == null) return 0; return definition.getAvailableAmount(getSize()); } // Permissions: /* * (non-Javadoc) * * @see * org.saga.chunkGroups.ChunkBundle#hasPermisson(org.saga.player.SagaPlayer, * org.saga.settlements.Settlement.SettlementPermission) */ public boolean hasPermission(SagaPlayer sagaPlayer, SettlementPermission permission) { // Owner or admin: if (isOwner(sagaPlayer.getName()) || sagaPlayer.isAdminMode()) return true; // Check role: Proficiency role = playerRoles.get(sagaPlayer.getName()); if (role == null) { return false; } // Check permission: return role.hasSettlementPermission(permission); } // Messages: /* * (non-Javadoc) * * @see org.saga.chunks.Bundle#chat(org.saga.player.SagaPlayer, * java.lang.String) */ @Override public void chat(SagaPlayer sagaPlayer, String message) { message = Colour.normal2 + "[" + Colour.normal1 + SettlementMessages.roledPlayer(this, sagaPlayer) + Colour.normal2 + "] " + message; Collection<SagaPlayer> onlineMembers = getOnlineMembers(); for (SagaPlayer onlineMember : onlineMembers) { onlineMember.message(message); } } // Active members: /** * Gets player last seen date. * * @param name * player name * @return last seen date */ public Date getLastSeen(String name) { // Online: if (Saga.plugin().isSagaPlayerLoaded(name)) return Calendar.getInstance().getTime(); // Offline: Date lastDate = lastSeen.get(name); if (lastDate == null) { SagaLogger.severe(this, "last seen date not found for " + name + " player"); lastDate = Calendar.getInstance().getTime(); lastSeen.put(name, lastDate); } return lastDate; } /** * Checks if the member is active. * * @param name * player name * @return true if active */ public boolean isMemberActive(String name) { Calendar inactiveCal = Calendar.getInstance(); inactiveCal.add(Calendar.DAY_OF_MONTH, -SettlementConfiguration.config().inactiveSetDays); Date inactivate = inactiveCal.getTime(); Date lastSeen = getLastSeen(name); return !inactivate.after(lastSeen); } /** * Gets inactive member count. * * @return inactive member count */ public int countInactiveMembers() { int inactive = 0; ArrayList<String> players = getMembers(); for (String playerName : players) { if (!isMemberActive(playerName)) inactive++; } return inactive; } /** * Gets active member count. * * @return active member count */ public int countActiveMembers() { int active = 0; ArrayList<String> players = getMembers(); for (String playerName : players) { if (isMemberActive(playerName)) active++; } return active; } // Requirements: /** * Check if settlement level requirements are met. * * @return true if the requirements are met */ public boolean checkRequirements() { return checkActiveMembers() && checkBuildings(); } /** * Checks if the settlement has enough active members. * * @return true if enough active members */ public boolean checkActiveMembers() { return countActiveMembers() >= SettlementConfiguration.config() .getRequiredActiveMembers(getSize()); } /** * Checks if the settlement has required buildings. * * @return true if the settlement has required buildings */ public boolean checkBuildings() { return SettlementConfiguration.config().checkBuildingRequirements(this); } // Events: /* * (non-Javadoc) * * @see org.saga.chunkGroups.ChunkBundle#onBuild(org.saga.listeners.events. * SagaBuildEvent) */ @Override public void onBuild(SagaBuildEvent event) { // Add override: if (!hasPermission(event.getSagaPlayer(), SettlementPermission.BUILD)) event.addBuildOverride(BuildOverride.SETTLEMENT_DENY); } /* * (non-Javadoc) * * @see * org.saga.chunkGroups.ChunkBundle#onMemberQuit(org.bukkit.event.player * .PlayerQuitEvent, org.saga.player.SagaPlayer) */ @Override public void onMemberQuit(PlayerQuitEvent event, SagaPlayer sagaPlayer) { // Update last seen: lastSeen.put(sagaPlayer.getName(), Calendar.getInstance().getTime()); } // Timed: /* * (non-Javadoc) * * @see org.saga.Clock.MinuteTicker#clockMinuteTick() */ @Override public boolean clockMinuteTick() { if (!isEnabled()) return false; int online = getOnlineMembers().size(); // Statistics: StatisticsManager.manager().addManminutes(this, online); // Work: handleWork(); // Collect: handleCollect(); // Produce: handleProduction(); // Check requirements: if (checkRequirements()) { // Increase claims: if (claims < SettlementConfiguration.config().getMaxClaims()) { claims += SettlementConfiguration.config().getClaimsPerMinute( online); // Statistics: StatisticsManager.manager().addSettlementClaims( this, SettlementConfiguration.config().getClaimsPerMinute( online)); } // Increase build points: if (buildPoints < SettlementConfiguration.config() .getMaxBuildPoints()) { buildPoints += SettlementConfiguration.config() .getBuildPointsPerMinute(online); // Statistics: StatisticsManager.manager().addSettlementBuildPoints( this, SettlementConfiguration.config() .getBuildPointsPerMinute(online)); } } return true; } /* * (non-Javadoc) * * @see * org.saga.Clock.DaytimeTicker#daytimeTick(org.saga.Clock.DaytimeTicker * .Daytime) */ @Override public boolean daytimeTick(Daytime daytime) { // Handle wages: if (daytime == EconomyConfiguration.config().getSettlementWagesTime()) handleWages(); return true; } /* * (non-Javadoc) * * @see org.saga.Clock.DaytimeTicker#checkWorld(java.lang.String) */ @Override public boolean checkWorld(String worldName) { return worldName .equals(GeneralConfiguration.config().getDefaultWorld()); } // Production: /** * Handles work points tick. * */ public void handleWork() { // Increase work points: Hashtable<String, Double> onlineRolesTotals = new Hashtable<>(); Collection<SagaPlayer> members = getOnlineMembers(); for (SagaPlayer sagaPlayer : members) { Proficiency role = getRole(sagaPlayer.getName()); if (role == null) continue; workPoints.put(role.getName(), getWorkPoints(role.getName()) + 1); Double total = onlineRolesTotals.get(role.getName()); if (total == null) total = 0.0; onlineRolesTotals.put(role.getName(), total + 1); } // Trim work points: Set<String> onlineRoles = onlineRolesTotals.keySet(); for (String role : onlineRoles) { if (workPoints.get(role) > onlineRolesTotals.get(role)) workPoints.put(role, onlineRolesTotals.get(role)); } // Distribute points: ArrayList<ProductionBuilding> prBuildings = getBuildings(ProductionBuilding.class); for (ProductionBuilding prBuilding : prBuildings) { prBuilding.work(); } } /** * Handles resource collection. * */ public void handleCollect() { ArrayList<ProductionBuilding> prBuildings = getBuildings(ProductionBuilding.class); for (ProductionBuilding prBuilding : prBuildings) { prBuilding.collect(); } } /** * Handles resource production: * */ public void handleProduction() { ArrayList<ProductionBuilding> prBuildings = getBuildings(ProductionBuilding.class); for (ProductionBuilding prBuilding : prBuildings) { prBuilding.produce(); } } // Other: /* * (non-Javadoc) * * @see org.saga.chunkGroups.ChunkBundle#toString() */ @Override public String toString() { return getId() + " (" + getName() + ")"; } // Types: /** * Settlement permissions. * * @author andf * */ public enum SettlementPermission { INVALID, TOGGLE_UNLIMITED_STORAGE, // General: ACCESS_WAREHOUSE, ACCESS_STORAGE, ADD_COINS, OPEN_HOME_CONTAINERS, OPEN_SETTLEMENT_CONTAINERS, BUILD, BUILD_BUILDING, BUILDING_UPGRADE, BUY_CLAIMS, BUY_BUILD_POINTS, CLAIM, CLAIM_SETTLEMENT, CRUMBLE_ARENA_SETUP, ABANDON, DECLARE_OWNER, DISSOLVE, FLASH_CHUNK, INVITE, KICK, SET_AFFILIATION, SET_ROLE, SET_BUILDING, TOWN_SQUARE_SET_SPAWN, REMOVE_AFFILIATION, REMOVE_BUILDING, REMOVE_COINS, RENAME, RESIGN, MEMBER_COMMAND, SPAWN, STORAGE_AREA_ADD, STORAGE_AREA_REMOVE, STORAGE_AREA_FLASH, // Farm: HURT_FARM_ANIMALS, // Home: REMOVE_RESIDENT, ADD_RESIDENT, // Trading post: MANAGE_EXPORT, MANAGE_IMPORT, MANAGE_SELL, MANAGE_BUY } }
gpl-3.0
hdecarne/de.carne
src/test/java/de/carne/test/util/StringsTest.java
3820
/* * Copyright (c) 2016-2020 Holger de Carne and contributors, All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.carne.test.util; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import de.carne.util.Strings; /** * Test {@linkplain Strings} class. */ class StringsTest { @Test void testIsEmpty() { Assertions.assertTrue(Strings.isEmpty(null)); Assertions.assertTrue(Strings.isEmpty("")); Assertions.assertFalse(Strings.isEmpty(" ")); Assertions.assertFalse(Strings.notEmpty(null)); Assertions.assertFalse(Strings.notEmpty("")); Assertions.assertTrue(Strings.notEmpty(" ")); } @Test void testValueOf() { Assertions.assertNotNull(Strings.valueOf(null)); Assertions.assertNotNull(Strings.valueOf(new Object() { @SuppressWarnings("null") @Override public String toString() { return null; } })); } @Test void testSafe() { Assertions.assertEquals("", Strings.safe(null)); Assertions.assertEquals(" ", Strings.safe(" ")); } @Test void testSafeTrim() { Assertions.assertEquals("", Strings.safeTrim(null)); Assertions.assertEquals("", Strings.safeTrim("")); Assertions.assertEquals("", Strings.safeTrim(" ")); Assertions.assertEquals("test", Strings.safeTrim("test")); } @Test void testTrim() { Assertions.assertEquals(null, Strings.trim(null)); Assertions.assertEquals("", Strings.trim("")); Assertions.assertEquals("", Strings.trim(" ")); Assertions.assertEquals("test", Strings.trim("test")); } @Test void testSplit() { Assertions.assertArrayEquals(new String[] { "l", "m=r" }, Strings.split("l=m=r", '=', false)); Assertions.assertArrayEquals(new String[] { "l", "m", "r" }, Strings.split("l=m=r", '=', true)); Assertions.assertArrayEquals(new String[] { "l" }, Strings.split("l", '=', true)); Assertions.assertArrayEquals(new String[] { "", "l" }, Strings.split("=l", '=', true)); Assertions.assertArrayEquals(new String[] { "l", "" }, Strings.split("l=", '=', true)); } @Test void testJoin() { final String[] strings = new String[] { "one", "two", "three" }; Assertions.assertEquals("one, two, three", Strings.join(strings, ", ")); Assertions.assertEquals("", Strings.join(strings, ", ", 0)); Assertions.assertEquals(Strings.ELLIPSIS, Strings.join(strings, ", ", Strings.ELLIPSIS.length())); Assertions.assertEquals("one, two, t...", Strings.join(strings, ", ", 14, "...")); } @Test void testEncodeDecode() { String decoded = "\\\0\u08af\b\t\n\f\ra\""; String encoded = "\\\\\\0\\u08AF\\b\\t\\n\\f\\ra\\\""; Assertions.assertEquals(encoded, Strings.encode(decoded)); Assertions.assertEquals(decoded, Strings.decode(encoded)); } @Test void testDecodeFailure() { Assertions.assertThrows(IllegalArgumentException.class, () -> { Strings.decode("\\?"); }); Assertions.assertThrows(IllegalArgumentException.class, () -> { Strings.decode("\\uXXXXXx"); }); } @Test void testEncodeHtml() { String decoded = "<script>'alert(\"&\\test\")';\n</script>"; String encoded = "&lt;script&gt;&apos;alert(&quot;&amp;\\test&quot;)&apos;;&#10;&lt;/script&gt;"; Assertions.assertEquals(encoded, Strings.encodeHtml(decoded)); } }
gpl-3.0
kremi151/MinaMod
src/main/java/lu/kremi151/minamod/item/ItemAmulet.java
3585
package lu.kremi151.minamod.item; import java.util.List; import javax.annotation.Nullable; import lu.kremi151.minamod.MinaCreativeTabs; import lu.kremi151.minamod.MinaItems; import lu.kremi151.minamod.capabilities.amulets.IAmulet; import lu.kremi151.minamod.capabilities.amulets.ItemAmuletCapabilityProvider; import lu.kremi151.minamod.capabilities.amulets.impl.AmuletEnder; import lu.kremi151.minamod.capabilities.amulets.impl.AmuletExperience; import lu.kremi151.minamod.capabilities.amulets.impl.AmuletHarmony; import lu.kremi151.minamod.capabilities.amulets.impl.AmuletPotionEffect; import lu.kremi151.minamod.capabilities.amulets.impl.AmuletReturn; import lu.kremi151.minamod.interfaces.ISyncCapabilitiesToClient; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.MobEffects; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class ItemAmulet extends Item{ public ItemAmulet(){ this.setCreativeTab(MinaCreativeTabs.AMULETS); this.setMaxStackSize(1); } @Override public net.minecraftforge.common.capabilities.ICapabilityProvider initCapabilities(ItemStack stack, @Nullable NBTTagCompound nbt) { final IAmulet cap; if(stack.getItem() == MinaItems.AMULET_OF_EXPERIENCE) { cap = new AmuletExperience(); }else if(stack.getItem() == MinaItems.AMULET_OF_RETURN) { cap = new AmuletReturn(); }else if(stack.getItem() == MinaItems.AMULET_OF_REGENERATION) { cap = new AmuletPotionEffect(stack, MobEffects.REGENERATION, 200); }else if(stack.getItem() == MinaItems.AMULET_OF_MERMAID) { cap = new AmuletPotionEffect(stack, MobEffects.WATER_BREATHING, 200); }else if(stack.getItem() == MinaItems.AMULET_OF_HARMONY) { cap = new AmuletHarmony(); }else { cap = new AmuletEnder(stack); } return new ItemAmuletCapabilityProvider(cap); } protected IAmulet getAmulet(ItemStack stack) { return stack.getCapability(IAmulet.CAPABILITY, null); } @SideOnly(Side.CLIENT) @Override public boolean hasEffect(ItemStack stack){ IAmulet amulet = getAmulet(stack); return amulet != null && amulet.hasEffect(); } @Override public boolean showDurabilityBar(ItemStack stack) { IAmulet amulet = getAmulet(stack); return amulet != null && amulet.hasDurability(); } @Override public double getDurabilityForDisplay(ItemStack stack) { IAmulet amulet = getAmulet(stack); return (amulet != null && amulet.hasDurability()) ? amulet.getDurability() : super.getDurabilityForDisplay(stack); } @Override public void addInformation(ItemStack stack, EntityPlayer player, List<String> tooltip, boolean advanced) { IAmulet amulet = getAmulet(stack); if(amulet != null)amulet.addInformation(player, tooltip, advanced); } public static class Syncable extends ItemAmulet implements ISyncCapabilitiesToClient{ @Override public NBTTagCompound writeSyncableData(ItemStack stack, NBTTagCompound nbt) { IAmulet amulet = getAmulet(stack); if(amulet != null) { return amulet.saveSyncData(nbt); }else { return nbt; } } @Override public void readSyncableData(ItemStack stack, NBTTagCompound nbt) { IAmulet amulet = getAmulet(stack); if(amulet != null)amulet.loadSyncData(nbt); } } }
gpl-3.0
Hainish/Swinedroid
src/com/legind/sqlite/DbAdapter.java
4818
package com.legind.sqlite; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DbAdapter { public static final String KEY_ROWID = "_id"; private DatabaseHelper mDbHelper; protected SQLiteDatabase mDb; private static final String TAG = "DbAdapter"; private static final String DATABASE_NAME = "data"; private static final int DATABASE_VERSION = 14; private String dbTable; private String[] fieldsString; static final String HEXES = "0123456789ABCDEF"; /** * Database creation sql statement */ private static final String[] DATABASE_CREATE_STATEMENTS = { "create table alerts (_id integer primary key autoincrement, sid int not null, cid int not null, ip_src blob not null, ip_dst blob not null, sig_priority smallint not null, sig_name varchar not null, timestamp varchar(19) not null);", "create table servers (_id integer primary key autoincrement, host varchar not null, port int not null, username varchar not null, password varchar not null, md5 varchar, sha1 varchar);" }; private static final String[] DATABASE_UPGRADE_STATEMENTS = { "DROP TABLE IF EXISTS alerts;", DATABASE_CREATE_STATEMENTS[0] }; private final Context mCtx; private class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { for(String dbCreateStatement : DATABASE_CREATE_STATEMENTS) db.execSQL(dbCreateStatement); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion); for(String dbUpgradeStatement : DATABASE_UPGRADE_STATEMENTS) db.execSQL(dbUpgradeStatement); } } /** * Constructor - takes the context to allow the database to be * opened/created * * @param ctx the Context within which to work * @param databaseVersion the version of the child table * @param databaseCreate the create statement * @param databaseTable the table of the child */ public DbAdapter(Context ctx, String dbTableLocal, String[] fieldsStringLocal) { dbTable = dbTableLocal; fieldsString = fieldsStringLocal; mCtx = ctx; } /** * Open the database. If it cannot be opened, try to create a new * instance of the database. If it cannot be created, throw an exception to * signal the failure * * @return this (self reference, allowing this to be chained in an * initialization call) * @throws SQLException if the database could be neither opened or created */ public DbAdapter open() throws SQLException { mDbHelper = new DatabaseHelper(mCtx); mDb = mDbHelper.getWritableDatabase(); return this; } public void close() { mDbHelper.close(); } /** * Delete the row with the given rowId * * @param rowId id of row to delete * @return true if deleted, false otherwise */ public boolean delete(long rowId) { return mDb.delete(dbTable, KEY_ROWID + "=" + rowId, null) > 0; } /** * Delete all rows in table * * @return true if deleted, false otherwise */ public boolean deleteAll() { return mDb.delete(dbTable, null, null) > 0; } /** * Return a Cursor over the list of all rows in the table * * @return Cursor over all alerts */ public Cursor fetchAll() { String[] fieldsWithRow = new String[fieldsString.length+1]; fieldsWithRow[0] = KEY_ROWID; System.arraycopy(fieldsString, 0, fieldsWithRow, 1, fieldsString.length); return mDb.query(dbTable, fieldsWithRow, null, null, null, null, null); } /** * Return a Cursor positioned at the row that matches the given rowId * * @param rowId id of alert to retrieve * @return Cursor positioned to matching row, if found * @throws SQLException if row could not be found/retrieved */ public Cursor fetch(long rowId) throws SQLException { String[] fieldsWithRow = new String[fieldsString.length+1]; fieldsWithRow[0] = KEY_ROWID; System.arraycopy(fieldsString, 0, fieldsWithRow, 1, fieldsString.length); Cursor mCursor = mDb.query(true, dbTable, fieldsWithRow, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } public static String getHex( byte [] raw ) { if ( raw == null ) { return null; } final StringBuilder hex = new StringBuilder( 2 * raw.length ); for ( final byte b : raw ) { hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F))); } return hex.toString(); } }
gpl-3.0
ThiagoGarciaAlves/ForestryMC
src/main/java/forestry/arboriculture/gadgets/TileArboristChest.java
1004
/******************************************************************************* * Copyright (c) 2011-2014 SirSengir. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0.txt * * Various Contributors including, but not limited to: * SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges ******************************************************************************/ package forestry.arboriculture.gadgets; import forestry.api.genetics.AlleleManager; import forestry.arboriculture.genetics.TreeHelper; import forestry.core.gadgets.TileNaturalistChest; import forestry.core.network.GuiId; public class TileArboristChest extends TileNaturalistChest { public TileArboristChest() { super(AlleleManager.alleleRegistry.getSpeciesRoot(TreeHelper.UID), GuiId.ArboristChestGUI.ordinal()); } }
gpl-3.0
slavidlancer/JavaSEtraining
Exercising/src/com/jse/tutorials/design_patterns/structural/proxy/ProxyImage.java
457
package com.jse.tutorials.design_patterns.structural.proxy; public class ProxyImage implements Image { private RealImage realImage; private String fileName; public ProxyImage(String fileName) { this.fileName = fileName; } @Override public void display() { if (this.realImage == null) { this.realImage = new RealImage(this.fileName); } this.realImage.display(); } }
gpl-3.0
Doctusoft/dsweb
dsweb/src/main/java/com/doctusoft/dsw/client/comp/Repeat.java
2274
package com.doctusoft.dsw.client.comp; /* * #%L * dsweb * %% * Copyright (C) 2014 Doctusoft Ltd. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import java.util.List; import lombok.Getter; import lombok.Setter; import com.doctusoft.ObservableProperty; import com.doctusoft.bean.binding.Bindings; import com.doctusoft.bean.binding.ValueBinding; import com.doctusoft.bean.binding.observable.ListBindingListener; import com.doctusoft.bean.binding.observable.ObservableList; import com.doctusoft.bean.binding.observable.ObservableValueBinding; import com.doctusoft.dsw.client.comp.model.ContainerModel; public abstract class Repeat<T> extends BaseComponent<Repeat<T>, ContainerModel> { @ObservableProperty @Getter @Setter private ObservableList<T> items = new ObservableList<T>(); public Repeat() { super(new ContainerModel()); new ListBindingListener<T>((ObservableValueBinding) Bindings.obs(this).get(Repeat_._items)) { @Override public void inserted(ObservableList<T> list, int index, T element) { HasComponentModel newRow = renderItem(element, index); model.getChildren().add(index, newRow.getComponentModel()); } @Override public void removed(ObservableList<T> list, int index, T element) { model.getChildren().remove(index); } }; } protected abstract HasComponentModel renderItem(T item, int rowNum); /** * If an observablelist is bound, it's insert and remove events will also propagate */ public Repeat<T> bind(ValueBinding<? extends List<T>> valueBinding) { Bindings.bind(valueBinding, (ValueBinding) Bindings.on(this).get(Repeat_._items)); return this; } }
gpl-3.0
Megalunchbox/2DGameProject
src/gfx/Display/Render.java
1269
package gfx.Display; import gfx.Assets.Assets; import gfx.ImageManager.SpriteSheet; import java.awt.Graphics; import java.awt.*; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; /* This class is not currently implemented! I plan it to be a separate class instead of the render method containing a bunch of code that makes it kinda hard to navigate so. */ public class Render { private CanvasLoader displayer = new CanvasLoader(); private BufferStrategy bs; private Graphics g; private BufferedImage testImage; private BufferedImage testImage2; private SpriteSheet sheet; int test1; int test2; public void Render () { final int width = displayer.getWidth(); final int height = displayer.getHeight();; bs = displayer.getCanvas().getBufferStrategy(); if (bs == null){ displayer.getCanvas().createBufferStrategy(3); return; } g = bs.getDrawGraphics(); g.setColor(Color.red); g.drawImage(Assets.image1, 20, 20 , null); // if (test1 != width/10) { // g.fillRect(test1 * 10, height / 2, 10, 10); // test1++; // } bs.show(); g.dispose(); } }
gpl-3.0
alejandrocq/HeartRateTest
mobile/src/androidTest/java/com/alejandro_castilla/heartratetest/ApplicationTest.java
367
package com.alejandro_castilla.heartratetest; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
gpl-3.0
Antiquum/Crimson
src/com/subterranean_security/crimson/client/stage1/Stage1.java
1144
package com.subterranean_security.crimson.client.stage1; import javax.net.ssl.SSLException; import com.subterranean_security.crimson.client.stage1.network.ClientConnector; import com.subterranean_security.crimson.core.proto.container.Containers.NetworkTarget; import com.subterranean_security.crimson.internal.InternalConfig; public class Stage1 { public static ClientConnector connector; public static InternalConfig ic; private int connectionIterations = 0; public static void main(String[] args) { // Establish the custom fallback exception handler Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler()); // Establish the custom shutdown hook Runtime.getRuntime().addShutdownHook(new ShutdownHook()); if (!Libraries.uptodate()) { connectionRoutine(); Libraries.update(); } connectionRoutine(); } public static void connectionRoutine() { for (NetworkTarget nt : ic.getTargets()) { try { connector = new ClientConnector(nt.getServer(), nt.getPort()); } catch (SSLException | InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
gpl-3.0
sdp0et/barsuift-simlife
simLifeCoreAPI/src/main/java/barsuift/simLife/environment/SunState.java
2336
/** * barsuift-simlife is a life simulator program * * Copyright (C) 2010 Cyrille GACHOT * * This file is part of barsuift-simlife. * * barsuift-simlife is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * barsuift-simlife 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 General Public License for more * details. * * You should have received a copy of the GNU General Public License along with barsuift-simlife. If not, see * <http://www.gnu.org/licenses/>. */ package barsuift.simLife.environment; import javax.xml.bind.annotation.XmlRootElement; import barsuift.simLife.State; import barsuift.simLife.j3d.environment.Sun3DState; @XmlRootElement public class SunState implements State { private Sun3DState sun3DState; public SunState() { super(); this.sun3DState = new Sun3DState(); } public SunState(Sun3DState sun3DState) { super(); this.sun3DState = sun3DState; } public Sun3DState getSun3DState() { return sun3DState; } public void setSun3DState(Sun3DState sun3dState) { sun3DState = sun3dState; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((sun3DState == null) ? 0 : sun3DState.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SunState other = (SunState) obj; if (sun3DState == null) { if (other.sun3DState != null) return false; } else if (!sun3DState.equals(other.sun3DState)) return false; return true; } @Override public String toString() { return "SunState [sun3DState=" + sun3DState + "]"; } }
gpl-3.0
shuichi/MediaMatrix
src/main/java/mediamatrix/gui/ImageSelection.java
1132
package mediamatrix.gui; import java.awt.Image; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; public class ImageSelection implements Transferable, ClipboardOwner { protected Image data; public ImageSelection(Image image) { this.data = image; } @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[]{DataFlavor.imageFlavor}; } @Override public boolean isDataFlavorSupported(DataFlavor flavor) { return DataFlavor.imageFlavor.equals(flavor); } @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (DataFlavor.imageFlavor.equals(flavor)) { return data; } throw new UnsupportedFlavorException(flavor); } @Override public void lostOwnership(Clipboard clipboard, Transferable contents) { this.data = null; } }
gpl-3.0
kilowog2814/TCC-Java
JavaSql/samples/alwaysencrypted/AlwaysEncrypted.java
5750
/*===================================================================== File: AlwaysEncrypted.java Summary: This Microsoft JDBC Driver for SQL Server sample application demonstrates how to create Column Master Key and Column Encryption Key for use with the Java Key Store for Always Encrypted feature. --------------------------------------------------------------------- This file is part of the Microsoft JDBC Driver for SQL Server Code Samples. Copyright (C) Microsoft Corporation. All rights reserved. This source code is intended only as a supplement to Microsoft Development Tools and/or on-line documentation. See these other materials for detailed information regarding Microsoft code samples. THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. =====================================================================*/ import java.sql.*; import javax.xml.bind.DatatypeConverter; import com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionJavaKeyStoreProvider; import com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionKeyStoreProvider; import com.microsoft.sqlserver.jdbc.SQLServerException; /** * This program demonstrates how to create Column Master Key (CMK) and Column Encryption Key (CEK) * CMK is created first and then it is used to create CEK */ public class AlwaysEncrypted { // Alias of the key stored in the keystore. private static String keyAlias = "<proide key alias>"; // Name by which the column master key will be known in the database. private static String columnMasterKeyName = "JDBC_CMK"; // Name by which the column encryption key will be known in the database. private static String columnEncryptionKey = "JDBC_CEK"; // The location of the keystore. private static String keyStoreLocation = "C:\\Dev\\Always Encrypted\\keystore.jks"; // The password of the keystore and the key. private static char[] keyStoreSecret = "********".toCharArray(); /** * Name of the encryption algorithm used to encrypt the value of * the column encryption key. The algorithm for the system providers must be RSA_OAEP. */ private static String algorithm = "RSA_OAEP"; public static void main(String[] args) { String connectionString = GetConnectionString(); try { // Note: if you are not using try-with-resources statements (as here), // you must remember to call close() on any Connection, Statement, // ResultSet objects that you create. // Open a connection to the database. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); try (Connection sourceConnection = DriverManager.getConnection(connectionString)) { // Instantiate the Java Key Store provider. SQLServerColumnEncryptionKeyStoreProvider storeProvider = new SQLServerColumnEncryptionJavaKeyStoreProvider( keyStoreLocation, keyStoreSecret); /** * Create column mater key * For details on syntax refer: * https://msdn.microsoft.com/library/mt146393.aspx * */ String createCMKSQL = "CREATE COLUMN MASTER KEY " + columnMasterKeyName + " WITH ( " + " KEY_STORE_PROVIDER_NAME = '" + storeProvider.getName() + "' , KEY_PATH = '" + keyAlias + "' ) "; try (Statement cmkStatement = sourceConnection.createStatement()) { cmkStatement.executeUpdate(createCMKSQL); System.out.println("Column Master Key created with name : " + columnMasterKeyName); } byte [] encryptedCEK=getEncryptedCEK(storeProvider); /** * Create column encryption key * For more details on the syntax refer: * https://msdn.microsoft.com/library/mt146372.aspx * Encrypted CEK first needs to be converted into varbinary_literal from bytes, * for which DatatypeConverter.printHexBinary is used */ String createCEKSQL = "CREATE COLUMN ENCRYPTION KEY " + columnEncryptionKey + " WITH VALUES ( " + " COLUMN_MASTER_KEY = " + columnMasterKeyName + " , ALGORITHM = '" + algorithm + "' , ENCRYPTED_VALUE = 0x" + DatatypeConverter.printHexBinary(encryptedCEK) + " ) "; try (Statement cekStatement = sourceConnection.createStatement()) { cekStatement.executeUpdate(createCEKSQL); System.out.println("CEK created with name : " + columnEncryptionKey); } } } catch (Exception e) { // Handle any errors that may have occurred. e.printStackTrace(); } } // To avoid storing the sourceConnection String in your code, // you can retrieve it from a configuration file. private static String GetConnectionString() { // Create a variable for the connection string. String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=ae;user=sa;password=********;"; return connectionUrl; } private static byte[] getEncryptedCEK(SQLServerColumnEncryptionKeyStoreProvider storeProvider) throws SQLServerException { /** * Following arguments needed by SQLServerColumnEncryptionJavaKeyStoreProvider * 1) keyStoreLocation : * Path where keystore is located, including the keystore file name. * 2) keyStoreSecret : * Password of the keystore and the key. */ String plainTextKey = "You need to give your plain text"; // plainTextKey has to be 32 bytes with current algorithm supported byte[] plainCEK = plainTextKey.getBytes(); // This will give us encrypted column encryption key in bytes byte[] encryptedCEK = storeProvider.encryptColumnEncryptionKey( keyAlias, algorithm, plainCEK); return encryptedCEK; } }
gpl-3.0
ustits/ColleagueBot
core/src/main/java/ru/ustits/colleague/repositories/records/RepeatRecord.java
797
package ru.ustits.colleague.repositories.records; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.Value; import javax.persistence.*; /** * @author ustits */ @Entity @Table(name = "repeats") @Value @AllArgsConstructor @NoArgsConstructor(access = AccessLevel.PRIVATE, force = true) public final class RepeatRecord { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String message; private String cron; @Column(name = "chat_id") private Long chatId; @Column(name = "user_id") private Long userId; public RepeatRecord(final String message, final String cron, final Long chatId, final Long userId) { this(null, message, cron, chatId, userId); } }
gpl-3.0
Dirdle/Feverfew
src/feverfew/StopPoint.java
8762
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package feverfew; /** * * @author Oscar * * This class represents a stop point on an action bar. It's just a way of * keeping track of things; all of the fields could be moved to ActBar, probably * */ // TODO figure out how to 'display' the scoring. import java.awt.geom.Rectangle2D; public class StopPoint extends Scaffold implements Testing { // TODO fix width to depend on stopcount, removing possible overlap private final static double DEFWIDTH = 0.1; private final static double MINRATIO = 0.2; // This scales how the minimum score grows with the difficulty private final static double WIDTHRATIO = 0.001; private final static double MAXWIDTH = 0.2; // These define the maximum width and how it scales down with increasing // difficulty. private final static double STDEVMAX = 0.01; private final static double STDEV_EXPCO = 110; private final static double STDEV_POW = 1.1; private final static double STDEV_REDCO = 0.0000625; // Numbers that control the scaling of the gaussian's standard deviation // given values can be tested using the spreadsheet private Rectangle2D displaybox; private double boxlength; private double boxwidth; public double location; // Location on bar as proportion of bar's length public double length; // The total width of the scoring region, as proportion of bar's length public double scoreFlatness; // A higher value here gives the gaussians used for calculating score a // Larger standard deviation, which makes them flatter public double minscore; // The minimum score as a proportion of the maximum score // Calculated from other values public double lowerBound, upperBound; // The proportionate positions of the edges of the stop point's scoring zone public String type; /** Describes the stop point; usual value will be 'norm' * Other values: * flat: either success or failure, no variation within, case 1000 * soon: highest value at start of scoring region, case 999 * late: highest value at end of scoring region, case 1001 */ public StopPoint(double position, double difficulty){ // Typical creation of a stop point at a given location with a given // level of difficulty. // The difficulty will usually be a number between 0 and 99 // However some other numbers give 'special case' difficulty this.location = position; if (difficulty == 1000){ type = "flat"; this.scoreFlatness = Double.POSITIVE_INFINITY; // Can actually construct a flat line using the usual gaussian fn :D this.minscore = StopPoint.MAXSCORE; this.length = StopPoint.DEFWIDTH; } else if (difficulty == 999){ // TODO soon difficulty } else if (difficulty == 1001){ // TODO late difficulty } else { assert 0 <= difficulty; assert 99 >= difficulty; // Stop if given a bad difficulty // TODO proper error-catching code instead this.type = "norm"; this.length = StopPoint.MAXWIDTH - StopPoint.WIDTHRATIO * difficulty; // Linear decrease in width with difficulty this.scoreFlatness = this.stdev(difficulty); // Square root decrease in std dev with difficulty this.minscore = (difficulty/99.0) * StopPoint.MINRATIO * StopPoint.MAXSCORE; // Linear *increase* in minimum score with difficulty // This is because otherwise the width becomes the same as the stdev } this.lowerBound = (this.location - (this.length/2.0)); this.upperBound = (this.location + (this.length/2.0)); LOGGER.log("Stop point created at " + Double.toString(this.location) + ". Set stop point width to " + Double.toString(length) + ". Stop point begins at " + Double.toString(lowerBound) + ". Stop point ends at " + Double.toString(upperBound)); //TODO display rectangle initialisation boxlength = BOARD_HEIGHT * PROPORTIONY * this.length; boxwidth = STOPMARKWIDTH; this.setY((int) (BOARD_HEIGHT * (0.5 + PROPORTIONY * (this.location - 0.5)) - Math.floor(boxlength/2.0))); this.setX((int) (BOARD_WIDTH * PROPORTIONX - Math.floor(boxwidth/2.0))); // This formula gives the absolute location of the stop point on the // y-axis. The x-axis location is trivial LOGGER.log("Determined absolute location of stop point: " + Double.toString(y)); displaybox = new Rectangle2D.Double(0, 0, boxwidth, boxlength); this.setShape(displaybox); this.setFill(true); this.setStroke(false); this.setFillColor(STOPMARKCOLOR); } /** * * @param target * * Unfinished/Nonfunctional at present. No known use. */ public void becomePoint(StopPoint target){ this.location = target.location; this.length = target.length; this.scoreFlatness = target.scoreFlatness; this.minscore = target.minscore; } public double score(double hitLocation){ // Returns the score based on the (proportionate) location of the // hit location within the stop point. double score; switch (this.type) { case "norm": LOGGER.log("Calculating score as gaussian with" + " prefactor: " + Double.toString(StopPoint.MAXSCORE) + ", centre: " + Double.toString(this.location) + ", StdDev: " + Double.toHexString(this.scoreFlatness) + ", location " + Double.toString(hitLocation)); score = this.gauss(StopPoint.MAXSCORE, this.location, this.scoreFlatness, hitLocation); // Normal gaussian scoring break; case "flat": score = StopPoint.MAXSCORE; // flat scoring could be replaced with a gaussian with infinite // standard deviation break; case "soon": // TODO soon difficulty score = -10; break; case "late": score = -10; break; default: score = -20; break; } return score; } public final void move(double position){ // Moves this stop point to the given position this.location = position; } public double getLoc(){ // Returns the location of the stop point return this.location; } public double getWid(){ // Returns the width of the stop point return this.length; } public double getMin(){ // Returns the minimum score of the stop point return this.minscore; } public double getSpread(){ // Returns the standard deviation/score flatness of the stop point return this.scoreFlatness; } public Rectangle2D getBox(){ return this.displaybox; } private double gauss(double height, double center, double stddev, double x){ // returns the value at x of a gaussian function with height, center and // standard deviation double expon = -1.0*(Math.pow((x - center), 2.0))/(2.0*stddev); return height*(Math.pow(Math.E, expon)); } private double stdev(double difficulty){ double exponent = ((99.0 - difficulty)/STDEV_EXPCO); double lincomp = STDEV_REDCO*Math.pow((difficulty + 1.0), STDEV_POW); return STDEVMAX - lincomp * Math.pow(Math.E, exponent); } public double getBoxlength() { return boxlength; } public void setBoxlength(double boxlength) { this.boxlength = boxlength; } }
gpl-3.0
Godfather95/SystemdRemote
src/main/java/de/delumiti/thieme/systemdremote/Tools/Service.java
2273
package de.delumiti.thieme.systemdremote.Tools; /** * Created by denni on 15.04.2016. */ public class Service { private String name; private String state; private String active; private String running; private String description; public Service(String name, String state, String active, String running, String description) { this.name = name; this.state = state; this.active = active; this.running = running; this.description = description; } public Service(String name, String state) { this.name = name; this.state = state; this.active = ""; this.running = ""; this.description = ""; } /** * Gets description. * * @return Value of description. */ public String getDescription() { return description; } /** * Sets new description. * * @param description New value of description. */ public void setDescription(String description) { this.description = description; } /** * Gets state. * * @return Value of state. */ public String getState() { return state; } /** * Sets new running. * * @param running New value of running. */ public void setRunning(String running) { this.running = running; } /** * Gets name. * * @return Value of name. */ public String getName() { return name; } /** * Gets running. * * @return Value of running. */ public String getRunning() { return running; } /** * Sets new active. * * @param active New value of active. */ public void setActive(String active) { this.active = active; } /** * Sets new state. * * @param state New value of state. */ public void setState(String state) { this.state = state; } /** * Sets new name. * * @param name New value of name. */ public void setName(String name) { this.name = name; } /** * Gets active. * * @return Value of active. */ public String getActive() { return active; } }
gpl-3.0
overlinden/Xardas
XardasComputerbase/src/de/wpsverlinden/xardas/plugins/computerbase/ComputerBase.java
2187
/* * Xardas - A Home Automation System * Copyright (C) 2012 Oliver Verlinden (http://wps-verlinden.de) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.wpsverlinden.xardas.plugins.computerbase; import java.util.HashMap; import java.util.Timer; import javax.swing.JPanel; import de.wpsverlinden.xardas.pluginsystem.IPlugable; import de.wpsverlinden.xardas.pluginsystem.IPluginController; public class ComputerBase implements IPlugable { IPluginController controller; Timer updatetimer; HashMap<String, String> settings; JPanel panel; @Override public String getName() { return "ComputerBase"; } @Override public String getVersion() { return "1.0"; } @Override public String getDescription() { return "Informs about the current computerbase news"; } @Override public void setPluginManager(IPluginController manager) { this.controller = manager; } @Override public void start() { settings = controller.loadData(); if (settings.get("REFRESH_INTERVAL") == null || settings.get("RSS_URL") == null) { controller.log("Error", "Error parsing setting file"); return; } int refreshInterval = Integer.parseInt(settings.get("REFRESH_INTERVAL")); String newsLocation = settings.get("RSS_URL"); updatetimer = new Timer(); updatetimer.schedule( new NewsUpdater(controller, newsLocation), 0, refreshInterval * 60 * 1000); } @Override public void stop() { if (updatetimer != null) { updatetimer.cancel(); updatetimer.purge(); } } @Override public boolean hasGui() { return true; } }
gpl-3.0
LeqxLeqx/jllegro
Java/src/allegro/display/ImageMode.java
156
package allegro.display; /** * Created by LeqxLeqx on 10/25/16. */ public enum ImageMode { CENTERED, LEFT_ALIGNED, RIGHT_ALIGNED, ; }
gpl-3.0
imatesiu/ReaderBpmn
src/main/java/petrinet/analysis/SinkPlacesSet.java
455
package petrinet.analysis; import models.graphbased.directed.petrinet.elements.Place; public class SinkPlacesSet extends AbstractComponentSet<Place> { /** * */ private static final long serialVersionUID = -4054839887327904941L; public SinkPlacesSet() { super("Sink places"); } public boolean equals(Object o) { if (o instanceof SinkPlacesSet) { return (super.equals(o)); } else { return false; } } }
gpl-3.0
adofsauron/KEEL
src/keel/Algorithms/UnsupervisedLearning/AssociationRules/FuzzyRuleLearning/Alcalaetal/Alcalaetal.java
10679
/*********************************************************************** This file is part of KEEL-software, the Data Mining tool for regression, classification, clustering, pattern mining and so on. Copyright (C) 2004-2010 F. Herrera (herrera@decsai.ugr.es) L. Sánchez (luciano@uniovi.es) J. Alcalá-Fdez (jalcala@decsai.ugr.es) S. García (sglopez@ujaen.es) A. Fernández (alberto.fernandez@ujaen.es) J. Luengo (julianlm@decsai.ugr.es) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ **********************************************************************/ package keel.Algorithms.UnsupervisedLearning.AssociationRules.FuzzyRuleLearning.Alcalaetal; /** * <p> * @author Written by Alvaro Lopez * @version 1.1 * @since JDK1.6 * </p> */ import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import org.core.Randomize; import keel.Dataset.Attributes; public class Alcalaetal { /** * <p> * It gathers all the parameters, launches the algorithm, and prints out the results * </p> */ private myDataset trans; private String rulesFilename; private String valuesFilename; private String uniformFuzzyAttributesFilename; private String adjustedFuzzyAttributesFilename; private String geneticLearningLogFilename; private AlcalaetalProcess proc; private ArrayList<AssociationRule> associationRulesSet; private int nEvaluations; private int popSize; private int nBitsGene; private double phi; private double d; private int nFuzzyRegionsForNumericAttributes; private boolean useMaxForOneFrequentItemsets; private double minSupport; private double minConfidence; private boolean somethingWrong = false; //to check if everything is correct. /** * Default constructor */ public Alcalaetal() { } /** * It reads the data from the input files and parse all the parameters * from the parameters array. * @param parameters parseParameters It contains the input files, output files and parameters */ public Alcalaetal(parseParameters parameters) { this.rulesFilename = parameters.getAssociationRulesFile(); this.adjustedFuzzyAttributesFilename = parameters.getOutputFile(0); this.valuesFilename = parameters.getOutputFile(1); this.uniformFuzzyAttributesFilename = parameters.getOutputFile(2); this.geneticLearningLogFilename = parameters.getOutputFile(3); try { System.out.println("\nReading the transaction set: " + parameters.getTransactionsInputFile()); this.trans = new myDataset(); this.trans.readDataSet(parameters.getTransactionsInputFile()); } catch (IOException e) { System.err.println("There was a problem while reading the input transaction set: " + e); somethingWrong = true; } long seed = Long.parseLong(parameters.getParameter(0)); this.nEvaluations = Integer.parseInt(parameters.getParameter(1)); this.popSize = Integer.parseInt(parameters.getParameter(2)); this.nBitsGene = Integer.parseInt(parameters.getParameter(3)); this.phi = Double.parseDouble(parameters.getParameter(4)); this.d = Double.parseDouble(parameters.getParameter(5)); this.nFuzzyRegionsForNumericAttributes = Integer.parseInt(parameters.getParameter(6)); this.useMaxForOneFrequentItemsets = Boolean.parseBoolean(parameters.getParameter(7)); this.minSupport = Double.parseDouble(parameters.getParameter(8)); this.minConfidence = Double.parseDouble(parameters.getParameter(9)); Randomize.setSeed(seed); } /** * It launches the algorithm */ public void execute() { if (somethingWrong) { //We do not execute the program System.err.println("An error was found"); System.err.println("Aborting the program"); //We should not use the statement: System.exit(-1); } else { this.proc = new AlcalaetalProcess(this.trans, this.nEvaluations, this.popSize, this.nBitsGene, this.phi, this.d, this.nFuzzyRegionsForNumericAttributes, this.useMaxForOneFrequentItemsets, this.minSupport, this.minConfidence); this.proc.run(); this.associationRulesSet = this.proc.getRulesSet(); this.proc.printReport(this.associationRulesSet); /*for (int i=0; i < this.associationRulesSet.size(); i++) { System.out.println(this.associationRulesSet.get(i)); }*/ try { int r, i; AssociationRule ar; Itemset itemset; this.saveFuzzyAttributes(this.uniformFuzzyAttributesFilename, this.proc.getUniformFuzzyAttributes()); this.saveFuzzyAttributes(this.adjustedFuzzyAttributesFilename, this.proc.getAdjustedFuzzyAttributes()); this.saveGeneticLearningLog(this.geneticLearningLogFilename, this.proc.getGeneticLearningLog()); PrintWriter rules_writer = new PrintWriter(this.rulesFilename); PrintWriter values_writer = new PrintWriter(this.valuesFilename); rules_writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); rules_writer.println("<rules>"); values_writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); values_writer.print("<values "); values_writer.println("n_one_frequent_itemsets=\"" + this.proc.getNumberOfOneFrequentItemsets() + "\" n_rules=\"" + this.associationRulesSet.size() + "\">"); for (r=0; r < this.associationRulesSet.size(); r++) { ar = this.associationRulesSet.get(r); rules_writer.println("<rule id = \"" + r + "\" />"); values_writer.println("<rule id=\"" + r + "\" rule_support=\"" + ar.getRuleSupport() + "\" antecedent_support=\"" + ar.getAntecedentSupport() + "\" confidence=\"" + ar.getConfidence() + "\"/>"); rules_writer.println("<antecedents>"); itemset = ar.getAntecedent(); for (i=0; i < itemset.size(); i++) this.createRule(itemset.get(i), this.proc.getAdjustedFuzzyAttributes(), rules_writer); rules_writer.println("</antecedents>"); rules_writer.println("<consequents>"); itemset = ar.getConsequent(); for (i=0; i < itemset.size(); i++) this.createRule(itemset.get(i), this.proc.getAdjustedFuzzyAttributes(), rules_writer); rules_writer.println("</consequents>"); rules_writer.println("</rule>"); } rules_writer.println("</rules>"); values_writer.println("</values>"); rules_writer.close(); values_writer.close(); System.out.println("\nAlgorithm Finished"); } catch (FileNotFoundException e) { e.printStackTrace(); } } } private void createRule(Item item, ArrayList<FuzzyAttribute> fuzzy_attributes, PrintWriter w) { int attr; boolean stop; FuzzyAttribute fuzzy_attr; FuzzyRegion[] fuzzy_regions; attr = item.getIDAttribute(); if (this.trans.isNominal(attr)) { w.print("<attribute name = \"" + this.trans.getAttributeName(attr) + "\" value=\""); w.print( ""+ this.trans.getNominalValue(attr, item.getIDLabel())); } else { stop = false; fuzzy_attr = fuzzy_attributes.get(0); for (int i=0; i < fuzzy_attributes.size() && !stop; i++) { fuzzy_attr = fuzzy_attributes.get(i); if (fuzzy_attr.getIdAttr() == item.getIDAttribute()) stop = true; } fuzzy_regions = fuzzy_attr.getFuzzyRegions(); w.print("<attribute name = \"" + trans.getAttributeName( fuzzy_attr.getIdAttr() ) + "\" value = \""); w.print( fuzzy_regions[ item.getIDLabel() ].getLabel() ); } w.println("\" />"); } private void saveFuzzyAttributes(String fuzzy_attrs_fname, ArrayList<FuzzyAttribute> fuzzy_attributes) throws FileNotFoundException { int attr, region, id_attr; boolean stop; FuzzyRegion[] fuzzy_regions; FuzzyAttribute fuzzy_attr; PrintWriter fuzzy_attrs_writer = new PrintWriter(fuzzy_attrs_fname); fuzzy_attrs_writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); fuzzy_attrs_writer.println("<data_base>"); for (attr=0; attr < this.trans.getnVars(); attr++) { if (this.trans.isNominal(attr)) { fuzzy_attrs_writer.println("<attribute name = \"" + this.trans.getAttributeName(attr) + "\" nValues = \"" + this.trans.nValueNominal(attr) + "\" Type = \"" + this.trans.getAttributeTypeString(attr) + "\" >"); for (region=0; region < this.trans.nValueNominal(attr); region++) { fuzzy_attrs_writer.println("<value \"" + this.trans.getNominalValue(attr, region) + "\" />"); } } else { fuzzy_attrs_writer.println("<attribute name = \"" + this.trans.getAttributeName(attr) + "\" nValues = \"" + this.nFuzzyRegionsForNumericAttributes + "\" Type = \"" + this.trans.getAttributeTypeString(attr) + "\" >"); stop = false; fuzzy_attr = fuzzy_attributes.get(0); for (int i=0; i < fuzzy_attributes.size() && !stop; i++) { fuzzy_attr = fuzzy_attributes.get(i); if (fuzzy_attr.getIdAttr() == attr) stop = true; } fuzzy_regions = fuzzy_attr.getFuzzyRegions(); for (region=0; region < fuzzy_regions.length; region++) { fuzzy_attrs_writer.print("<value \"" + fuzzy_regions[region].getLabel() + "\" "); fuzzy_attrs_writer.print("\"" + fuzzy_regions[region].getX0() + "\" "); fuzzy_attrs_writer.print("\"" + fuzzy_regions[region].getX1() + "\" "); fuzzy_attrs_writer.println("\"" + fuzzy_regions[region].getX3() + "\" />"); } } fuzzy_attrs_writer.println("</attribute>"); } fuzzy_attrs_writer.println("</data_base>"); fuzzy_attrs_writer.close(); } private void saveGeneticLearningLog(String genetic_learning_log_fname, String xml_str) throws FileNotFoundException { PrintWriter genetic_learning_log_writer = new PrintWriter(genetic_learning_log_fname); genetic_learning_log_writer.println(xml_str); genetic_learning_log_writer.close(); } }
gpl-3.0
FabioZumbi12/UltimateChat
UltimateChat-Spigot/src/main/java/br/net/fabiozumbi12/UltimateChat/Bukkit/hooks/UCFactionsHookInterface.java
202
package br.net.fabiozumbi12.UltimateChat.Bukkit.hooks; import org.bukkit.entity.Player; public interface UCFactionsHookInterface { String formatFac(String text, Player sender, Object receiver); }
gpl-3.0
dburgmann/fbRecommender
lib/restfb-1.6.11/source/library/com/restfb/batch/BatchResponse.java
3330
/* * Copyright (c) 2010-2012 Mark Allen. * * 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.restfb.batch; import static java.util.Collections.unmodifiableList; import java.util.ArrayList; import java.util.List; import com.restfb.Facebook; import com.restfb.util.ReflectionUtils; /** * Encapsulates a discrete part of an entire <a * href="https://developers.facebook.com/docs/reference/api/batch/" * target="_blank">Facebook Batch API</a> response. * * @author <a href="http://restfb.com">Mark Allen</a> * @since 1.6.5 */ public class BatchResponse { @Facebook private Integer code; @Facebook private String body; @Facebook private List<BatchHeader> headers = new ArrayList<BatchHeader>(); /** * "Magic" no-argument constructor so we can reflectively make instances of * this class with DefaultJsonMapper, but normal client code cannot. */ protected BatchResponse() {} /** * Creates a batch response with the given HTTP response status code, headers, * and JSON body. * * @param code * HTTP status code. * @param headers * HTTP headers. * @param body * JSON body. */ public BatchResponse(Integer code, List<BatchHeader> headers, String body) { this.code = code; this.body = body; if (headers != null) this.headers.addAll(headers); } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return ReflectionUtils.hashCode(this); } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object that) { return ReflectionUtils.equals(this, that); } /** * @see java.lang.Object#toString() */ @Override public String toString() { return ReflectionUtils.toString(this); } /** * The HTTP status code for this response. * * @return The HTTP status code for this response. */ public Integer getCode() { return code; } /** * The HTTP response body JSON. * * @return The HTTP response body JSON. */ public String getBody() { return body; } /** * The HTTP response headers. * * @return The HTTP response headers. */ public List<BatchHeader> getHeaders() { return unmodifiableList(headers); } }
gpl-3.0
slavidlancer/JavaSEtraining
Exercising/src/com/jse/tutorials/data_structures/queue/QueueArray.java
1555
package com.jse.tutorials.data_structures.queue; import java.util.Arrays; import java.util.NoSuchElementException; public class QueueArray<T> implements Queue<T> { private T[] arr; private int total, first, next; @SuppressWarnings("unchecked") public QueueArray() { arr = (T[]) new Object[2]; } private void resize(int capacity) { @SuppressWarnings("unchecked") T[] tmp = (T[]) new Object[capacity]; int size = arr.length; for (int i = 0; i < total; i++) { tmp[i] = arr[(first + i) % size]; } arr = tmp; first = 0; next = total; } @Override public Queue<T> enqueue(T element) { int size = arr.length; if (size == total) { resize(size * 2); } arr[next++] = element; if (next == size) { next = 0; } total++; return this; } @Override public T dequeue() { int size = arr.length; if (total == 0) { throw new NoSuchElementException(); } T element = arr[first]; arr[first] = null; if (++first == size) { first = 0; } if ((--total > 0) && (total == (size / 4))) { resize(size / 2); } return element; } @Override public String toString() { return Arrays.toString(arr); } }
gpl-3.0
Gawdl3y/task-timer-legacy
android/TaskTimer/src/main/java/com/gawdl3y/android/actionablelistview/ActionItem.java
1235
package com.gawdl3y.android.actionablelistview; /** * Stores all information needed to create a {@code MenuItem} for the {@code ActionMode} started by an {@code ActionableListView} * @author Schuyler Cebulskie */ public class ActionItem { private int mActionType = -1; private int mPosition; private int mIconResource; private int mTitleResource; public ActionItem(int actionType, int position, int iconRes, int titleRes) { mActionType = actionType; mPosition = position; mIconResource = iconRes; mTitleResource = titleRes; } public int getActionType() { return mActionType; } public void setActionType(int actionType) { mActionType = actionType; } public int getPosition() { return mPosition; } public void setPosition(int position) { mPosition = position; } public int getIconResource() { return mIconResource; } public void setIconResource(int iconResource) { mIconResource = iconResource; } public int getTitleResource() { return mTitleResource; } public void setTitleResource(int titleResource) { mTitleResource = titleResource; } }
gpl-3.0
comick/mini-gnutella
src/it/unipi/di/cli/comignan/lpr08/servent/Message.java
4071
/* This file is part of Mini-Gnutella. * Copyright (C) 2010 Michele Comignano * * Foobar is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Foobar 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Foobar. If not, see <http://www.gnu.org/licenses/>. */ package it.unipi.di.cli.comignan.lpr08.servent; import java.io.Serializable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Random; /** * Il generico messaggio con le caratteristiche comuni a tutti i messaggi. * Ogni messaggio estende questa classe. * @author Michele Comignano */ public abstract class Message implements Serializable { /** * Generatore di numeri casuali per la generazione degli identificatori. */ private static Random random = new Random(); /** * Il massimo numero di inoltri per un nuovo messaggio. */ public static final byte DEFAULT_TTL = 7; /** * Il numero di bytes che compongono l'identificatore univoco. */ private static final int ID_LENGTH = 16; /** * Un valore che identifica univocamente il messaggio all'interno della rete * Gnutella anche dopo inoltri successivi. */ protected byte[] messageId; /** * Identifica i tipo di messaggio (ping, pong, ...). */ protected byte messageType; /** * Il numero di volte che il messaggio può ancora essere inoltrato. */ private byte ttl; /** * Costruisce un nuovo messaggio del tipo dato. * @param messageType il tipo del messaggio. */ protected Message(byte messageType) { messageId = new byte[ID_LENGTH]; random.nextBytes(messageId); try { messageId = MessageDigest.getInstance("SHA-256").digest(messageId); } catch (NoSuchAlgorithmException e) { } this.messageType = messageType; this.ttl = DEFAULT_TTL; } /** * Crea un nuovo messaggio di tipo dato che sarà identificato dall'id fornito. * Utile quando si riceve un messaggio di ping e si crea un messaggio di pong * che dovendo seguire la rotta inversa, deve avere stesso identificatore. * @param messageId l'identificatore univoco. * @param messageType il tipo del messaggio. */ protected Message(byte[] messageId, byte messageType) { this(messageType); this.messageId = messageId; } /** * Prepara il messaggio ad essere inoltrato decrementando il ttl e lanciando * un opportuna eccezione de il messaggio non può più essere inoltrato. * @throws DeadMessageException se il messaggio non è più inoltrabile. */ protected void prepareForward() throws DeadMessageException { if (ttl-- <= 0) { throw new DeadMessageException(); } } /** * Ricava un intero dall'id univoco del messaggio. Nella messaggi di tipo diverso possono * avere lo stesso id, ad esempio uno di ping e il rispettivo messaggio di pong. In entrambi * i casi sarà restituito lo stesso valore e questo è utile perchè questi messaggi sono * usati come chiavi di tabelle hash contenenti le connessioni di destinazione o * provenienza. * @return */ @Override public int hashCode() { int ret = 0; for (int i = 0; i < messageId.length; i++) { ret += messageId[i]; } return ret; } /** * Segenedo l'idea della hashCode due messaggi anche di tipo diverso risulteranno uguali * se hanno lo stesso identificatore univoco. * @param obj * @return */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof Message)) { return false; } return ((Message) obj).hashCode() == hashCode(); } }
gpl-3.0
abmindiarepomanager/ABMOpenMainet
Mainet1.1/MainetServiceParent/MainetServiceCommon/src/main/java/com/abm/mainet/cfc/checklist/dto/ChecklistMst.java
2708
package com.abm.mainet.cfc.checklist.dto; import java.io.Serializable; import java.util.Date; /** * @author hiren.poriya * */ public class ChecklistMst implements Serializable { private static final long serialVersionUID = 1132522826774168076L; private Long clId; private Long orgid; private Long smServiceId; private String docGroup; private String clStatus; private Long updatedBy; private Date updatedDate; private Long createdBy; private Date createdDate; private Long hiddenServiceId; private String lgIpMac; private String lgIpMacUpd; public String getLgIpMac() { return lgIpMac; } public void setLgIpMac(final String lgIpMac) { this.lgIpMac = lgIpMac; } public String getLgIpMacUpd() { return lgIpMacUpd; } public void setLgIpMacUpd(final String lgIpMacUpd) { this.lgIpMacUpd = lgIpMacUpd; } public Long getClId() { return clId; } public Long getOrgid() { return orgid; } public Long getSmServiceId() { return smServiceId; } public String getDocGroup() { return docGroup; } public String getClStatus() { return clStatus; } public Long getUpdatedBy() { return updatedBy; } public Date getUpdatedDate() { return updatedDate; } public Long getCreatedBy() { return createdBy; } public Date getCreatedDate() { return createdDate; } public void setClId(final Long clId) { this.clId = clId; } public void setOrgid(final Long orgid) { this.orgid = orgid; } public void setSmServiceId(final Long smServiceId) { this.smServiceId = smServiceId; } public void setDocGroup(final String docGroup) { this.docGroup = docGroup; } public void setClStatus(final String clStatus) { this.clStatus = clStatus; } public void setUpdatedBy(final Long updatedBy) { this.updatedBy = updatedBy; } public void setUpdatedDate(final Date updatedDate) { this.updatedDate = updatedDate; } public void setCreatedBy(final Long createdBy) { this.createdBy = createdBy; } public void setCreatedDate(final Date createdDate) { this.createdDate = createdDate; } public Long getHiddenServiceId() { return hiddenServiceId; } public void setHiddenServiceId(final Long hiddenServiceId) { this.hiddenServiceId = hiddenServiceId; } }
gpl-3.0
fedepaol/BikeSharing
app/src/main/java/com/whiterabbit/pisabike/screens/favs/StationsFavsModule.java
1654
/* * Copyright (c) 2016 Federico Paolinelli. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.whiterabbit.pisabike.screens.favs; import com.whiterabbit.pisabike.schedule.SchedulersProvider; import com.whiterabbit.pisabike.screens.list.StationsFavsPresenter; import com.whiterabbit.pisabike.screens.list.StationsFavsPresenterImpl; import com.whiterabbit.pisabike.screens.list.StationsListPresenter; import com.whiterabbit.pisabike.screens.list.StationsListPresenterImpl; import com.whiterabbit.pisabike.storage.BikesProvider; import dagger.Module; import dagger.Provides; import pl.charmas.android.reactivelocation.ReactiveLocationProvider; @Module public class StationsFavsModule { @Provides public StationsFavsPresenter providePresenter(BikesProvider bikesProvider, SchedulersProvider schedulers, ReactiveLocationProvider location){ return new StationsFavsPresenterImpl(bikesProvider, schedulers, location); } }
gpl-3.0
lgulyas/MEME
Plugins/VCPlugins/ai/aitia/meme/builtinvcplugins/VC_StandardDeviation.java
1530
/******************************************************************************* * Copyright (C) 2006-2013 AITIA International, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package ai.aitia.meme.builtinvcplugins; import ai.aitia.meme.paramsweep.colt.Descriptive; import ai.aitia.meme.paramsweep.colt.DoubleArrayList; public class VC_StandardDeviation extends ColtBuiltinFn { //==================================================================================================== // implemented interfaces public String getLocalizedName() { return "STANDARD_DEVIATION()"; } //---------------------------------------------------------------------------------------------------- public Object compute(final IContext context) { final DoubleArrayList dal = convert2DAL(context); return Descriptive.standardDeviation(dal); } }
gpl-3.0
Cams13/ants-challenge
Bot.java
2180
/** * Provides basic game state handling. */ public abstract class Bot extends AbstractSystemInputParser { private Ants ants; /** * {@inheritDoc} */ @Override public void setup(int loadTime, int turnTime, int rows, int cols, int turns, int viewRadius2, int attackRadius2, int spawnRadius2) { setAnts(new Ants(loadTime, turnTime, rows, cols, turns, viewRadius2, attackRadius2, spawnRadius2)); } /** * Returns game state information. * * @return game state information */ public Ants getAnts() { return ants; } /** * Sets game state information. * * @param ants game state information to be set */ protected void setAnts(Ants ants) { this.ants = ants; } /** * {@inheritDoc} */ @Override public void beforeUpdate() { ants.setTurnStartTime(System.currentTimeMillis()); ants.clearMyAnts(); ants.clearEnemyAnts(); ants.clearMyHills(); ants.clearEnemyHills(); ants.clearFood(); ants.clearDeadAnts(); ants.getOrders().clear(); ants.clearVision(); } /** * {@inheritDoc} */ @Override public void addWater(int row, int col) { ants.update(Ilk.WATER, new Tile(row, col)); } /** * {@inheritDoc} */ @Override public void addAnt(int row, int col, int owner) { ants.update(owner > 0 ? Ilk.ENEMY_ANT : Ilk.MY_ANT, new Tile(row, col)); } /** * {@inheritDoc} */ @Override public void addFood(int row, int col) { ants.update(Ilk.FOOD, new Tile(row, col)); } /** * {@inheritDoc} */ @Override public void removeAnt(int row, int col, int owner) { ants.update(Ilk.DEAD, new Tile(row, col)); } /** * {@inheritDoc} */ @Override public void addHill(int row, int col, int owner) { ants.updateHills(owner, new Tile(row, col)); } /** * {@inheritDoc} */ @Override public void afterUpdate() { ants.setVision(); } }
gpl-3.0
TetrisMulti/Tetris
src/Beans/Forms.java
534
package Beans; import java.awt.*; /** * Created by Christoph on 14.03.2017. * Enum Klasse für die einzelnen Tetris Formen mit Farben */ public enum Forms { STICK(new Color(0,240,240)), BLOCK(new Color(249,240,0)), STAIRRIGHT(new Color(0,240,0)), STAIRLEFT(new Color(240,0,0)), LEFTL(new Color(0,0,240)), RIGHTL(new Color(240,160,0)), POTEST(new Color(160,0,240)) ; private Color c; Forms(Color c) { this.c = c; } public Color getC() { return c; } // }
gpl-3.0
ensozos/android-1
app/src/main/java/org/glucosio/android/tools/GlucoseRanges.java
1743
package org.glucosio.android.tools; import org.glucosio.android.db.DatabaseHandler; public class GlucoseRanges { private DatabaseHandler dB; private String preferredRange; private int customMin; private int customMax; public GlucoseRanges(){ dB = new DatabaseHandler(); this.preferredRange = dB.getUser(1).get_preferred_range(); if (preferredRange.equals("Custom range")){ this.customMin = dB.getUser(1).get_custom_range_min(); this.customMax = dB.getUser(1).get_custom_range_max(); } } public String colorFromRange(int reading) { // Check for Hypo/Hyperglycemia if (reading < 70 | reading > 200) { return "purple"; } else { // if not check with custom ranges switch (preferredRange) { case "ADA": if (reading >= 70 & reading <= 180) { return "green"; } else { return "red"; } case "AACE": if (reading >= 110 & reading <= 140) { return "green"; } else { return "red"; } case "UK NICE": if (reading >= 72 & reading <= 153) { return "green"; } else { return "red"; } default: if (reading >= customMin & reading <= customMax) { return "green"; } else { return "red"; } } } } }
gpl-3.0
abmindiarepomanager/ABMOpenMainet
Mainet1.0/MainetBRMS/Mainet_BRMS_BPMN/src/main/java/com/abm/mainet/brms/repository/ChecklistRepository.java
803
package com.abm.mainet.brms.repository; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import com.abm.mainet.brms.entity.TbDocumentGroupEntity; public interface ChecklistRepository extends CrudRepository<TbDocumentGroupEntity, Long>{ @Query("SELECT cl FROM TbDocumentGroupEntity cl,TbComparamDetEntity cp WHERE cl.docStatus='A' AND cl.orgId=:orgId " + " and cl.groupCpdId=cp.cpdId and cp.cpdValue in (:docGroup) and cl.orgId=cp.orgid " + " and cp.cpdStatus='A' and cp.orgid=:orgId ORDER BY cl.docSrNo ASC ") List<TbDocumentGroupEntity> fetchCheckListByDocumentGroup(@Param("docGroup")List<String> docGroupList, @Param("orgId")long orgId); }
gpl-3.0
DISID/disid-proofs
spring-roo-datatables-multiselect/src/main/java/org/springframework/roo/multiselect/domain/Owner.java
1107
package org.springframework.roo.multiselect.domain; import org.springframework.roo.addon.javabean.annotations.RooJavaBean; import org.springframework.roo.addon.javabean.annotations.RooToString; import org.springframework.roo.addon.jpa.annotations.entity.RooJpaEntity; import java.util.HashSet; import java.util.Set; import javax.persistence.FetchType; import javax.persistence.OneToMany; import org.springframework.roo.addon.jpa.annotations.entity.JpaRelationType; import org.springframework.roo.addon.jpa.annotations.entity.RooJpaRelation; import org.springframework.roo.addon.ws.annotations.jaxb.RooJaxbEntity; /** * = Owner * * TODO Auto-generated class documentation * */ @RooJavaBean @RooToString @RooJpaEntity @RooJaxbEntity public class Owner extends AbstractPerson { /** * TODO Auto-generated field documentation * */ @OneToMany(cascade = { javax.persistence.CascadeType.MERGE, javax.persistence.CascadeType.PERSIST }, fetch = FetchType.LAZY, mappedBy = "owner") @RooJpaRelation(type = JpaRelationType.AGGREGATION) private Set<Pet> pets = new HashSet<Pet>(); }
gpl-3.0
SupaHam/SupaCommons
commons-minecraft/src/main/java/com/supaham/commons/minecraft/world/space/Position.java
15592
package com.supaham.commons.minecraft.world.space; import com.google.common.base.Preconditions; import javax.annotation.Nonnull; import pluginbase.config.annotation.SerializeWith; @SerializeWith(PositionSerializer.class) public class Position extends Vector { public static final Position ZERO = new Position(0, 0, 0, 0, 0); public static final Position ONE = new Position(1, 1, 1, 0, 0); protected float yaw; protected float pitch; public Position(double x, double y, double z) { super(x, y, z); } public Position(double x, double y, double z, float yaw, float pitch) { super(x, y, z); this.yaw = yaw; this.pitch = pitch; } public float getYaw() { return yaw; } public Position setYaw(float yaw) { return yaw == this.yaw ? this : new Position(x, y, z, yaw, pitch); } public float getPitch() { return pitch; } public Position setPitch(float pitch) { return pitch == this.pitch ? this : new Position(x, y, z, yaw, pitch); } /** * Creates a new {@link Vector} of this vector plus another {@link Vector}. If * the given vector is equals to {@link #ZERO} this same Point instance is returned. * * @param o the other vector to add * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position add(@Nonnull Vector o) { Preconditions.checkNotNull(o, "o cannot be null."); return ZERO.equals(o) ? this : new Position(this.x + o.x, this.y + o.y, this.z + o.z, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector plus the three given components. If * the given components are equal to 0 this same Point instance is returned. * * @param x how much to add on the x axis * @param y how much to add on the y axis * @param z how much to add on the z axis * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position add(double x, double y, double z) { return x == 0 && y == 0 && z == 0 ? this : new Position(this.x + x, this.y + y, this.z + z, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector plus the given int constant on all axes. * If the given constant is equal to 0, this same Point instance is returned. * * @param a constant to add to all three components * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position add(int a) { return a == 0 ? this : new Position(this.x + a, this.y + a, this.z + a, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector plus the given double constant on all * axes. If the given constant is equal to 0, this same Point instance is returned. * * @param a constant to add to all three components * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position add(double a) { return a == 0 ? this : new Position(this.x + a, this.y + a, this.z + a, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector plus the given float constant on all * axes. If the given constant is equal to 0, this same Point instance is returned. * * @param a constant to add to all three components * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position add(float a) { return a == 0 ? this : new Position(this.x + a, this.y + a, this.z + a, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector minus another {@link Vector}. If * the given vector is equals to {@link #ZERO} this same Point instance is returned. * * @param o the other vector to subtract * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position subtract(@Nonnull Vector o) { Preconditions.checkNotNull(o, "o cannot be null."); return ZERO.equals(o) ? this : new Position(this.x - o.x, this.y - o.y, this.z - o.z, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector minus the three given components. If * the given components are equal to 0 this same Point instance is returned. * * @param x how much to subtract on the x axis * @param y how much to subtract on the y axis * @param z how much to subtract on the z axis * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position subtract(double x, double y, double z) { return x == 0 && y == 0 && z == 0 ? this : new Position(this.x - x, this.y - y, this.z - z, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector minus the given int constant on all axes. * If the given constant is equal to 0, this same Point instance is returned. * * @param a constant to subtract from all three components * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position subtract(int a) { return a == 0 ? this : new Position(this.x - a, this.y - a, this.z - a, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector minus the given double constant on all * axes. If the given constant is equal to 0, this same Point instance is returned. * * @param a constant to subtract from all three components * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position subtract(double a) { return a == 0 ? this : new Position(this.x - a, this.y - a, this.z - a, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector minus the given float constant on all * axes. If the given constant is equal to 0, this same Point instance is returned. * * @param a constant to subtract from all three components * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position subtract(float a) { return a == 0 ? this : new Position(this.x - a, this.y - a, this.z - a, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector divided by another {@link * Vector}. If the given vector is equals to {@link #ONE} this same Point * instance is returned. * * @param o the other vector to divide by * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position divide(@Nonnull Vector o) { Preconditions.checkNotNull(o, "o cannot be null."); return ONE.equals(o) ? this : new Position(this.x / o.x, this.y / o.y, this.z / o.z, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector divided by the three given components. If * the given components are equal to 1 this same Point instance is returned. * * @param x how much to divide by on the x axis * @param y how much to divide by on the y axis * @param z how much to divide by on the z axis * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position divide(double x, double y, double z) { return x == 1 && y == 1 && z == 1 ? this : new Position(this.x / x, this.y / y, this.z / z, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector divided by the given int constant on all * axes. If the given constant is equal to 1, this same Point instance is returned. * * @param d constant to divide by for all three components * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position divide(int d) { return d == 1 ? this : new Position(this.x / d, this.y / d, this.z / d, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector divided by the given double constant on * all axes. If the given constant is equal to 1, this same Point instance is returned. * * @param d constant to divide by for all three components * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position divide(double d) { return d == 1 ? this : new Position(this.x / d, this.y / d, this.z / d, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector divided by the given float constant on * all axes. If the given constant is equal to 1, this same Point instance is returned. * * @param d constant to divide by for all three components * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position divide(float d) { return d == 1 ? this : new Position(this.x / d, this.y / d, this.z / d, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector multiplied by another {@link * Vector}. If the given vector is equals to {@link #ONE} this same Point * instance is returned. * * @param o the other vector to multiply by * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position multiply(@Nonnull Vector o) { Preconditions.checkNotNull(o, "o cannot be null."); return ONE.equals(o) ? this : new Position(this.x * o.x, this.y * o.y, this.z * o.z, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector multiplied by the three given components. * If the given components are equal to 1 this same Point instance is returned. * * @param x how much to multiply by on the x axis * @param y how much to multiply by on the y axis * @param z how much to multiply by on the z axis * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position multiply(double x, double y, double z) { return x == 1 && y == 1 && z == 1 ? this : new Position(this.x * x, this.y * y, this.z * z, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector multiplied by the given int constant on * all axes. If the given constant is equal to 1, this same Point instance is returned. * * @param m constant to multiply by for all three components * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position multiply(int m) { return m == 1 ? this : new Position(this.x * m, this.y * m, this.z * m, this.yaw, this.pitch); } /** * Creates a new {@link Vector} of this vector multiplied by the given double constant * on all axes. If the given constant is equal to 1, this same Point instance is * returned. * * @param m constant to multiply by for all three components * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position multiply(double m) { return m == 1 ? this : new Position(this.x * m, this.y * m, this.z * m, this.yaw, this.pitch); } /** * Returns a new {@link Vector} of this vector multiplied by the given float constant * on all axes. If the given constant is equal to 1, this same Point instance is * returned. * * @param m constant to multiply by for all three components * * @return a new {@link Vector} or the same instance if no modification was made */ @Nonnull public Position multiply(float m) { return m == 1 ? this : new Position(this.x * m, this.y * m, this.z * m, this.yaw, this.pitch); } /** * Returns a new {@link Vector} of the midpoint vector between this vector and another * {@link Vector}. If the given constant is {@link #equals(Object)} to the given vector * {@code o}, this same Point instance is returned. * * @param o the other vector * * @return a new {@link Vector} of the midpoint */ @Nonnull public Position midpoint(@Nonnull Vector o) { Preconditions.checkNotNull(o, "o cannot be null."); return equals(o) ? this : new Position((this.x + o.x) / 2.0D, (this.y + o.y) / 2.0D, (this.z + o.z) / 2.0D, this.yaw, this.pitch); } /** * Returns a new {@link Vector} of the cross product of this vector with another {@link * Vector}. The cross product is defined as: * <ul> * <li>x = y1 * z2 - y2 * z1 * <li>y = z1 * x2 - z2 * x1 * <li>z = x1 * y2 - x2 * y1 * </ul> * * @param o the other vector * * @return a new {@link Vector} of the cross product */ @Nonnull public Position crossProduct(@Nonnull Vector o) { Preconditions.checkNotNull(o, "o cannot be null."); return equals(o) ? this : new Position(this.y * o.z - o.y * this.z, this.z * o.x - o.z * this.x, this.x * o.y - o.x * this.y, this.yaw, this.pitch); } /** * Returns a new {@link Vector} of this vector to a unit vector (a vector with length * of 1). * * @return a new {@link Vector} of the unit vector */ @Nonnull public Position normalize() { return divide(length()); } /** * Returns a new {@link Position} with the three {@code x, y, z} components negated. Where a * {@code Position[-1,0,1,2,3].negate()} occurs, the returned position will be {@code Position[1,0,-1,2,3]}. * <p /> * <b>Note: The yaw and pitch are not affected by this operation.</b> This is done to ensure consistent behaviour * with all instances of {@link Vector}. * * @return negated position * @see #negate(boolean) */ @Override public Position negate() { return negate(false); } /** * Returns a new {@link Position} with the three {@code x, y, z} components negated. If {@code direction} is true, * the yaw and pitch will be negated as well. * <p /> * Where a {@code Position[-1,0,1,2,3].negate(false)} occurs, the returned position will be {@code * Position[1,0,-1,2,3]}. * <br /> * Where a {@code Position[-1,0,1,2,3].negate(true)} occurs, the returned position will be {@code * Position[1,0,-1,-2,-3]}. * * @param direction whether to negate the direction * * @return negated position * @see #negateDirection() */ public Position negate(boolean direction) { return new Position(x == 0 ? 0 : -x, y == 0 ? 0 : -y, z == 0 ? 0 : -z, yaw != 0 && direction ? -this.yaw : this.yaw, pitch != 0 && direction ? -this.pitch : this.pitch); } /** * Returns a new {@link Position} with the direction negated. * <p /> * Where a {@code Position[-1,0,1,2,3].negateDirection()} occurs, the returned position will be * {@code Position[1,0,-1,-2,-3]}. * * @return postion with negated direction */ public Position negateDirection() { return new Position(x, y, z, yaw == 0 ? 0 : -yaw, pitch == 0 ? 0 : -pitch); } @Nonnull public Position copy() { return new Position(x, y, z, yaw, pitch); } @Nonnull @Override public Position toPosition() { return super.toPosition(this.yaw, this.pitch); } @Nonnull @Override public MutablePosition toMutablePosition() { return super.toMutablePosition(this.yaw, this.pitch); } }
gpl-3.0
srug-dev/Refuel
RefuelApp/app/src/main/java/com/srug/mobile/refuel/view/UserFragment.java
2241
package com.srug.mobile.refuel.view; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.srug.mobile.refuel.R; import com.srug.mobile.refuel.view.ui.UserListAdapter; import com.srug.mobile.refuel.view.ui.VehicleListAdapter; public class UserFragment extends Fragment { public static final String USER_FRAGMENT_TAG = "com.srug.mobile.refuel.view.USER_FRAGMENT_TAG"; private Context mContext; private UserListAdapter mUserListAdapter; private VehicleListAdapter mVehicleListAdapter; private RecyclerView mRvUserList; private RecyclerView mRvVehicleList; public UserFragment() { } public void setAdapter(VehicleListAdapter adapter) { mVehicleListAdapter = adapter; } public void setAdapter(UserListAdapter adapter) { mUserListAdapter = adapter; } @Override public void onAttach(Activity activity) { super.onAttach(activity); mContext = activity.getApplicationContext(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_user, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { mRvUserList = (RecyclerView) view.findViewById(R.id.rv_user_list); mRvUserList.setHasFixedSize(true); mRvUserList.setAdapter(mUserListAdapter); LinearLayoutManager userListLayoutManager = new LinearLayoutManager(mContext); mRvUserList.setLayoutManager(userListLayoutManager); mRvVehicleList = (RecyclerView) view.findViewById(R.id.rv_vehicle_list); mRvVehicleList.setHasFixedSize(true); mRvVehicleList.setAdapter(mVehicleListAdapter); LinearLayoutManager vehicleListLayoutManager = new LinearLayoutManager(mContext); mRvVehicleList.setLayoutManager(vehicleListLayoutManager); } }
gpl-3.0
Naoghuman/lib-database-objectdb
src/test/java/com/github/naoghuman/lib/database/core/ObjectBTypesEntity.java
2744
/* * Copyright (C) 2015 Naoghuman * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.github.naoghuman.lib.database.core; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; @Entity @Access(AccessType.PROPERTY) @Table(name = "ObjectBTypesEntity") @NamedQueries({ @NamedQuery(// need crud name = "ObjectBTypesEntity.findAll", query = "SELECT p from ObjectBTypesEntity p") }) public class ObjectBTypesEntity implements Externalizable { private static final long serialVersionUID = 1L; // START ------------------------------------------------------------------- private IntegerProperty id; private int _id; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "Id") public final int getId() { if (this.id == null) { return _id; } else { return id.get(); } } public final void setId(int id) { if (this.id == null) { _id = id; } else { this.id.set(id); } } public IntegerProperty idProperty() { if (id == null) { id = new SimpleIntegerProperty(this, "Id", _id); } return id; } // END ------------------------------------------------------------------- @Override public void writeExternal(ObjectOutput out) throws IOException { } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } }
gpl-3.0
disappearTesting/workspace
JAVA/src/Exercises/ScannerEvenOddWhile.java
971
package Exercises; import java.util.Scanner; /** Ïðîãðàììà-ñîîáùàþþùàÿ, ÿâëÿåòñÿ ëè öåëîå ÷èñëî * ââåä¸ííîå ïîëüçîâàòåëåì, ÷¸òíûì èëè íå÷¸òíûì. * Åñëè ïîëüçîâàòåëü ââåä¸ò íå öåëîå ÷èñëî, * òî ñîîáùàåò åìó îá îøèáêå. * * Âàðèàíò ðåàëèçàöèè ñ ïîìîùüþ * öèêëà while (true) * @author hookie * @version 1.0 */ public class ScannerEvenOddWhile { public static int i; public static void inScanner() { while (true) { Scanner in = new Scanner(System.in); System.out.print("Ââåäèòå ÷åòíîå ÷èñëî: "); if(in.hasNextInt()) { i = in.nextInt(); if(i%2 == 0) { System.out.println("Âû ââåëè ÷åòíîå ÷èñëî: " + i); in.close(); System.out.print("Ðàáîòà ïðîãðàììû çàâåðøåíà."); break; } else if(i%2 != 0) { System.out.println("Âû ââåëè íå÷åòíîå ÷èñëî: " + i); } } else { System.out.println("Îøèáêà. Ïðîâåðüòå ïðàâèëüíîñòü ââîäà!"); } } } public static void main(String[] args) { inScanner(); } }
gpl-3.0
rbotafogo/scicom
src/rb/scicom/MDIntVectorD4.java
3180
/****************************************************************************************** * @author Rodrigo Botafogo * * Copyright © 2013 Rodrigo Botafogo. All Rights Reserved. Permission to use, copy, modify, * and distribute this software and its documentation, without fee and without a signed * licensing agreement, is hereby granted, provided that the above copyright notice, this * paragraph and the following two paragraphs appear in all copies, modifications, and * distributions. * * IN NO EVENT SHALL RODRIGO BOTAFOGO BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, * INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF * THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF RODRIGO BOTAFOGO HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * RODRIGO BOTAFOGO SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE * SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". * RODRIGO BOTAFOGO HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, * OR MODIFICATIONS. ******************************************************************************************/ package rb.scicom; import ucar.ma2.*; import org.renjin.sexp.*; public class MDIntVectorD4 extends MDIntVector { private int _jump0, _jump1; private int _shape1, _shape2, _shape3; /*------------------------------------------------------------------------------------- * *-----------------------------------------------------------------------------------*/ private MDIntVectorD4(AttributeMap attributes) { super(attributes); } /*------------------------------------------------------------------------------------- * *-----------------------------------------------------------------------------------*/ public MDIntVectorD4(ArrayInt array, AttributeMap attributes) { super(attributes); _array = array; _index = _array.getIndex(); _shape1 = array.getShape()[1]; _shape2 = array.getShape()[2]; _shape3 = array.getShape()[3]; _jump1 = _shape2 * _shape3; _jump0 = _jump1 * _shape1; } /*------------------------------------------------------------------------------------- * Given an element in the array in colum-major order finds the coresponding counter in * row-major order. Assumes that currElement is a valid element of the Vector. *-----------------------------------------------------------------------------------*/ public void setCurrentCounter(int currElement) { int current0, current1, current2, current3; // Initial dimensions, i.e., all but the last two current0 = currElement / _jump0; currElement -= current0 * _jump0; current1 = currElement / _jump1; currElement -= current1 * _jump1; // Last two dimensions current2 = currElement % _shape2; currElement = (currElement - current2) / _shape2; current3 = currElement % _shape3; currElement = (currElement - current3) / _shape3; _index.set(current0, current1, current2, current3); // transfer to subclass fields } }
gpl-3.0
cleberecht/singa
singa-structure/src/main/java/bio/singa/structure/parser/plip/PlipCountFingerprint.java
1219
package bio.singa.structure.parser.plip; import bio.singa.mathematics.vectors.RegularVector; import bio.singa.mathematics.vectors.Vector; import java.util.Map; import java.util.TreeMap; import java.util.stream.Stream; public class PlipCountFingerprint { private Map<InteractionType, Integer> counts = new TreeMap<>(); private Vector vector; private PlipCountFingerprint() { Stream.of(InteractionType.values()) .forEach(interactionType -> counts.putIfAbsent(interactionType, 0)); } public static PlipCountFingerprint of(InteractionContainer interactionContainer) { PlipCountFingerprint plipCountFingerprint = new PlipCountFingerprint(); for (Interaction interaction : interactionContainer.getInteractions()) { plipCountFingerprint.counts.merge(interaction.getInteractionType(), 1, Integer::sum); } return plipCountFingerprint; } public Vector getVector() { if (vector == null) { double[] elements = counts.values().stream() .mapToDouble(Double::valueOf) .toArray(); vector = new RegularVector(elements); } return vector; } }
gpl-3.0
isalnikov/ACMP
src/main/java/ru/isalnikov/acmp/acmp61/Main.java
1735
package ru.isalnikov.acmp.acmp61; /** * Известны результаты каждой из 4х четвертей баскетбольной встречи. Нужно * определить победителя матча. * * Входные данные * * Входной файл INPUT.TXT содержит 4 строки, в каждой строке находится два целых * числа a и b – итоговый счет в соответствующей четверти. а – количество * набранных очков за четверть первой командой, b – количество очков, набранных * за четверть второй командой. (0 ≤ a,b ≤ 100). * * @author Igor Salnikov <admin@isalnikov.com> */ import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { try (Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out)) { solve(in, out); } } private static void solve(Scanner in, PrintWriter out) { int a1 = in.nextInt(); int b1 = in.nextInt(); int a2 = in.nextInt(); int b2 = in.nextInt(); int a3 = in.nextInt(); int b3 = in.nextInt(); int a4 = in.nextInt(); int b4 = in.nextInt(); int result = Integer.compare(a1 + a2 + a3+a4, b1 + b2 + b3+b4); if (result == 1) { out.print("1"); } else if (result == -1) { out.print("2"); } else { out.print("DRAW"); } out.flush(); } }
gpl-3.0
ThirtyDegreesRay/OpenHub
app/src/main/java/com/thirtydegreesray/openhub/ui/fragment/UserListFragment.java
4125
package com.thirtydegreesray.openhub.ui.fragment; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.View; import com.thirtydegreesray.openhub.R; import com.thirtydegreesray.openhub.inject.component.AppComponent; import com.thirtydegreesray.openhub.inject.component.DaggerFragmentComponent; import com.thirtydegreesray.openhub.inject.module.FragmentModule; import com.thirtydegreesray.openhub.mvp.contract.IUserListContract; import com.thirtydegreesray.openhub.mvp.model.SearchModel; import com.thirtydegreesray.openhub.mvp.model.User; import com.thirtydegreesray.openhub.mvp.presenter.UserListPresenter; import com.thirtydegreesray.openhub.ui.activity.ProfileActivity; import com.thirtydegreesray.openhub.ui.adapter.UsersAdapter; import com.thirtydegreesray.openhub.ui.fragment.base.ListFragment; import com.thirtydegreesray.openhub.util.BundleHelper; import java.util.ArrayList; /** * Created by ThirtyDegreesRay on 2017/8/16 17:40:20 */ public class UserListFragment extends ListFragment<UserListPresenter, UsersAdapter> implements IUserListContract.View{ public enum UserListType{ STARGAZERS, WATCHERS, FOLLOWERS, FOLLOWING, SEARCH, ORG_MEMBERS, TRACE, BOOKMARK } public static UserListFragment create(@NonNull UserListType type, @NonNull String user, @NonNull String repo){ UserListFragment fragment = new UserListFragment(); fragment.setArguments( BundleHelper.builder() .put("type", type) .put("user", user) .put("repo", repo) .build() ); return fragment; } public static UserListFragment createForSearch(@NonNull SearchModel searchModel){ UserListFragment fragment = new UserListFragment(); fragment.setArguments( BundleHelper.builder() .put("type", UserListType.SEARCH) .put("searchModel", searchModel) .build() ); return fragment; } public static UserListFragment createForTrace(){ UserListFragment fragment = new UserListFragment(); fragment.setArguments(BundleHelper.builder().put("type", UserListType.TRACE).build()); return fragment; } public static UserListFragment createForBookmark(){ UserListFragment fragment = new UserListFragment(); fragment.setArguments(BundleHelper.builder().put("type", UserListType.BOOKMARK).build()); return fragment; } @Override protected int getLayoutId() { return R.layout.fragment_list; } @Override protected void setupFragmentComponent(AppComponent appComponent) { DaggerFragmentComponent.builder() .appComponent(appComponent) .fragmentModule(new FragmentModule(this)) .build() .inject(this); } @Override protected void initFragment(Bundle savedInstanceState) { super.initFragment(savedInstanceState); setLoadMoreEnable(true); } @Override protected void onReLoadData() { mPresenter.loadUsers(1, true); } @Override protected String getEmptyTip() { return getString(R.string.no_user); } @Override public void showUsers(ArrayList<User> users) { adapter.setData(users); postNotifyDataSetChanged(); } @Override protected void onLoadMore(int page) { super.onLoadMore(page); mPresenter.loadUsers(page, false); } @Override public void onItemClick(int position, @NonNull View view) { super.onItemClick(position, view); View userAvatar = view.findViewById(R.id.avatar); ProfileActivity.show(getActivity(), userAvatar, adapter.getData().get(position).getLogin(), adapter.getData().get(position).getAvatarUrl()); } @Override public void onFragmentShowed() { super.onFragmentShowed(); if(mPresenter != null) mPresenter.prepareLoadData(); } }
gpl-3.0
axkr/symja_android_library
symja_android_library/matheclipse-core/src/main/java/org/matheclipse/core/expression/AST.java
14813
package org.matheclipse.core.expression; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.StringTokenizer; import org.matheclipse.core.basic.Config; import org.matheclipse.core.eval.exception.ASTElementLimitExceeded; import org.matheclipse.core.interfaces.IAST; import org.matheclipse.core.interfaces.IASTAppendable; import org.matheclipse.core.interfaces.IASTMutable; import org.matheclipse.core.interfaces.IExpr; import org.matheclipse.core.interfaces.ISymbol; /** * (A)bstract (S)yntax (T)ree of a given function. * * <p> * In Symja, an abstract syntax tree (AST), is a tree representation of the abstract syntactic * structure of the Symja source code. Each node of the tree denotes a construct occurring in the * source code. The syntax is 'abstract' in the sense that it does not represent every detail that * appears in the real syntax. For instance, grouping parentheses are implicit in the tree * structure, and a syntactic construct such as a <code>Sin[x]</code> expression will be denoted by * an AST with 2 nodes. One node for the header <code>Sin</code> and one node for the argument * <code>x</code>. Internally an AST is represented as a list which contains * * <ul> * <li>the operator of a function (i.e. the &quot;header&quot;-symbol: Sin, Cos, Inverse, Plus, * Times,...) at index <code>0</code> and * <li>the <code>n</code> arguments of a function in the index <code>1 to n</code> * </ul> * * <p> * See: <a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree">Wikipedia: Abstract syntax * tree</a>. */ public class AST extends HMArrayList implements Externalizable { /** */ private static final long serialVersionUID = 4295200630292148027L; public static AST newInstance(final IExpr head) { AST ast = new AST(5, false); ast.append(head); return ast; } protected static AST newInstance(final int intialCapacity, final IAST ast, int endPosition) { if (Config.MAX_AST_SIZE < intialCapacity) { ASTElementLimitExceeded.throwIt(intialCapacity); } AST result = new AST(intialCapacity, false); result.appendAll(ast, 0, endPosition); return result; } /** * @param initialCapacity the initial capacity (i.e. number of arguments without the header * element) of the list. * @param head the header expression of the function. If the ast represents a function like <code> * f[x,y], Sin[x],...</code>, the <code>head</code> will be an instance of type ISymbol. * @param initNull initialize all elements with <code>null</code>. * @return */ public static AST newInstance(final int initialCapacity, final IExpr head, boolean initNull) { if (Config.MAX_AST_SIZE < initialCapacity || initialCapacity < 0) { ASTElementLimitExceeded.throwIt(initialCapacity); } AST ast = new AST(initialCapacity, initNull); if (initNull) { ast.set(0, head); } else { ast.append(head); } return ast; } public static AST newInstance(final int initialCapacity, final IExpr head) { if (Config.MAX_AST_SIZE < initialCapacity || initialCapacity < 0) { ASTElementLimitExceeded.throwIt(initialCapacity); } AST ast = new AST(initialCapacity); ast.append(head); return ast; } /** * Create a new function expression (AST - abstract syntax tree), where all arguments are Java * {@link ComplexNum} values. * * @param symbol * @param evalComplex if <code>true</code> test if the imaginary part of the complex number is * zero and insert a {@link Num} real value. * @param arr the complex number arguments * @return */ public static AST newInstance(final ISymbol symbol, boolean evalComplex, final org.hipparchus.complex.Complex... arr) { if (Config.MAX_AST_SIZE < arr.length) { ASTElementLimitExceeded.throwIt(arr.length); } IExpr[] eArr = new IExpr[arr.length + 1]; eArr[0] = symbol; if (evalComplex) { double im; for (int i = 1; i <= arr.length; i++) { im = arr[i - 1].getImaginary(); if (F.isZero(im)) { eArr[i] = Num.valueOf(arr[i - 1].getReal()); } else { eArr[i] = ComplexNum.valueOf(arr[i - 1]); } } } else { for (int i = 1; i <= arr.length; i++) { eArr[i] = ComplexNum.valueOf(arr[i - 1]); } } return new AST(eArr); } /** * Constructs a list with header <i>symbol</i> and the arguments containing the given DoubleImpl * values. * * @param symbol * @param arr * @return */ public static AST newInstance(final ISymbol symbol, final double... arr) { if (Config.MAX_AST_SIZE < arr.length) { ASTElementLimitExceeded.throwIt(arr.length); } IExpr[] eArr = new IExpr[arr.length + 1]; eArr[0] = symbol; for (int i = 1; i <= arr.length; i++) { eArr[i] = Num.valueOf(arr[i - 1]); } return new AST(eArr); } /** * Constructs a list with header <i>symbol</i> and the arguments containing the given DoubleImpl * matrix values as <i>List</i> rows * * @param symbol * @param matrix * @return * @see Num */ public static AST newInstance(final ISymbol symbol, final double[][] matrix) { if (Config.MAX_AST_SIZE < matrix.length) { ASTElementLimitExceeded.throwIt(matrix.length); } IExpr[] eArr = new IExpr[matrix.length + 1]; eArr[0] = symbol; for (int i = 1; i <= matrix.length; i++) { eArr[i] = newInstance(S.List, matrix[i - 1]); } return new AST(eArr); } public static AST newInstance(final ISymbol symbol, final int... arr) { if (Config.MAX_AST_SIZE < arr.length) { ASTElementLimitExceeded.throwIt(arr.length); } IExpr[] eArr = new IExpr[arr.length + 1]; eArr[0] = symbol; for (int i = 1; i <= arr.length; i++) { eArr[i] = AbstractIntegerSym.valueOf(arr[i - 1]); } return new AST(eArr); } /** * simple parser to simplify unit tests. The parser assumes that the String contains no syntax * errors. * * <p> * Example &quot;List[x,List[y]]&quot; * * @param inputString * @return */ public static IAST parse(final String inputString) { final StringTokenizer tokenizer = new StringTokenizer(inputString, "[],", true); String token = tokenizer.nextToken(); final IASTAppendable list = newInstance(StringX.valueOf(token)); token = tokenizer.nextToken(); if ("[".equals(token)) { parseList(tokenizer, list); return list; } // syntax fError occured return null; } private static void parseList(final StringTokenizer tokenizer, final IASTAppendable list) { String token = tokenizer.nextToken(); do { if ("]".equals(token)) { return; } else if (" ".equals(token)) { // ignore spaces } else { String arg; if (",".equals(token)) { arg = tokenizer.nextToken(); } else { arg = token; } token = tokenizer.nextToken(); if ("[".equals(token)) { IASTAppendable argList = newInstance(StringX.valueOf(arg)); parseList(tokenizer, argList); list.append(argList); } else { list.append(StringX.valueOf(arg)); continue; } } token = tokenizer.nextToken(); } while (tokenizer.hasMoreTokens()); } /** Public no-arg constructor only needed for serialization */ public AST() { super(0); } /* package private */ AST(IExpr head, IExpr... exprs) { super(head, exprs); } /** * Package private constructor. * * @param exprs */ /* package private */ AST(IExpr[] exprs) { super(exprs); } /** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity (i.e. number of arguments without the header * element) of the list. * @param setLength if <code>true</code>, sets the array's size to initialCapacity. */ protected AST(final int initialCapacity, final boolean setLength) { super(initialCapacity + 1); lastIndex += (setLength ? initialCapacity + 1 : 0); } protected AST(final int initialCapacity) { super(initialCapacity + 1); } /** {@inheritDoc} */ @Override public IAST appendOneIdentity(IAST value) { if (value.isAST1()) { append(value.arg1()); } else { append(value); } return this; } /** * Returns a shallow copy of this <tt>AST</tt> instance. (The elements themselves are not copied.) * * @return a clone of this <tt>AST</tt> instance. */ // @Override // public IAST clone() { // throw new UnsupportedOperationException(); //// AST ast = new AST(); //// // ast.fProperties = null; //// ast.array = array.clone(); //// ast.hashValue = 0; //// ast.firstIndex = firstIndex; //// ast.lastIndex = lastIndex; //// return ast; // } @Override public IASTAppendable copyAppendable() { if (size() > Config.MIN_LIMIT_PERSISTENT_LIST) { return new ASTRRBTree(this); } AST ast = new AST(); // ast.fProperties = null; ast.array = array.clone(); ast.hashValue = 0; ast.firstIndex = firstIndex; ast.lastIndex = lastIndex; return ast; } @Override public IASTAppendable copyAppendable(int additionalCapacity) { final int size = size(); if (size > Config.MIN_LIMIT_PERSISTENT_LIST || additionalCapacity > Config.MIN_LIMIT_PERSISTENT_LIST) { return new ASTRRBTree(this); } AST ast = new AST(); // ast.fProperties = null; if (size + additionalCapacity > array.length) { ast.array = new IExpr[size() + additionalCapacity]; System.arraycopy(array, 0, ast.array, 0, array.length); } else { ast.array = array.clone(); } ast.hashValue = 0; ast.firstIndex = firstIndex; ast.lastIndex = lastIndex; return ast; } @Override public IAST getItems(int[] items, int length) { AST result = new AST(length, true); result.set(0, head()); for (int i = 0; i < length; i++) { result.set(i + 1, get(items[i])); } return result; } @Override public IASTMutable copy() { switch (size()) { case 1: return new AST0(head()); case 2: return new AST1(head(), arg1()); case 3: return new AST2(head(), arg1(), arg2()); case 4: return new AST3(head(), arg1(), arg2(), arg3()); } AST ast = new AST(); // ast.fProperties = null; ast.array = array.clone(); ast.hashValue = 0; ast.firstIndex = firstIndex; ast.lastIndex = lastIndex; return ast; } /** {@inheritDoc} */ @Override public IAST rest() { switch (size()) { case 1: return this; case 2: return F.headAST0(head()); case 3: return F.unaryAST1(head(), arg2()); // case 4: // return F.binaryAST2(head(), arg2(), arg3()); // case 5: // return F.ternaryAST3(head(), arg2(), arg3(), arg4()); default: if (isOrderlessAST()) { return super.rest(); } // return new ASTProxy(this, 2); return super.rest(); } } @Override public IAST removeFromEnd(int fromPosition) { if (0 < fromPosition && fromPosition <= size()) { if (fromPosition == size()) { return this; } AST ast = new AST(array); ast.firstIndex = firstIndex; ast.lastIndex = firstIndex + fromPosition; return ast; } else { throw new IndexOutOfBoundsException("Index: " + Integer.valueOf(fromPosition) + ", Size: " + Integer.valueOf(lastIndex - firstIndex)); } } @Override public IAST removeFromStart(int firstPosition) { if (firstPosition == 1) { return this; } if (0 < firstPosition && firstPosition <= size()) { int last = size(); int size = last - firstPosition + 1; switch (size) { case 1: return F.headAST0(head()); case 2: return F.unaryAST1(head(), get(last - 1)); case 3: return F.binaryAST2(head(), get(last - 2), get(last - 1)); case 4: return F.ternaryAST3(head(), get(last - 3), get(last - 2), get(last - 1)); default: if (isOrderlessAST()) { return copyFrom(firstPosition); } // return new ASTProxy(this, firstPosition); return copyFrom(firstPosition); } } else { throw new IndexOutOfBoundsException( "Index: " + Integer.valueOf(firstPosition) + ", Size: " + size()); } } @Override public void readExternal(ObjectInput objectInput) throws IOException, ClassNotFoundException { this.fEvalFlags = objectInput.readShort(); int size; byte attributeFlags = objectInput.readByte(); if (attributeFlags != 0) { size = attributeFlags; IExpr[] array = new IExpr[size]; init(array); int exprIDSize = objectInput.readByte(); for (int i = 0; i < exprIDSize; i++) { this.array[i] = S.exprID(objectInput.readShort()); // F.GLOBAL_IDS[objectInput.readShort()]; } for (int i = exprIDSize; i < size; i++) { this.array[i] = (IExpr) objectInput.readObject(); } return; } size = objectInput.readInt(); IExpr[] array = new IExpr[size]; init(array); for (int i = 0; i < size; i++) { this.array[i] = (IExpr) objectInput.readObject(); } } @Override public void writeExternal(ObjectOutput objectOutput) throws IOException { objectOutput.writeShort(fEvalFlags); int size = size(); byte attributeFlags = (byte) 0; if (size > 0 && size < 128) { Short exprID = S.GLOBAL_IDS_MAP.get(head()); if (exprID != null) { int exprIDSize = 1; short[] exprIDArray = new short[size]; exprIDArray[0] = exprID; for (int i = 1; i < size; i++) { exprID = S.GLOBAL_IDS_MAP.get(get(i)); if (exprID == null) { break; } exprIDArray[i] = exprID; exprIDSize++; } // optimized path attributeFlags = (byte) size; objectOutput.writeByte(attributeFlags); objectOutput.writeByte((byte) exprIDSize); for (int i = 0; i < exprIDSize; i++) { objectOutput.writeShort(exprIDArray[i]); } for (int i = exprIDSize; i < size; i++) { objectOutput.writeObject(get(i)); } return; } } objectOutput.writeByte(attributeFlags); objectOutput.writeInt(size); for (int i = 0; i < size; i++) { objectOutput.writeObject(get(i)); } } private Object writeReplace() { return optional(); } }
gpl-3.0
zeminlu/comitaco
tests/ase2016/introclass/smallest/introclass_af81ffd4_000.java
1082
package ase2016.introclass.smallest; public class introclass_af81ffd4_000 { public introclass_af81ffd4_000() { } /*@ @ requires true; @ ensures ((\result == \old(a)) || (\result == \old(b)) || (\result == \old(c)) || (\result == \old(d)) ); @ ensures ((\result <= \old(a)) && (\result <= \old(b)) && (\result <= \old(c)) && (\result <= \old(d)) ); @ signals (RuntimeException e) false; @ @*/ public int smallest(int a, int b, int c, int d) { int m = 0; //mutGenLimit 1 int p = 0; //mutGenLimit 1 int n = 0; //mutGenLimit 1 if (a > b) { //mutGenLimit 1 m = b; //mutGenLimit 1 } else if (a < b) { //mutGenLimit 1 m = a; //mutGenLimit 1 } if (m > c) { //mutGenLimit 1 n = c; //mutGenLimit 1 } else if (m < c) { //mutGenLimit 1 n = m; //mutGenLimit 1 } if (n > d) { //mutGenLimit 1 p = d; //mutGenLimit 1 } else if (n < d) { //mutGenLimit 1 p = n; //mutGenLimit 1 } return p; //mutGenLimit 1 } }
gpl-3.0
scaffeinate/Stormcast
app/src/main/java/io/stormcast/app/stormcast/common/network/Flags.java
988
package io.stormcast.app.stormcast.common.network; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; public class Flags { @SerializedName("sources") @Expose private List<String> sources = new ArrayList<String>(); @SerializedName("isd-stations") @Expose private List<String> isdStations = new ArrayList<String>(); @SerializedName("units") @Expose private String units; public List<String> getSources() { return sources; } public void setSources(List<String> sources) { this.sources = sources; } public List<String> getIsdStations() { return isdStations; } public void setIsdStations(List<String> isdStations) { this.isdStations = isdStations; } public String getUnits() { return units; } public void setUnits(String units) { this.units = units; } }
gpl-3.0
tpfinal-pp1/tp-final
src/main/java/com/TpFinal/services/Planificador.java
20662
package com.TpFinal.services; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.format.DateTimeFormatterBuilder; import java.util.Date; import java.util.List; import org.quartz.CronScheduleBuilder; import org.quartz.Job; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.quartz.TriggerBuilder; import org.quartz.TriggerKey; import org.quartz.impl.StdSchedulerFactory; import com.TpFinal.dto.cita.Cita; import com.TpFinal.dto.cobro.Cobro; import com.TpFinal.dto.contrato.ContratoAlquiler; import com.TpFinal.dto.parametrosSistema.ParametrosSistema; import com.TpFinal.dto.persona.Calificacion; public class Planificador { Scheduler sc; Job notificacion; Job mailSender; // citas Integer horasAntesCita1 = 1; Integer horasAntesCita2 = 24; // cobros por vencer Integer perioricidadPorVencerA; Integer perioricidadPorVencerB; Integer perioricidadPorVencerC; Integer perioricidadPorVencerD; Integer diasAntesCobroPorVencer; // cobros vencidos LocalTime horaInicioCobrosVencidos; // Contratos por vencer Integer mesesAntesVencimientoContrato; Integer perioricidadEnDiasVencimientoContrato; // Contratos vencidos Integer perioricidadContratoVencido; Integer diasAntesContratoVencido; private static Planificador instancia; public static boolean demoIniciado = false; public static Planificador get() { if (instancia == null) { try { instancia = new Planificador(); } catch (SchedulerException e) { e.printStackTrace(); } } return instancia; } private Planificador() throws SchedulerException { if (sc == null) this.sc = StdSchedulerFactory.getDefaultScheduler(); ParametrosSistema ps = ParametrosSistemaService.getParametros(); setParametros(ps); } public void setParametros(ParametrosSistema ps) { // Cobros vencidos horaInicioCobrosVencidos = LocalTime.of(19, 00, 00); // Cobros por vencer this.perioricidadPorVencerA = ps.getFrecuenciaAvisoCategoriaA(); this.perioricidadPorVencerB = ps.getFrecuenciaAvisoCategoriaB(); this.perioricidadPorVencerC = ps.getFrecuenciaAvisoCategoriaC(); this.perioricidadPorVencerD = ps.getFrecuenciaAvisoCategoriaD(); this.diasAntesCobroPorVencer = 10; // Contrato vencido this.perioricidadContratoVencido = ps.getPeriodicidadEnDias_DiasAntesVencimientoContrato(); this.diasAntesContratoVencido = ps.getDiasAntesVencimientoContrato(); // contrato por vencer this.mesesAntesVencimientoContrato = ps.getMesesAntesVencimientoContrato(); this.perioricidadEnDiasVencimientoContrato = ps.getPeriodicidadEnDias_MesesAntesVencimientoContrato(); } public void setNotificacion(Job notificacion) { this.notificacion = notificacion; } public void setMailSender(Job mailSender) { this.mailSender = mailSender; } public void encender() { try { if (sc != null && !sc.isShutdown()) { sc.shutdown(); // bajamos en planificador viejo, si existe. } sc = StdSchedulerFactory.getDefaultScheduler(); sc.start(); } catch ( SchedulerException e) { e.printStackTrace(); } } public void apagar() { try { if (sc.isStarted()) try { sc.shutdown(); } catch (SchedulerException e) { e.printStackTrace(); } } catch (SchedulerException e) { e.printStackTrace(); } } public void updateTriggersJobCita(List<Cita> citas) { citas.forEach(cita -> this.removeJobCita(cita)); citas.forEach(cita -> this.addJobCita(cita)); } public boolean notificacionVencida(Integer horasAntesCita, LocalDateTime inicioCita){ LocalDateTime now=LocalDateTime.now(); System.out.println("Recordatorio: "+inicioCita.minusHours(horasAntesCita)+ " es Antes que ahora? ("+now+"\n"); if(inicioCita.minusHours(horasAntesCita).isBefore(now)) System.out.println("VENCIDA!!!\n"); else{ System.out.println("NO VENCIDA!!!\n"); } return inicioCita.minusHours(horasAntesCita).isBefore(now); } public void addJobCita(Cita cita) { if (cita.getId() != null) { if(!notificacionVencida(horasAntesCita1,cita.getFechaInicio())) agregarJobNotificacionCita(cita, horasAntesCita1, 1); if(!notificacionVencida(horasAntesCita2,cita.getFechaInicio())) agregarJobNotificacionCita(cita, horasAntesCita2, 2); } else throw new IllegalArgumentException("La cita debe estar persistida"); } public void addJobCita(Cita cita, Integer hsAntesRecordatorio1, Integer hsAntesRecordatorio2) { if (cita.getId() != null) { if(!notificacionVencida(hsAntesRecordatorio1,cita.getFechaInicio()) ) agregarJobNotificacionCita(cita, hsAntesRecordatorio1, 1); if(!notificacionVencida(hsAntesRecordatorio2,cita.getFechaInicio()) ) agregarJobNotificacionCita(cita, hsAntesRecordatorio2, 2); } else throw new IllegalArgumentException("La cita debe estar persistida"); } public boolean removeJobCita(Cita cita) { boolean ret = true; try { if (cita.getId() != null) { if(!notificacionVencida(horasAntesCita1,cita.getFechaInicio()) ){ ret = sc.unscheduleJob(TriggerKey.triggerKey(cita.getTriggerKey() + "-1")); } if(!notificacionVencida(horasAntesCita1,cita.getFechaInicio())) { ret =ret&&sc.unscheduleJob(TriggerKey.triggerKey(cita.getTriggerKey() + "-2")); } return ret; } else{ throw new IllegalArgumentException("La cita debe estar persistida"); } } catch (Exception e) { e.printStackTrace(); } return ret; } public void updateTriggersJobCobrosVencidos(List<Cobro> cobros) { cobros.forEach(cobro -> this.removeJobCobroVencido(cobro)); cobros.forEach(cobro -> this.addJobCobroVencido(cobro)); } public void addJobsCobrosVencidos(ContratoAlquiler c) { c.getCobros().forEach(c1 -> this.addJobCobroVencido(c1)); System.out.println("[INFO] Agregados jobs de cobros vencidos correctamente"); } public void addJobCobroVencido(Cobro cobro) { if (cobro.getId() != null) { agregarJobNotificacionCobroVencido(cobro, 1); agregarJobMailCobroPorVencido(cobro, 2); System.out.println("[INFO] Agregados jobs de cobros vencidos correctamente"); } else throw new IllegalArgumentException("El Cobro debe estar persistida"); } public boolean removeJobCobroVencido(Cobro cobro) { boolean ret = true; ; try { if (cobro.getId() != null) { ret = ret && sc.unscheduleJob(TriggerKey.triggerKey(cobro.getTriggerKey() + "-1")); ret = ret && sc.unscheduleJob(TriggerKey.triggerKey(cobro.getTriggerKey() + "-2")); System.out.println("[INFO] Eliminados jobs de cobros vencidos correctamente"); } else throw new IllegalArgumentException("El Cobro debe estar persistida"); } catch (Exception e) { e.printStackTrace(); } return ret; } public void updateTriggersJobCobrosPorVencer(List<Cobro> cobros) { cobros.forEach(cobro -> this.removeJobCobroPorVencer(cobro)); cobros.forEach(cobro -> this.addJobCobroPorVencer(cobro)); } public void addJobsCobrosPorVencer(ContratoAlquiler ca) { ca.getCobros().forEach(cob -> { if (cob.getFechaDeVencimiento().compareTo(LocalDate.now()) > 0) { addJobCobroPorVencer(cob); } }); System.out.println("[INFO] Agregados jobs de cobros por vencer correctamente"); } public void addJobCobroPorVencer(Cobro cobro) { if (cobro.getId() != null) { agregarJobMailCobroPorVencer(cobro, diasAntesCobroPorVencer, 3); System.out.println("[INFO] Agregados jobs de cobros por vencer correctamente"); } else throw new IllegalArgumentException("El Cobro debe estar persistida"); } public boolean removeJobCobroPorVencer(Cobro cobro) { boolean ret = true; ; try { if (cobro.getId() != null) { ret = ret && sc.unscheduleJob(TriggerKey.triggerKey(cobro.getTriggerKey() + "-3")); System.out.println("[INFO] Eliminados jobs de cobros por vencer correctamente"); } else throw new IllegalArgumentException("El Cobro debe estar persistida"); } catch (Exception e) { e.printStackTrace(); } return ret; } public void updateTriggersJobAlquileresPorVencer(List<ContratoAlquiler> alquileres) { alquileres.forEach(alquiler -> this.removeJobAlquilerPorVencer(alquiler)); alquileres.forEach(alquiler -> this.addJobAlquilerPorVencer(alquiler)); } public void addJobAlquilerPorVencer(ContratoAlquiler contrato) { if (contrato.getId() != null && tieneVencimientoFuturo(contrato)) { agregarJobMailAlquilerPorVencer(contrato, mesesAntesVencimientoContrato, 1); agregarJobNotificacionAlquilerPorVencer(contrato, mesesAntesVencimientoContrato, 2); System.out.println("[INFO] Alquiler por vencer agregado a quartz correctamente"); } } public boolean removeJobAlquilerPorVencer(ContratoAlquiler contrato) { boolean ret = true; try { if (contrato.getId() != null) { ret = ret && sc.unscheduleJob(TriggerKey.triggerKey(contrato.getTriggerKey() + "-1")); ret = ret && sc.unscheduleJob(TriggerKey.triggerKey(contrato.getTriggerKey() + "-2")); System.out.println("[INFO] Alquiler por vencer borrado de quartz correctamente"); } else throw new IllegalArgumentException("El contrato debe estar persistida"); } catch (Exception e) { e.printStackTrace(); } return ret; } public void updateTriggersJobAlquileresVencidos(List<ContratoAlquiler> alquileres) { alquileres.forEach(alquiler -> this.removeJobAlquilerVencido(alquiler)); alquileres.forEach(alquiler -> this.addJobAlquilerVencido(alquiler)); } public void addJobAlquilerVencido(ContratoAlquiler contrato) { if (contrato.getId() != null) { agregarJobMailAlquilerVencido(contrato, 3); System.out.println("[INFO] Alquiler vencido agregado a quartz correctamente"); } } public boolean removeJobAlquilerVencido(ContratoAlquiler contrato) { boolean ret = true; try { if (contrato.getId() != null) { ret = ret && sc.unscheduleJob(TriggerKey.triggerKey(contrato.getTriggerKey() + "-3")); System.out.println("[INFO] Alquiler vencido borrado de quartz correctamente"); } else throw new IllegalArgumentException("El contrato debe estar persistida"); } catch (Exception e) { e.printStackTrace(); } return ret; } public void agregarJobNotificacionSistema(String titulo, String mensaje, String username, LocalDateTime fechaInicio, LocalDateTime fechaFin, String perioricidad, String id) { try { String horan = "0 " + fechaInicio.getMinute() + " " + fechaInicio.getHour(); horan = horan + " " + perioricidad; horan = horan + " * ? *"; JobDetail j1 = JobBuilder.newJob(notificacion.getClass()) .usingJobData("mensaje", mensaje) .usingJobData("titulo", titulo) .usingJobData("idCita", id) .usingJobData("usuario", username) .build(); j1.getKey(); Date startDate = Date.from(fechaInicio.minusMinutes(1).atZone(ZoneId.systemDefault()).toInstant()); Date endDate = Date.from(fechaFin.plusMinutes(1).atZone(ZoneId.systemDefault()).toInstant()); Trigger t = TriggerBuilder.newTrigger().withIdentity(id) .startAt(startDate) .withSchedule(CronScheduleBuilder.cronSchedule(horan)) .endAt(endDate) .build(); sc.scheduleJob(j1, t); } catch (SchedulerException e) { e.printStackTrace(); } } public void agregarJobMail(String encabezado, String mensaje, String destinatario, LocalDateTime fechaInicio, LocalDateTime fechaFin, String perioricidad, String id) { try { String horan = "0 " + fechaInicio.getMinute() + " " + fechaInicio.getHour(); horan = horan + " " + perioricidad; horan = horan + " * ? *"; JobDetail j1 = JobBuilder.newJob(mailSender.getClass()) .usingJobData("mensaje", mensaje) .usingJobData("encabezado", encabezado) .usingJobData("destinatario", destinatario) .build(); j1.getKey(); Date startDate = Date.from(fechaInicio.minusMinutes(1).atZone(ZoneId.systemDefault()).toInstant()); Date endDate = Date.from(fechaFin.plusMinutes(1).atZone(ZoneId.systemDefault()).toInstant()); Trigger t = TriggerBuilder.newTrigger().withIdentity(id) .startAt(startDate) .withSchedule(CronScheduleBuilder.cronSchedule(horan)) .endAt(endDate) .build(); sc.scheduleJob(j1, t); } catch (SchedulerException e) { e.printStackTrace(); } } private void agregarJobNotificacionCita(Cita c, Integer horas, Integer nro) { LocalDateTime fechaInicio = c.getFechaInicio(); System.out.println("Fecha" + fechaInicio); fechaInicio = fechaInicio.minusHours(horas); LocalDateTime fechaFin = c.getFechaInicio(); String perioricidad = "1/1"; String triggerKey = c.getTriggerKey() + "-" + nro.toString(); String username = c.getEmpleado(); agregarJobNotificacionSistema(c.getTitulo(), c.getMessage(), username, fechaInicio, fechaFin, perioricidad, triggerKey); } private void agregarJobNotificacionCobroVencido(Cobro c, Integer nro) { LocalDateTime fechaInicio = LocalDateTime.of(c.getFechaDeVencimiento(), LocalTime.now().plusMinutes(1)); LocalDateTime fechaFin = LocalDateTime.of(c.getFechaDeVencimiento(), LocalTime.now().plusMinutes(10)); String perioricidad = "1/1"; String triggerKey = c.getTriggerKey() + "-" + nro.toString(); String username = "broadcast"; agregarJobNotificacionSistema(c.getTitulo(), c.getMessage(), username, fechaInicio, fechaFin, perioricidad, triggerKey); } private void agregarJobMailCobroPorVencido(Cobro c, Integer nro) { LocalDateTime fechaInicio = LocalDateTime.of(c.getFechaDeVencimiento().plusDays(1), LocalTime.now().plusMinutes( 1)); LocalDateTime fechaFin = fechaInicio.plusYears(150); String dia = String.valueOf(fechaInicio.getDayOfMonth()); String perioricidad = dia + "/" + this.perioricidadSegunCalificacion(c); String triggerKey = c.getTriggerKey() + "-" + nro.toString(); ContratoAlquiler ca = (ContratoAlquiler) c.getContrato(); String titulo = "Pago vencido"; String texto = "Señor/a inquilino/a: " + ca.getInquilinoContrato().getPersona().toString() + " recuerde que el pago del alquiler del inmueble:"+ca.getInmueble().toString()+"\nVencio el dia: " + c.getFechaDeVencimiento() .format(new DateTimeFormatterBuilder().appendPattern("dd/MM/YYYY").toFormatter()).toString(); String mail = ca.getInquilinoContrato().getPersona().getMail(); agregarJobMail(titulo, texto, mail, fechaInicio, fechaFin, perioricidad, triggerKey); } private void agregarJobMailCobroPorVencer(Cobro c, Integer dias, Integer nro) { LocalDateTime fechaInicio = LocalDateTime.of(c.getFechaDeVencimiento(), LocalTime.now().plusMinutes(1)); LocalDateTime fechaFin = LocalDateTime.of(c.getFechaDeVencimiento(), LocalTime.now().plusMinutes(1)); fechaInicio = fechaInicio.minusDays(dias); fechaFin = fechaFin.minusDays(1); String dia=String.valueOf(fechaInicio.getDayOfMonth()); String perioricidad = dia+"/"+this.perioricidadSegunCalificacion(c); String triggerKey = c.getTriggerKey()+"-"+nro.toString(); ContratoAlquiler ca= (ContratoAlquiler) c.getContrato(); String titulo="Pago proximo a vencer"; String texto="Señor/ra inquilino/a: "+ca.getInquilinoContrato().getPersona().toString()+" recuerde que el pago del alquiler del inmueble: \n" +ca.getInmueble().toString() + "\nvence el dia: " +c.getFechaDeVencimiento() .format(new DateTimeFormatterBuilder().appendPattern("dd/MM/YYYY").toFormatter()).toString(); String mail=ca.getInquilinoContrato().getPersona().getMail(); agregarJobMail(titulo, texto, mail, fechaInicio, fechaFin, perioricidad, triggerKey); } private void agregarJobMailAlquilerPorVencer(ContratoAlquiler c, Integer meses, Integer key) { LocalDateTime fechaInicio = LocalDateTime.of(c.getFechaIngreso().plusMonths(c.getDuracionContrato() .getDuracion()), LocalTime.now().plusMinutes(1)); LocalDateTime fechaFin = LocalDateTime.of(c.getFechaIngreso().plusMonths(c.getDuracionContrato().getDuracion()), LocalTime.now().plusMinutes(10)); fechaInicio = fechaInicio.minusMonths(meses); String triggerKey = c.getTriggerKey() + "-" + key.toString(); String dia = String.valueOf(fechaInicio.getDayOfMonth()); String perioricidad = dia + "/" + this.perioricidadEnDiasVencimientoContrato.toString(); String mensaje = "Señor/ra inquilino/a "+c.getInquilinoContrato().getPersona().toString() +".\nEl contrato de alquiler del inmueble:\n" +c.getInmueble().toString()+"\n" +"se vence el dia: " + c.getFechaIngreso().plusMonths(c.getDuracionContrato().getDuracion()) .format(new DateTimeFormatterBuilder().appendPattern("dd/MM/YYYY").toFormatter()).toString() + "." + "\nRecuerde que el inmueble debe ser " + "entregado en condiciones"; agregarJobMail("Vencimiento de contrato", mensaje, c.getInquilinoContrato().getPersona().getMail(), fechaInicio, fechaFin, perioricidad, triggerKey); } private void agregarJobNotificacionAlquilerPorVencer(ContratoAlquiler c, Integer meses, Integer key) { LocalDateTime fechaInicio = LocalDateTime.of(c.getFechaIngreso().plusMonths(c.getDuracionContrato() .getDuracion()), LocalTime.now().plusMinutes(1)); LocalDateTime fechaFin = LocalDateTime.of(c.getFechaIngreso().plusMonths(c.getDuracionContrato().getDuracion()), LocalTime.now().plusMinutes(10)); fechaInicio = fechaInicio.minusMonths(meses); String triggerKey = c.getTriggerKey() + "-" + key.toString(); String dia = String.valueOf(fechaInicio.getDayOfMonth()); String perioricidad = dia + "/" + this.perioricidadEnDiasVencimientoContrato.toString(); String username = "broadcast"; agregarJobNotificacionSistema(c.getTitulo(), c.getMessage(), username, fechaInicio, fechaFin, perioricidad, triggerKey); } private void agregarJobMailAlquilerVencido(ContratoAlquiler c, Integer key) { LocalDateTime fechaInicio = LocalDateTime.of(c.getFechaIngreso().plusMonths(c.getDuracionContrato() .getDuracion()), LocalTime.now().plusMinutes(1)); fechaInicio = fechaInicio.minusDays(this.diasAntesContratoVencido); LocalDateTime fechaFin = LocalDateTime.of(c.getFechaIngreso().plusMonths(c.getDuracionContrato().getDuracion()), LocalTime.now().plusMinutes(10)); String triggerKey = c.getTriggerKey() + "-" + key.toString(); String dia = String.valueOf(fechaInicio.getDayOfMonth()); String perioricidad = dia + "/" + this.perioricidadContratoVencido; String mensaje = "Señor/ra inquilino/a "+c.getInquilinoContrato().getPersona().toString() +".\nEl contrato de alquiler del inmueble:\n" +c.getInmueble().toString()+"\n" +"se vence el dia: " + c.getFechaIngreso().plusMonths(c.getDuracionContrato().getDuracion()) .format(new DateTimeFormatterBuilder().appendPattern("dd/MM/YYYY").toFormatter()).toString() + "." + "\nRecuerde que el inmueble debe ser " + "entregado en condiciones"; agregarJobMail("Vencimiento de contrato", mensaje, c.getInquilinoContrato().getPersona().getMail(), fechaInicio, fechaFin, perioricidad, triggerKey); } public LocalTime getHoraInicioCobrosVencidos() { return horaInicioCobrosVencidos; } public void setHoraInicioCobrosVencidos(LocalTime horaInicioCobrosVencidos) { this.horaInicioCobrosVencidos = horaInicioCobrosVencidos; } private boolean tieneVencimientoFuturo(ContratoAlquiler ca) { return ca.getFechaIngreso().plusMonths(ca.getDuracionContrato().getDuracion()) .compareTo(LocalDate.now()) > 0; } private Calificacion getCalificacionInquilino(Cobro c) { ContratoAlquiler ca = (ContratoAlquiler) c.getContrato(); Calificacion ret = Calificacion.C; if (ca.getInquilinoContrato().getCalificacion() != null) ret = ca.getInquilinoContrato().getCalificacion(); return ret; } private String perioricidadSegunCalificacion(Cobro c) { Integer ret = 0; Calificacion cal = getCalificacionInquilino(c); if (cal.equals(Calificacion.A)) { ret = this.perioricidadPorVencerA; } else if (cal.equals(Calificacion.B)) { ret = this.perioricidadPorVencerB; } else if (cal.equals(Calificacion.C)) { ret = this.perioricidadPorVencerC; } else if (cal.equals(Calificacion.D)) { ret = this.perioricidadPorVencerD; } return ret.toString(); } }
gpl-3.0
mxm2005/mxmTxtReader
src/com/example/mxmtxtreader/BookActivity.java
3384
package com.example.mxmtxtreader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import com.example.mxmtxtreader.fragment.YesNoDialog; import com.example.mxmtxtreader.file.FileService; import com.example.mxmtxtreader.util.iniconfig; import android.app.Activity; import android.app.DialogFragment; import android.content.Intent; import android.content.res.Resources.NotFoundException; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; public class BookActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_book); } @Override protected void onStart() { super.onStart(); ListView lv_books = (ListView) findViewById(R.id.lv_books); LoadBooks(lv_books); lv_books.setOnItemClickListener(new myOnItemClickListener()); } private class myOnItemClickListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // String text = parent.getItemAtPosition(position)+""; // Log.i("tag",text); TextView vName = (TextView) v.findViewById(R.id.book_name); TextView vAddr = (TextView) v.findViewById(R.id.book_addr); Log.i("tag", vName.getText().toString() + "--" + vAddr.getText().toString()); Intent inte = new Intent(); inte.setClass(BookActivity.this, ReadingActivity.class); Bundle bundle = new Bundle(); bundle.putString("book_name", vName.getText().toString()); bundle.putString("book_addr", vAddr.getText().toString()); inte.putExtras(bundle); startActivity(inte); } } //load book list private void LoadBooks(ListView lv) { // read init data ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); HashMap<String, String> map1 = new HashMap<String, String>(); ArrayList<String> lstBook = new ArrayList<String>(); String path=""; ArrayList<String> lstIni = new ArrayList<String>(); try { lstIni = FileService.readList(this.getResources().openRawResource( R.drawable.init)); path = iniconfig.getInstance().GetItem(lstIni, "book_list_path"); path = getFilesDir() + File.separator + path;// Environment.getDataDirectory() File f = new File(path); if (!f.exists()) f.createNewFile(); FileInputStream sr = new FileInputStream(f); lstBook = FileService.readList(sr); } catch (Exception ex) { Log.i("exception", ex.getMessage() + ex.getCause()); } for (int i = 0; i < lstBook.size(); i++) { if(lstBook.get(i).length()==0) continue; map1 = new HashMap<String, String>(); String[] a = lstBook.get(i).split(","); map1.put("book_name", a[0]); map1.put("book_addr", a[1]); list.add(map1); } SimpleAdapter listAdapter = new SimpleAdapter(this, list, R.layout.book_item, new String[] { "book_name", "book_addr" }, new int[] { R.id.book_name, R.id.book_addr }); lv.setAdapter(listAdapter); } }
gpl-3.0
databrary/datavyu
src/main/java/org/datavyu/util/FileFilters/FrameCsvFilter.java
1502
/** * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.datavyu.util.FileFilters; import javax.swing.filechooser.FileFilter; import java.io.File; /** * A file filter for CSV files. */ public final class FrameCsvFilter extends FileFilter { public static final FrameCsvFilter INSTANCE = new FrameCsvFilter(); private FrameCsvFilter() { } /** * @return The description of the file filter. */ @Override public String getDescription() { return "Frame-by-frame CSV file (*.csv)"; } /** * Determines if the file filter will accept the supplied file. * * @param file The file to check if this file will accept. * @return true if the file is to be accepted, false otherwise. */ @Override public boolean accept(final File file) { return (file.getName().endsWith(".csv") || file.isDirectory()); } }
gpl-3.0
Captain-Chaos/WorldPainter
WorldPainter/WPDynmapPreviewer/src/main/java/org/pepsoft/worldpainter/dynmap/WPDynmapWorld.java
4683
package org.pepsoft.worldpainter.dynmap; import org.dynmap.DynmapChunk; import org.dynmap.DynmapLocation; import org.dynmap.DynmapWorld; import org.dynmap.utils.MapChunkCache; import org.pepsoft.minecraft.JavaLevel; import org.pepsoft.worldpainter.Dimension; import org.pepsoft.worldpainter.*; import org.pepsoft.worldpainter.exporting.JavaMinecraftWorld; import org.pepsoft.worldpainter.exporting.MinecraftWorld; import javax.vecmath.Point3i; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.List; /** * A {@link DynmapWorld} implementation which wraps a {@link MinecraftWorld} for * use with the dynmap API. * * <p>Use the static factory methods to obtain correctly configured instances * for various kinds of {@code MinecraftWorld} * * <p>Created by Pepijn Schmitz on 05-06-15. */ public class WPDynmapWorld extends DynmapWorld { private WPDynmapWorld(MinecraftWorld world, String name, int waterLevel) { super(name, world.getMaxHeight(), waterLevel); this.world = world; chunkCache = new WPMapChunkCache(this, world); } @Override public boolean isNether() { return dim == Constants.DIM_NETHER || dim == Constants.DIM_NETHER_CEILING; } @Override public DynmapLocation getSpawnLocation() { return spawnLocation; } @Override public long getTime() { return 10000; // Noon } @Override public boolean hasStorm() { return false; } @Override public boolean isThundering() { return false; } @Override public boolean isLoaded() { return false; } @Override public void setWorldUnloaded() { // Do nothing } @Override public int getLightLevel(int x, int y, int z) { return world.getBlockLightLevel(x, z, y); } @Override public int getHighestBlockYAt(int x, int z) { return world.getHighestNonAirBlock(x, z); } @Override public boolean canGetSkyLightLevel() { return true; } @Override public int getSkyLightLevel(int x, int y, int z) { return world.getSkyLightLevel(x, z, y); } @Override public String getEnvironment() { switch (dim) { case Constants.DIM_NORMAL: case Constants.DIM_NORMAL_CEILING: return "normal"; case Constants.DIM_END: case Constants.DIM_END_CEILING: return "the_end"; case Constants.DIM_NETHER: case Constants.DIM_NETHER_CEILING: return "nether"; default: throw new IllegalArgumentException("Dimension " + dim + " not supported"); } } @Override public MapChunkCache getChunkCache(List<DynmapChunk> chunks) { return chunkCache; } public static WPDynmapWorld forDimension(MinecraftWorld minecraftWorld, Dimension dimension) { int waterLevel; TileFactory tileFactory = dimension.getTileFactory(); if (tileFactory instanceof HeightMapTileFactory) { waterLevel = ((HeightMapTileFactory) tileFactory).getWaterHeight(); } else { waterLevel = 62; } World2 wpWorld = dimension.getWorld(); Point spawnPoint = wpWorld.getSpawnPoint(); return forMinecraftWorld(minecraftWorld, wpWorld.getName() + " - " + dimension.getName(), dimension.getDim(), waterLevel, new Point3i(spawnPoint.x, spawnPoint.y, dimension.getIntHeightAt(spawnPoint.x, spawnPoint.y))); } public static WPDynmapWorld forMinecraftMap(File worldDir, int dim) throws IOException { File levelDatFile = new File(worldDir, "level.dat"); JavaLevel level = JavaLevel.load(levelDatFile); return forMinecraftWorld(new JavaMinecraftWorld(worldDir, dim, level.getMaxHeight(), level.getVersion() == org.pepsoft.minecraft.Constants.VERSION_MCREGION ? DefaultPlugin.JAVA_MCREGION : DefaultPlugin.JAVA_ANVIL, true, 256), level.getName(), dim, 62, new Point3i(level.getSpawnX(), level.getSpawnZ(), level.getSpawnY())); } public static WPDynmapWorld forMinecraftWorld(MinecraftWorld minecraftWorld, String name, int dim, int waterLevel, Point3i spawnPoint) { WPDynmapWorld world = new WPDynmapWorld(minecraftWorld, name, waterLevel); world.dim = dim; if (spawnPoint != null) { world.spawnLocation = new DynmapLocation(name, spawnPoint.x, spawnPoint.z, spawnPoint.y); } return world; } private final MinecraftWorld world; private final WPMapChunkCache chunkCache; private int dim; private DynmapLocation spawnLocation; }
gpl-3.0
guiguilechat/EveOnline
model/sde/SDE-Types/src/generated/java/fr/guiguilechat/jcelechat/model/sde/types/module/MissileLauncherBomb.java
8820
package fr.guiguilechat.jcelechat.model.sde.types.module; import java.io.InputStreamReader; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import fr.guiguilechat.jcelechat.model.sde.Attribute; import fr.guiguilechat.jcelechat.model.sde.IMetaCategory; import fr.guiguilechat.jcelechat.model.sde.IMetaGroup; import fr.guiguilechat.jcelechat.model.sde.annotations.DefaultDoubleValue; import fr.guiguilechat.jcelechat.model.sde.annotations.DefaultIntValue; import fr.guiguilechat.jcelechat.model.sde.annotations.HighIsGood; import fr.guiguilechat.jcelechat.model.sde.annotations.Stackable; import fr.guiguilechat.jcelechat.model.sde.types.Module; import org.yaml.snakeyaml.Yaml; public class MissileLauncherBomb extends Module { /** * */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(0) public int CanFitShipGroup01; /** * One of the groups of charge this launcher can be loaded with. */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(0) public int ChargeGroup1; /** * One of the groups of charge this launcher can be loaded with. */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(0) public int ChargeGroup2; /** * One of the groups of charge this launcher can be loaded with. */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(0) public int ChargeGroup3; /** * Number of charges consumed per activation */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(1) public int ChargeRate; /** * CPU need of module */ @HighIsGood(false) @Stackable(true) @DefaultDoubleValue(0.0) public double Cpu; /** * Modules with this attribute set to 1 can not be used in deadspace. Modules with this attribute set to 2 can not be used in deadspace even where "disableModuleBlocking" is selected */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(0) public int DeadspaceUnsafe; /** * If set on a charge or module type, will prevent it from being activated in empire space. */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(0) public int DisallowInEmpireSpace; /** * If set, this module cannot be activated and made to autorepeat. */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(0) public int DisallowRepeatingActivation; /** * Maximum modules of same group that can be activated at same time, 0 = no limit, 1 = 1 */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(0) public int MaxGroupActive; /** * */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(0) public int MaxGroupFitted; /** * Authoring has been moved to FSD * The ranking of the module within its tech level */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(0) public int MetaLevel; /** * */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(0) public int MinVelocityActivationLimit; /** * Amount of time that has to be waited after the deactivation of this module until it can be reactivated. */ @HighIsGood(false) @Stackable(true) @DefaultIntValue(0) public int ModuleReactivationDelay; /** * current power need */ @HighIsGood(false) @Stackable(true) @DefaultIntValue(0) public int Power; /** * reload time (ms) */ @HighIsGood(false) @Stackable(true) @DefaultDoubleValue(10000.0) public double ReloadTime; /** * The type ID of the skill that is required. */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(0) public int RequiredSkill1; /** * Required skill level for skill 1 */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(0) public int RequiredSkill1Level; /** * */ @HighIsGood(false) @Stackable(true) @DefaultIntValue(0) public int SignatureRadiusAdd; /** * The number of slots this module requires. Only used for launchers, bays and turrets. */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(1) public int Slots; /** * Time in milliseconds between possible activations */ @HighIsGood(false) @Stackable(false) @DefaultIntValue(0) public int Speed; /** * Authoring has been moved to FSD * Tech level of an item */ @HighIsGood(true) @Stackable(true) @DefaultIntValue(1) public int TechLevel; /** * The value of this attribute is a graphicsID which controls the color scheme of this type. It is used to apply said color scheme to items of other types whose gfx representation is tied in with the attribute holder. Example: Turrets on ships. */ @HighIsGood(false) @Stackable(false) @DefaultIntValue(0) public int TypeColorScheme; public static final MissileLauncherBomb.MetaGroup METAGROUP = new MissileLauncherBomb.MetaGroup(); @Override public Number attribute(Attribute attribute) { switch (attribute.getId()) { case 1298 : { return CanFitShipGroup01; } case 604 : { return ChargeGroup1; } case 605 : { return ChargeGroup2; } case 606 : { return ChargeGroup3; } case 56 : { return ChargeRate; } case 50 : { return Cpu; } case 801 : { return DeadspaceUnsafe; } case 1074 : { return DisallowInEmpireSpace; } case 1014 : { return DisallowRepeatingActivation; } case 763 : { return MaxGroupActive; } case 1544 : { return MaxGroupFitted; } case 633 : { return MetaLevel; } case 2608 : { return MinVelocityActivationLimit; } case 669 : { return ModuleReactivationDelay; } case 30 : { return Power; } case 1795 : { return ReloadTime; } case 182 : { return RequiredSkill1; } case 277 : { return RequiredSkill1Level; } case 983 : { return SignatureRadiusAdd; } case 47 : { return Slots; } case 51 : { return Speed; } case 422 : { return TechLevel; } case 1768 : { return TypeColorScheme; } default: { return super.attribute((attribute)); } } } @Override public IMetaGroup<MissileLauncherBomb> getGroup() { return METAGROUP; } public static class MetaGroup implements IMetaGroup<MissileLauncherBomb> { public static final String RESOURCE_PATH = "SDE/types/module/MissileLauncherBomb.yaml"; private Map<String, MissileLauncherBomb> cache = (null); @Override public IMetaCategory<? super MissileLauncherBomb> category() { return Module.METACAT; } @Override public int getGroupId() { return 862; } @Override public String getName() { return "MissileLauncherBomb"; } @Override public synchronized Map<String, MissileLauncherBomb> load() { if (cache == null) { try(final InputStreamReader reader = new InputStreamReader(MissileLauncherBomb.MetaGroup.class.getClassLoader().getResourceAsStream((RESOURCE_PATH)))) { cache = new Yaml().loadAs(reader, (Container.class)).types; } catch (final Exception exception) { throw new UnsupportedOperationException("catch this", exception); } } return Collections.unmodifiableMap(cache); } private static class Container { public LinkedHashMap<String, MissileLauncherBomb> types; } } }
gpl-3.0
gameinbucket/space-obelisk
source/math/MathUtil.java
4068
package com.gameinbucket.math; public abstract class MathUtil { //private static long m_w = 521288629; //private static long m_z = 362436069; //private static final double magic = 1.0 / (4294967296.0 + 2.0); //4294967296 = 2 ^ 32 private MathUtil() { } /*static unsigned long next = 1; int myrand() { next = next * 1103515245 + 12345; return((unsigned)(next/65536) % 32768); } public static void set_random_seed(long w) { if (w != 0) m_w = w; } public static void set_random_seeds(long w, long z) { if (w != 0) m_w = w; if (z != 0) m_z = z; } public static void set_random_seeds_system_time() { long x = System.currentTimeMillis(); set_random_seeds(x >> 16, x % 4294967296L); } public static double random_double(int n) { n = (n >> 13) ^ n; int nn = (n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff; return 1.0 - ((double)nn / 1073741824.0); } public static long random_long() { m_z = 36969 * (m_z & 65535) + (m_z >> 16); m_w = 18000 * (m_w & 65535) + (m_w >> 16); return (m_z << 16) + m_w; } public static float random_float() { long u = random_long(); return (float)((u + 1.0) * magic); }*/ public static float average(float a, float b) { return (a + b) / 2; } public static float saturate(float a) { if (a < 0) return 0; else if (a > 1) return 1; return a; } public static float lerp(float a, float b, float w) { return (a + (b - a) * w); } public static float smoothstep(float a, float b, float w) { w = saturate((w - a) / (b - a)); return w * w * (3 - 2 * w); } public static float radian(float degree) { return degree * 0.017453292519943f; } public static float degree(float radian) { float degree = radian * 57.29577951308232f; while (degree >= 360) degree -= 360; while (degree < 0) degree += 360; return degree; } /*public static final float sin(float rad) { return sin[(int) (rad * radToIndex) & SIN_MASK]; } public static final float cos(float rad) { return cos[(int) (rad * radToIndex) & SIN_MASK]; } public static final float sinDeg(float deg) { return sin[(int) (deg * degToIndex) & SIN_MASK]; } public static final float cosDeg(float deg) { return cos[(int) (deg * degToIndex) & SIN_MASK]; } public static final int FIXED_POINT = 16; public static final int ONE = 1 << FIXED_POINT; public static int mul(int a, int b) { return (int) ((long) a * (long) b >> FIXED_POINT); } public static int toFix( double val ) { return (int) (val * ONE); } public static int intVal( int fix ) { return fix >> FIXED_POINT; } public static double doubleVal( int fix ) { return ((double) fix) / ONE; } private static final float RAD,DEG; private static final int SIN_BITS,SIN_MASK,SIN_COUNT; private static final float radFull,radToIndex; private static final float degFull,degToIndex; private static final float[] sin, cos; static { RAD = (float) Math.PI / 180.0f; DEG = 180.0f / (float) Math.PI; SIN_BITS = 12; SIN_MASK = ~(-1 << SIN_BITS); SIN_COUNT = SIN_MASK + 1; radFull = (float) (Math.PI * 2.0); degFull = (float) (360.0); radToIndex = SIN_COUNT / radFull; degToIndex = SIN_COUNT / degFull; sin = new float[SIN_COUNT]; cos = new float[SIN_COUNT]; for (int i = 0; i < SIN_COUNT; i++) { sin[i] = (float) Math.sin((i + 0.5f) / SIN_COUNT * radFull); cos[i] = (float) Math.cos((i + 0.5f) / SIN_COUNT * radFull); } // Four cardinal directions (credits: Nate) for (int i = 0; i < 360; i += 90) { sin[(int)(i * degToIndex) & SIN_MASK] = (float)Math.sin(i * Math.PI / 180.0); cos[(int)(i * degToIndex) & SIN_MASK] = (float)Math.cos(i * Math.PI / 180.0); } } */ public static void print(String t) { android.util.Log.e("print", t); } }
gpl-3.0
grwlf/vsim
tr/com/prosoft/vhdl/ir/IRAfter.java
1049
package com.prosoft.vhdl.ir; public class IRAfter extends IROper { public IRAfter( IROper value, IROper time ) { setChild(0, value); setChild(1, time); setBegin(value.getBegin()); setEnd(time.getEnd()); } @Override public IROper dup() { IRAfter res = new IRAfter(getValue().dup(), getTime().dup()); res.dupChildrenAndCoordAndType(this); return res; } public IROper getValue() { return getChild(0); } public IROper getTime() { return getChild(1); } @Override public IROperKind getKind() { return IROperKind.AFTER; } @Override public boolean isEqualTo(IROper other) { return defaultIsEqualTo(other); } @Override protected boolean requiresValuesAtChildren() { return true; } @Override public void semanticCheck(IRErrorFactory err) throws CompilerError { getTime().setType(err.parser.getTimeType()); getTime().semanticCheck(err); getValue().setTypeIfNull(getType()); getValue().semanticCheck(err); setType(getValue().getType()); } }
gpl-3.0
PiLogic/PlotSquared
src/main/java/com/intellectualcrafters/plot/commands/Done.java
4752
//////////////////////////////////////////////////////////////////////////////////////////////////// // PlotSquared - A plot manager and world generator for the Bukkit API / // Copyright (c) 2014 IntellectualSites/IntellectualCrafters / // / // This program is free software; you can redistribute it and/or modify / // it under the terms of the GNU General Public License as published by / // the Free Software Foundation; either version 3 of the License, or / // (at your option) any later version. / // / // This program 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 General Public License for more details. / // / // You should have received a copy of the GNU General Public License / // along with this program; if not, write to the Free Software Foundation, / // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / // / // You can contact us via: support@intellectualsites.com / //////////////////////////////////////////////////////////////////////////////////////////////////// package com.intellectualcrafters.plot.commands; import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.flag.Flag; import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.generator.HybridUtils; import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.PlotAnalysis; import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.util.BlockManager; import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.UUIDHandler; import com.plotsquared.general.commands.CommandDeclaration; @CommandDeclaration( command = "done", aliases = {"submit"}, description = "Mark a plot as done", permission = "plots.done", category = CommandCategory.ACTIONS, requiredType = RequiredType.NONE ) public class Done extends SubCommand { @Override public boolean onCommand(final PlotPlayer plr, final String[] args) { final Location loc = plr.getLocation(); final Plot plot = MainUtil.getPlot(loc); if (plot == null || !plot.hasOwner()) { return !sendMessage(plr, C.NOT_IN_PLOT); } if ((!plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.done")) { MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); return false; } if (plot.getSettings().flags.containsKey("done")) { MainUtil.sendMessage(plr, C.DONE_ALREADY_DONE); return false; } if (MainUtil.runners.containsKey(plot)) { MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); return false; } MainUtil.runners.put(plot, 1); MainUtil.sendMessage(plr, C.GENERATING_LINK); HybridUtils.manager.analyzePlot(plot, new RunnableVal<PlotAnalysis>() { @Override public void run() { MainUtil.runners.remove(plot); if (value == null || value.getComplexity() >= Settings.CLEAR_THRESHOLD) { Flag flag = new Flag(FlagManager.getFlag("done"), (System.currentTimeMillis() / 1000)); FlagManager.addPlotFlag(plot, flag); MainUtil.sendMessage(plr, C.DONE_SUCCESS); } else { MainUtil.sendMessage(plr, C.DONE_INSUFFICIENT_COMPLEXITY); } } }); return true; } }
gpl-3.0
LeoTremblay/activityinfo
server/src/main/java/org/activityinfo/legacy/shared/reports/model/typeadapter/CategoryAdapter.java
1619
package org.activityinfo.legacy.shared.reports.model.typeadapter; /* * #%L * ActivityInfo Server * %% * Copyright (C) 2009 - 2013 UNICEF * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ import org.activityinfo.legacy.shared.reports.content.DimensionCategory; import org.activityinfo.legacy.shared.reports.content.EntityCategory; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.adapters.XmlAdapter; /** * @author Alex Bertram */ public class CategoryAdapter extends XmlAdapter<CategoryAdapter.Category, DimensionCategory> { public static class Category { @XmlAttribute private Integer id; } @Override public DimensionCategory unmarshal(Category category) throws Exception { if (category.id != null) { return new EntityCategory(category.id); } return null; } @Override public Category marshal(DimensionCategory v) throws Exception { return null; } }
gpl-3.0
DivineH/DesignPatterns
行为型模式/备忘录模式/备忘录模式-封装/src/com/designPatterns/Memento/Originator.java
655
package com.designPatterns.Memento; //Ô­·¢Æ÷ public class Originator { private String state; //ÄÚ²¿Àà private class ConcreteMemento implements Memento { private String state; private ConcreteMemento(String state) { this.state = state; } private String getState(){ return this.state; } } public Memento createMemento() { return new ConcreteMemento(this.state); } public void restoreMemento(Memento memento) { setState(((ConcreteMemento)memento).getState()); } public void setState(String state) { this.state=state; } public String getState() { return this.state; } }
gpl-3.0
WavePropagation/org.macroing.wicked
src/main/org/macroing/wicked/swing/CheckBoxImpl.java
3749
/** * Copyright 2009 - 2014 Jörgen Lundgren * * This file is part of org.macroing.wicked. * * org.macroing.wicked 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. * * org.macroing.wicked 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 org.macroing.wicked. If not, see <http://www.gnu.org/licenses/>. */ package org.macroing.wicked.swing; import java.lang.reflect.Field;//TODO: Remove once done! import javax.swing.JCheckBox; import org.macroing.wicked.CheckBox; import org.macroing.wicked.Platform; final class CheckBoxImpl extends CheckBox { private final JCheckBox jCheckBox = ComponentUtilities.newJCheckBox(); public CheckBoxImpl(Platform platform, String id) { super(platform, id); } @Override public boolean isMovable() { return Boolean.class.cast(ComponentUtilities.getClientProperty(jCheckBox, ComponentUtilities.KEY_MOVABLE, false)); } @Override public boolean isResizable() { return Boolean.class.cast(ComponentUtilities.getClientProperty(jCheckBox, ComponentUtilities.KEY_RESIZABLE, false)); } @Override public boolean isSelected() { return ComponentUtilities.isSelected(jCheckBox); } @Override public boolean isVisible() { return ComponentUtilities.isVisible(jCheckBox); } @Override public CheckBox setLocation(final int x, final int y, long key) { if(authenticate(key)) { ComponentUtilities.setLocation(jCheckBox, x, y); Platform platform = Platform.getDefaultPlatform(); platform.updateComponentPin(this); } return this; } @Override public CheckBox setMovable(boolean isMovable, long key) { if(authenticate(key)) { ComponentUtilities.putClientProperty(jCheckBox, ComponentUtilities.KEY_MOVABLE, isMovable); } return this; } @Override public CheckBox setResizable(boolean isResizable, long key) { if(authenticate(key)) { ComponentUtilities.putClientProperty(jCheckBox, ComponentUtilities.KEY_RESIZABLE, isResizable); } return this; } @Override public CheckBox setSelected(boolean isSelected, long key) { if(authenticate(key)) { ComponentUtilities.setSelected(jCheckBox, isSelected); } return this; } @Override public CheckBox setSize(int width, int height, long key) { if(authenticate(key)) { ComponentUtilities.setSize(jCheckBox, width, height); Platform platform = Platform.getDefaultPlatform(); platform.updateComponentPin(this); } return this; } @Override public CheckBox setText(String text, long key) { if(authenticate(key)) { ComponentUtilities.setText(jCheckBox, text); } return this; } @Override public CheckBox setVisible(boolean isVisible, long key) { if(authenticate(key)) { ComponentUtilities.setVisible(jCheckBox, isVisible); } return this; } @Override public int getHeight() { return ComponentUtilities.getHeight(jCheckBox); } @Override public int getWidth() { return ComponentUtilities.getWidth(jCheckBox); } @Override public int getX() { return ComponentUtilities.getX(jCheckBox); } @Override public int getY() { return ComponentUtilities.getY(jCheckBox); } @Override public Object getComponentObject() { return jCheckBox; } @Override public String getText() { return ComponentUtilities.getText(jCheckBox); } }
gpl-3.0
nelsonsilva/MuVis
src/main/java/muvis/view/main/MuVisTreemapMouseActionListener.java
3708
/* * The GPLv3 licence : * ----------------- * Copyright (c) 2009 Ricardo Dias * * This file is part of MuVis. * * MuVis is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MuVis 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MuVis. If not, see <http://www.gnu.org/licenses/>. */ package muvis.view.main; import java.awt.event.MouseEvent; import java.util.ArrayList; import muvis.Messages; import muvis.view.MainViewsMouseAdapter; import muvis.view.main.actions.AddToPlaylistTreemapAction; import muvis.view.main.actions.FindNonSimilarElementsTreemapAction; import muvis.view.main.actions.FindSimilarElementsTreemapAction; import muvis.view.main.actions.PreviewTreemapAction; import muvis.view.main.actions.SimilarityTreemapAction; import net.bouthier.treemapSwing.TMView; /** * Main view Treemap mouse listener. Gives support to the main actions such as: * adding elements to playlist, using similarity filter or making a preview of * the selected elements. * @author Ricardo */ public class MuVisTreemapMouseActionListener extends MainViewsMouseAdapter { protected TMView view; protected MuVisTreemapNode nodeUnder; protected ArrayList<MuVisTreemapNode> selectedNodes; protected PreviewTreemapAction previewAction; protected AddToPlaylistTreemapAction addToPlaylistAction; protected SimilarityTreemapAction findSimilarAction, findNonSimilarAction; public MuVisTreemapMouseActionListener(TMView view, ArrayList<MuVisTreemapNode> selectedNodes) { this.view = view; this.selectedNodes = selectedNodes; previewAction = new PreviewTreemapAction(selectedNodes); addToPlaylistAction = new AddToPlaylistTreemapAction(selectedNodes); findSimilarAction = new FindSimilarElementsTreemapAction(selectedNodes); findNonSimilarAction = new FindNonSimilarElementsTreemapAction(selectedNodes); } @Override protected void assignActionListeners() { previewAction.setNodeUnder(nodeUnder); addToPlaylistAction.setNodeUnder(nodeUnder); findSimilarAction.setNodeUnder(nodeUnder); findNonSimilarAction.setNodeUnder(nodeUnder); previewElementMenu.addActionListener(previewAction); addElementToPlaylistMenu.addActionListener(addToPlaylistAction); findSimilarElementMenu.addActionListener(findSimilarAction); findNonSimilarElementMenu.addActionListener(findNonSimilarAction); } @Override protected void mouseHandler(MouseEvent e) { Object node = view.getNodeUnderTheMouse(e); if (node != null && e.isPopupTrigger()) { MuVisTreemapNode fNode = (MuVisTreemapNode) node; nodeUnder = fNode; MainViewsMouseAdapter.ElementType type; if (selectedNodes.isEmpty() || selectedNodes.size() == 1) { type = MainViewsMouseAdapter.ElementType.SIMPLE; } else { type = MainViewsMouseAdapter.ElementType.MULTIPLE; } contextMenu = createContextMenu(Messages.COL_ARTIST_NAME_LABEL, type); //show the menu if (contextMenu != null && contextMenu.getComponentCount() > 0) { contextMenu.show(view, e.getX(), e.getY()); } } } }
gpl-3.0
titus08/frostwire-desktop
lib/jars-src/h2-1.3.164/org/h2/index/TreeIndex.java
11194
/* * Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License, * Version 1.0, and under the Eclipse Public License, Version 1.0 * (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.index; import org.h2.constant.SysProperties; import org.h2.engine.Session; import org.h2.message.DbException; import org.h2.result.Row; import org.h2.result.SearchRow; import org.h2.table.IndexColumn; import org.h2.table.RegularTable; import org.h2.table.TableFilter; import org.h2.value.Value; import org.h2.value.ValueNull; /** * The tree index is an in-memory index based on a binary AVL trees. */ public class TreeIndex extends BaseIndex { private TreeNode root; private RegularTable tableData; private long rowCount; private boolean closed; public TreeIndex(RegularTable table, int id, String indexName, IndexColumn[] columns, IndexType indexType) { initBaseIndex(table, id, indexName, columns, indexType); tableData = table; } public void close(Session session) { root = null; closed = true; } public void add(Session session, Row row) { if (closed) { throw DbException.throwInternalError(); } TreeNode i = new TreeNode(row); TreeNode n = root, x = n; boolean isLeft = true; while (true) { if (n == null) { if (x == null) { root = i; rowCount++; return; } set(x, isLeft, i); break; } Row r = n.row; int compare = compareRows(row, r); if (compare == 0) { if (indexType.isUnique()) { if (!containsNullAndAllowMultipleNull(row)) { throw getDuplicateKeyException(); } } compare = compareKeys(row, r); } isLeft = compare < 0; x = n; n = child(x, isLeft); } balance(x, isLeft); rowCount++; } private void balance(TreeNode x, boolean isLeft) { while (true) { int sign = isLeft ? 1 : -1; switch (x.balance * sign) { case 1: x.balance = 0; return; case 0: x.balance = -sign; break; case -1: TreeNode l = child(x, isLeft); if (l.balance == -sign) { replace(x, l); set(x, isLeft, child(l, !isLeft)); set(l, !isLeft, x); x.balance = 0; l.balance = 0; } else { TreeNode r = child(l, !isLeft); replace(x, r); set(l, !isLeft, child(r, isLeft)); set(r, isLeft, l); set(x, isLeft, child(r, !isLeft)); set(r, !isLeft, x); int rb = r.balance; x.balance = (rb == -sign) ? sign : 0; l.balance = (rb == sign) ? -sign : 0; r.balance = 0; } return; default: DbException.throwInternalError("b:" + x.balance * sign); } if (x == root) { return; } isLeft = x.isFromLeft(); x = x.parent; } } private static TreeNode child(TreeNode x, boolean isLeft) { return isLeft ? x.left : x.right; } private void replace(TreeNode x, TreeNode n) { if (x == root) { root = n; if (n != null) { n.parent = null; } } else { set(x.parent, x.isFromLeft(), n); } } private static void set(TreeNode parent, boolean left, TreeNode n) { if (left) { parent.left = n; } else { parent.right = n; } if (n != null) { n.parent = parent; } } public void remove(Session session, Row row) { if (closed) { throw DbException.throwInternalError(); } TreeNode x = findFirstNode(row, true); if (x == null) { throw DbException.throwInternalError("not found!"); } TreeNode n; if (x.left == null) { n = x.right; } else if (x.right == null) { n = x.left; } else { TreeNode d = x; x = x.left; for (TreeNode temp = x; (temp = temp.right) != null;) { x = temp; } // x will be replaced with n later n = x.left; // swap d and x int b = x.balance; x.balance = d.balance; d.balance = b; // set x.parent TreeNode xp = x.parent; TreeNode dp = d.parent; if (d == root) { root = x; } x.parent = dp; if (dp != null) { if (dp.right == d) { dp.right = x; } else { dp.left = x; } } // TODO index / tree: link d.r = x(p?).r directly if (xp == d) { d.parent = x; if (d.left == x) { x.left = d; x.right = d.right; } else { x.right = d; x.left = d.left; } } else { d.parent = xp; xp.right = d; x.right = d.right; x.left = d.left; } if (SysProperties.CHECK && x.right == null) { DbException.throwInternalError("tree corrupted"); } x.right.parent = x; x.left.parent = x; // set d.left, d.right d.left = n; if (n != null) { n.parent = d; } d.right = null; x = d; } rowCount--; boolean isLeft = x.isFromLeft(); replace(x, n); n = x.parent; while (n != null) { x = n; int sign = isLeft ? 1 : -1; switch (x.balance * sign) { case -1: x.balance = 0; break; case 0: x.balance = sign; return; case 1: TreeNode r = child(x, !isLeft); int b = r.balance; if (b * sign >= 0) { replace(x, r); set(x, !isLeft, child(r, isLeft)); set(r, isLeft, x); if (b == 0) { x.balance = sign; r.balance = -sign; return; } x.balance = 0; r.balance = 0; x = r; } else { TreeNode l = child(r, isLeft); replace(x, l); b = l.balance; set(r, isLeft, child(l, !isLeft)); set(l, !isLeft, r); set(x, !isLeft, child(l, isLeft)); set(l, isLeft, x); x.balance = (b == sign) ? -sign : 0; r.balance = (b == -sign) ? sign : 0; l.balance = 0; x = l; } break; default: DbException.throwInternalError("b: " + x.balance * sign); } isLeft = x.isFromLeft(); n = x.parent; } } private TreeNode findFirstNode(SearchRow row, boolean withKey) { TreeNode x = root, result = x; while (x != null) { result = x; int compare = compareRows(x.row, row); if (compare == 0 && withKey) { compare = compareKeys(x.row, row); } if (compare == 0) { if (withKey) { return x; } x = x.left; } else if (compare > 0) { x = x.left; } else { x = x.right; } } return result; } public Cursor find(TableFilter filter, SearchRow first, SearchRow last) { return find(first, last); } public Cursor find(Session session, SearchRow first, SearchRow last) { return find(first, last); } private Cursor find(SearchRow first, SearchRow last) { if (first == null) { TreeNode x = root, n; while (x != null) { n = x.left; if (n == null) { break; } x = n; } return new TreeCursor(this, x, null, last); } TreeNode x = findFirstNode(first, false); return new TreeCursor(this, x, first, last); } public double getCost(Session session, int[] masks) { return getCostRangeIndex(masks, tableData.getRowCountApproximation()); } public void remove(Session session) { truncate(session); } public void truncate(Session session) { root = null; rowCount = 0; } public void checkRename() { // nothing to do } public boolean needRebuild() { return true; } public boolean canGetFirstOrLast() { return true; } public Cursor findFirstOrLast(Session session, boolean first) { if (closed) { throw DbException.throwInternalError(); } if (first) { // TODO optimization: this loops through NULL Cursor cursor = find(session, null, null); while (cursor.next()) { SearchRow row = cursor.getSearchRow(); Value v = row.getValue(columnIds[0]); if (v != ValueNull.INSTANCE) { return cursor; } } return cursor; } TreeNode x = root, n; while (x != null) { n = x.right; if (n == null) { break; } x = n; } TreeCursor cursor = new TreeCursor(this, x, null, null); if (x == null) { return cursor; } // TODO optimization: this loops through NULL elements do { SearchRow row = cursor.getSearchRow(); if (row == null) { break; } Value v = row.getValue(columnIds[0]); if (v != ValueNull.INSTANCE) { return cursor; } } while (cursor.previous()); return cursor; } public long getRowCount(Session session) { return rowCount; } public long getRowCountApproximation() { return rowCount; } }
gpl-3.0
ucberkeley/moocchat
turk/src/com/amazonaws/mturk/cmd/UpdateHITs.java
5364
/* * Copyright 2012 Amazon Technologies, Inc. * * Licensed under the Amazon Software License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/asl * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and * limitations under the License. */ package com.amazonaws.mturk.cmd; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import org.apache.commons.cli.CommandLine; import com.amazonaws.mturk.addon.HITDataOutput; import com.amazonaws.mturk.addon.HITDataWriter; import com.amazonaws.mturk.addon.HITProperties; import com.amazonaws.mturk.requester.HIT; public class UpdateHITs extends AbstractCmd { public int MAX_HITS_UNLIMITED = -1; private final static String ARG_SUCCESS = "success"; private final static String ARG_PROPERTIES = "properties"; public static void main(String[] args) { UpdateHITs lh = new UpdateHITs(); lh.run(args); } protected void initOptions() { opt.addOption(ARG_SUCCESS, true, "(required) The success file to use (in comma-delimited format -- eg. helloworld.success).This should contain the 'hitid' column"); opt.addOption(ARG_PROPERTIES, true, "(required) The updated properties file (that contains the new values) to use (in key:value form -- eg. helloworld.properties)"); } protected void printHelp() { formatter.printHelp(UpdateHITs.class.getName() + " -" + ARG_SUCCESS + " [input_file]" + " -" + ARG_PROPERTIES + " [properties_file]", opt); } protected void runCommand(CommandLine cmdLine) throws Exception { if (!cmdLine.hasOption(ARG_SUCCESS)) { log.error("Missing: -" + ARG_SUCCESS + " [path to success file -- eg. c:\\mturk\\helloworld.success]"); System.exit(-1); } else if (!cmdLine.hasOption(ARG_PROPERTIES)) { log.error("Missing: -" + ARG_PROPERTIES + " [path to config file -- eg. c:\\mturk\\helloworld.properties]"); System.exit(-1); } try { updateHITs(cmdLine.getOptionValue(ARG_SUCCESS), cmdLine.getOptionValue(ARG_PROPERTIES)); } catch (Exception e) { log.error("Error loading HITs: " + e.getLocalizedMessage(), e); System.exit(-1); } } public HIT[] updateHITs(String successFile, String props) throws Exception { HITProperties hc = new HITProperties(props); // Output initializing message log.info("--[Initializing]----------"); log.info(" Success File: " + successFile); log.info(" Properties: " + props); log.info("--[Updating HITs]----------"); Date startTime = new Date(); log.info(" Start time: " + startTime); String[] hitIds = super.getFieldValuesFromFile(successFile, "hitid"); String[] hitTypeIds = super.getFieldValuesFromFile(successFile, "hittypeid"); log.info(" Input: " + hitIds.length + " hitids"); HITDataOutput success = new HITDataWriter(successFile + ".success"); HITDataOutput failure = null; success.setFieldNames( new String[] {"hitid", "hittypeid"} ); String newHITTypeId; try { newHITTypeId = service.registerHITType(hc.getAutoApprovalDelay(), hc.getAssignmentDuration(), hc.getRewardAmount(), hc.getTitle(), hc.getKeywords(), hc.getDescription(), hc.getQualificationRequirements()); } catch (Exception e) { log.error("Failed to register new HITType: " + e.getLocalizedMessage(), e); return new HIT[0]; } log.info(" New HITTypeId: " + newHITTypeId); List<HIT> hits = new ArrayList<HIT>(hitIds.length); for (int i=0 ; i<hitIds.length ; i++) { try { HIT hit = service.getHIT(hitIds[i]); service.changeHITTypeOfHIT(hit.getHITId(), newHITTypeId); HashMap<String,String> good = new HashMap<String,String>(); good.put( "hitid", hit.getHITId() ); good.put( "hittypeid", newHITTypeId ); success.writeValues( good ); log.info("Updated HIT #" + i + " (" + hit.getHITId() + ") to new HITTypeId " + newHITTypeId); hits.add(hit); } catch (Exception e) { if (failure == null) { failure = new HITDataWriter(successFile + ".failure"); failure.setFieldNames( new String[] {"hitid", "hittypeid"} ); } HashMap<String,String> fail = new HashMap<String,String>(); fail.put( "hitid", hitIds[i] ); fail.put( "hittypeid", hitTypeIds[i] ); failure.writeValues( fail ); log.info("Failed to update HIT #" + i + "(" + hitIds[i] + ") to new HITTypeId " + newHITTypeId +" Error message:" + e.getLocalizedMessage()); } } Date endTime = new Date(); log.info(" End time: " + endTime); log.info("--[Done Updating HITs]----------"); log.info(hitIds.length + " HITS were processed"); log.info(hits.size() + " HITS were updated"); if (hitIds.length != hits.size()) log.info(hitIds.length - hits.size() + " HITS could not be updated"); log.info(" Total load time: " + (endTime.getTime() - startTime.getTime()) / 1000 + " seconds."); return hits.toArray(new HIT[hits.size()]); } }
gpl-3.0
rainerangermeier/StockService
Server/StockService/src/main/java/service/data/jsonwrapper/YQLQueryWrapper.java
316
package service.data.jsonwrapper; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown=true) public class YQLQueryWrapper { private YQLQuery query; public YQLQuery getQuery() { return query; } public void setQuery(YQLQuery query) { this.query = query; } }
gpl-3.0
20zinnm/AutpShear
AutoShear/src/autoshear/AutpShear.java
367
package autoshear; import org.bukkit.plugin.java.JavaPlugin; public class AutpShear extends JavaPlugin { public void onEnable() { getLogger().info("AutoShear enabled!"); AutoShearListener asl = new AutoShearListener(); getServer().getPluginManager().registerEvents(asl, this); } public void onDisable() { getLogger().info("AutoShear disabled!"); } }
gpl-3.0
Dove-Bren/QuestManager
src/main/java/com/skyisland/questmanager/ui/menu/action/TeleportAction.java
2428
/* * QuestManager: An RPG plugin for the Bukkit API. * Copyright (C) 2015-2016 Github Contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.skyisland.questmanager.ui.menu.action; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import com.skyisland.questmanager.player.QuestPlayer; import com.skyisland.questmanager.ui.ChatMenu; import com.skyisland.questmanager.ui.menu.SimpleChatMenu; import com.skyisland.questmanager.ui.menu.message.Message; /** * Ferries a player * */ public class TeleportAction implements MenuAction { private int cost; private Location destination; private QuestPlayer player; private Message denial; public TeleportAction(int cost, Location destination, QuestPlayer player, Message denialMessage) { this.cost = cost; this.player = player; this.denial = denialMessage; this.destination = destination; } @Override public void onAction() { //check their money if (player.getMoney() >= cost) { //they have enough money //blindness for some time, but just teleportation & particles! if (!player.getPlayer().isOnline()) { System.out.println("Very bad TeleportAction error!!!!!!!!!!!!!"); return; } player.addMoney(-cost); Player p = player.getPlayer().getPlayer(); p.addPotionEffect( new PotionEffect(PotionEffectType.BLINDNESS, 60, 5)); p.teleport(destination); destination.getWorld().playEffect(destination, Effect.STEP_SOUND, 0); } else { //not enough money //show them a menu, sorrow ChatMenu menu = new SimpleChatMenu(denial.getFormattedMessage()); menu.show(player.getPlayer().getPlayer(), null); } } }
gpl-3.0
weizengke/gdoj
gdoj/src/com/gdoj/admin/action/HomeEditAction.java
1593
package com.gdoj.admin.action; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.gdoj.bean.TopUsersBean; import com.gdoj.user.service.UserService; import com.gdoj.user.vo.User; import org.apache.struts2.ServletActionContext; import org.apache.struts2.json.annotations.JSON; import org.quartz.SchedulerContext; import com.opensymphony.xwork2.ActionSupport; import com.util.MyApplicationContextUtil; import com.util.StreamHandler; import com.util.freemarker.MyFreeMarker; public class HomeEditAction extends ActionSupport { private static final long serialVersionUID = 1L; private String content; private String sidebar_content; public String getSidebar_content() { return sidebar_content; } public void setSidebar_content(String sidebarContent) { sidebar_content = sidebarContent; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String homeedit()throws Exception { try { String path = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/"); //System.out.println(path+"WEB-INF\\templates\\homepage.html"); content = StreamHandler.read(path+"WEB-INF\\templates\\homepage.html"); sidebar_content = StreamHandler.read(path+"WEB-INF\\templates\\sidebarex.html"); //System.out.println(content); } catch (Exception e) { // TODO: handle exception return ERROR; } return SUCCESS; } }
gpl-3.0
git-mhaque/java-design-patterns
src/flyweight/Client.java
1481
/******************************************************************************* * Copyright (c) 2003-2013 Mahfuzul Haque * * This file is part of java-design-patterns which provides example implementations of 23 GoF design patterns. * * * java-design-patterns is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * java-design-patterns 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with java-design-patterns. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ /* * Created on Dec 18, 2003 * */ package flyweight; public class Client { public static void main(String args[]) { char document[] ={ 'a','a','z','k','b','b','a','c','k','d','z','a' }; Context context = new Context(); CharacterFlyweightFactory factory = new CharacterFlyweightFactory(); for(int i = 0; i < document.length; i++ ) { Character c = factory.getCharacter(document[i]); c.drawCharacter(context); } System.out.println(); } }
gpl-3.0
tferr/cx3dp-mvn
src/main/java/ini/cx3d/electrophysiology/model/SynapseELModel.java
244
package ini.cx3d.electrophysiology.model; import ini.cx3d.electrophysiology.ElectroPhysiolgySynapse; public interface SynapseELModel extends Processable{ public SynapseELModel getI(); public void setELObject(ElectroPhysiolgySynapse o); }
gpl-3.0
msdhedhi/VerifyWinFileDigitalSignature
src/main/java/com/dhedhi/utils/verifywinsign/exceptions/WindowsPEFileFormatException.java
258
package com.dhedhi.utils.verifywinsign.exceptions; public class WindowsPEFileFormatException extends RuntimeException { private static final long serialVersionUID = 1L; public WindowsPEFileFormatException(String s) { super(s); } }
gpl-3.0
vexelon-dot-net/currencybg.app
src/main/java/net/vexelon/currencybg/app/db/models/WalletEntryInvestment.java
2333
package net.vexelon.currencybg.app.db.models; import java.math.BigDecimal; /** * Describes investment info for a single wallet entry and a currency source * */ public class WalletEntryInvestment { private WalletEntry walletEntry; private CurrencyData currencyData; private BigDecimal initialValue; private BigDecimal currentValue; private BigDecimal investmentMargin; private BigDecimal investmentMarginPercentage; private int investmentDuration; // in days private BigDecimal dailyChange; private BigDecimal dailyChangePercentage; public WalletEntryInvestment(WalletEntry entry, CurrencyData currencyData) { this.walletEntry = entry; this.currencyData = currencyData; } public BigDecimal getInitialValue() { return initialValue; } public void setInitialValue(BigDecimal initialValue) { this.initialValue = initialValue; } public BigDecimal getCurrentValue() { return currentValue; } public void setCurrentValue(BigDecimal currentValue) { this.currentValue = currentValue; } public WalletEntry getWalletEntry() { return walletEntry; } public void setWalletEntry(WalletEntry walletEntry) { this.walletEntry = walletEntry; } public CurrencyData getCurrencyData() { return currencyData; } public void setCurrencyData(CurrencyData currencyData) { this.currencyData = currencyData; } public BigDecimal getInvestmentMargin() { return investmentMargin; } public void setInvestmentMargin(BigDecimal investmentMargin) { this.investmentMargin = investmentMargin; } public BigDecimal getInvestmentMarginPercentage() { return investmentMarginPercentage; } public void setInvestmentMarginPercentage(BigDecimal investmentMarginPercentage) { this.investmentMarginPercentage = investmentMarginPercentage; } public int getInvestmentDuration() { return investmentDuration; } public void setInvestmentDuration(int investmentDuration) { this.investmentDuration = investmentDuration; } public BigDecimal getDailyChange() { return dailyChange; } public void setDailyChange(BigDecimal dailyChange) { this.dailyChange = dailyChange; } public BigDecimal getDailyChangePercentage() { return dailyChangePercentage; } public void setDailyChangePercentage(BigDecimal dailyChangePercentage) { this.dailyChangePercentage = dailyChangePercentage; } }
gpl-3.0
arindamgit/arduino-unlock-ubuntu
src/main/java/serialcomms/Main.java
3113
package serialcomms; import java.io.IOException; import java.util.Iterator; import java.util.Map.Entry; import java.util.Set; import gnu.io.CommPortIdentifier; import gnu.io.NoSuchPortException; import gnu.io.PortInUseException; import gnu.io.UnsupportedCommOperationException; public class Main { Entry<String, CommPortIdentifier> arduinoPort = null; Set<Entry<String, CommPortIdentifier>> portsWithoutArduino = null; Set<Entry<String, CommPortIdentifier>> portsWithArduino = null; Communicator comm = new Communicator(); private static int MAX_TRY = 15000; public static void main(String args[]) throws IOException, NoSuchPortException, PortInUseException, UnsupportedCommOperationException { instructions(); Main thisClass = new Main(); System.out.println("Unplug your Arduino... When done press Enter"); System.in.read(); thisClass.portsWithoutArduino = thisClass.getPorts(); System.out.println("Now plug-in your Arduino... When done press Enter"); System.in.read(); int tryst = 0; System.out.println("Trying to connect to your Arduino, please stand by"); do { tryst++; if(tryst % 1000 == 0) System.out.print("."); if(tryst > MAX_TRY) { System.out.println("\nCannot find your Arduino. Sorry"); System.exit(-1); } thisClass.portsWithArduino = thisClass.getPorts(); } while(thisClass.portsWithArduino.size() == thisClass.portsWithoutArduino.size()); System.out.println(); Iterator<Entry<String, CommPortIdentifier>> iterator = thisClass.portsWithArduino.iterator(); while(iterator.hasNext()) { Entry<String, CommPortIdentifier> testPort = iterator.next(); if(!thisClass.portsWithoutArduino.contains(testPort)) thisClass.arduinoPort = testPort; } System.out.println("Arduino port found at " + thisClass.arduinoPort.getKey()); thisClass.connect(); thisClass.initCommunicator(); while(true); } private Set<Entry<String, CommPortIdentifier>> getPorts() { return comm.searchForPorts().entrySet(); } private void connect() throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException { comm.connect(arduinoPort.getValue()); } private void initCommunicator() throws IOException { comm.initListener(); } private void stopCommunicator() throws IOException { comm.shutdown(); } private static void instructions() { System.out.println("The program will try to detect your arduino"); System.out.println("Please follow the instructions"); System.out.println(" ----------------------------------------- "); } private void attachShutdown() { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { Thread.sleep(200); System.out.println("Shouting down ..."); stopCommunicator(); } catch (InterruptedException e) { System.out.println("Shouting down not clean thread interrupted ..."); } catch (IOException e) { System.out.println("Shouting down not clean IOException ..."); e.printStackTrace(); } } }); } }
gpl-3.0
lyrachord/FX3DAndroid
src/main/java/org/fxyz/shapes/primitives/helper/Text3DHelper.java
6577
/* * Copyright (C) 2013-2015 F(X)yz, * Sean Phillips, Jason Pollastrini and Jose Pereda * All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.fxyz.shapes.primitives.helper; import static java8.util.stream.StreamSupport.*; import java8.lang.Iterables; import java8.util.stream.*; import java.util.ArrayList; import java.util.List; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.geometry.Point2D; import javafx.scene.paint.Color; import javafx.scene.shape.ClosePath; import javafx.scene.shape.CubicCurveTo; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.shape.PathElement; import javafx.scene.shape.QuadCurveTo; import javafx.scene.shape.Rectangle; import javafx.scene.shape.Shape; import javafx.scene.text.Font; import javafx.scene.text.Text; import org.fxyz.geometry.Point3D; /** * * @author José Pereda */ public class Text3DHelper { private final static int POINTS_CURVE = 10; private final String text; private List<Point3D> list; private Point3D p0; private final List<LineSegment> polis=new ArrayList<>(); public Text3DHelper(String text, String font, int size){ this.text=text; list=new ArrayList<>(); //android will failed at this point because text has no font name Text textNode = new Text(); textNode.setFont(new Font(font,size)); textNode.setText(text); // Convert Text to Path Path subtract = (Path)(Shape.subtract(textNode, new Rectangle(0, 0))); // Convert Path elements into lists of points defining the perimeter (exterior or interior) Iterables.forEach(subtract.getElements(), this::getPoints); // Group exterior polygons with their interior polygons stream(polis).filter(LineSegment::isHole).forEach(hole->{ stream(polis).filter(poly->!poly.isHole()) .filter(poly->!((Path)Shape.intersect(poly.getPath(), hole.getPath())).getElements().isEmpty()) .filter(poly->poly.getPath().contains(new Point2D(hole.getOrigen().x,hole.getOrigen().y))) .forEach(poly->poly.addHole(hole)); }); Iterables.removeIf(polis, LineSegment::isHole); } public List<LineSegment> getLineSegment() { return polis; } public List<Point3D> getOffset(){ return stream(polis).sorted((p1,p2)->(int)(p1.getOrigen().x-p2.getOrigen().x)) .map(LineSegment::getOrigen).collect(Collectors.toList()); } private void getPoints(PathElement elem){ if(elem instanceof MoveTo){ list=new ArrayList<>(); p0=new Point3D((float)((MoveTo)elem).getX(),(float)((MoveTo)elem).getY(),0f); list.add(p0); } else if(elem instanceof LineTo){ list.add(new Point3D((float)((LineTo)elem).getX(),(float)((LineTo)elem).getY(),0f)); } else if(elem instanceof CubicCurveTo){ Point3D ini = (list.size()>0?list.get(list.size()-1):p0); IntStreams.rangeClosed(1, POINTS_CURVE).forEach(i->list.add(evalCubicBezier((CubicCurveTo)elem, ini, ((double)i)/POINTS_CURVE))); } else if(elem instanceof QuadCurveTo){ Point3D ini = (list.size()>0?list.get(list.size()-1):p0); IntStreams.rangeClosed(1, POINTS_CURVE).forEach(i->list.add(evalQuadBezier((QuadCurveTo)elem, ini, ((double)i)/POINTS_CURVE))); } else if(elem instanceof ClosePath){ list.add(p0); // Every closed path is a polygon (exterior or interior==hole) // the text, the list of points and a new path between them are // stored in a LineSegment: a continuous line that can change direction if(Math.abs(getArea())>0.001){ LineSegment line = new LineSegment(text); line.setHole(isHole()); line.setPoints(list); line.setPath(generatePath()); line.setOrigen(p0); polis.add(line); } } } private Point3D evalCubicBezier(CubicCurveTo c, Point3D ini, double t){ Point3D p=new Point3D((float)(Math.pow(1-t,3)*ini.x+ 3*t*Math.pow(1-t,2)*c.getControlX1()+ 3*(1-t)*t*t*c.getControlX2()+ Math.pow(t, 3)*c.getX()), (float)(Math.pow(1-t,3)*ini.y+ 3*t*Math.pow(1-t, 2)*c.getControlY1()+ 3*(1-t)*t*t*c.getControlY2()+ Math.pow(t, 3)*c.getY()), 0f); return p; } private Point3D evalQuadBezier(QuadCurveTo c, Point3D ini, double t){ Point3D p=new Point3D((float)(Math.pow(1-t,2)*ini.x+ 2*(1-t)*t*c.getControlX()+ Math.pow(t, 2)*c.getX()), (float)(Math.pow(1-t,2)*ini.y+ 2*(1-t)*t*c.getControlY()+ Math.pow(t, 2)*c.getY()), 0f); return p; } private double getArea(){ DoubleProperty res=new SimpleDoubleProperty(); IntStreams.range(0, list.size()-1) .forEach(i->res.set(res.get()+list.get(i).crossProduct(list.get(i+1)).z)); // System.out.println("path: "+res.doubleValue()/2); return res.doubleValue()/2d; } private boolean isHole(){ // area>0 -> the path is a hole, clockwise (y up) // area<0 -> the path is a polygon, counterclockwise (y up) return getArea()>0; } private Path generatePath(){ Path path = new Path(new MoveTo(list.get(0).x,list.get(0).y)); stream(list).skip(1).forEach(p->path.getElements().add(new LineTo(p.x,p.y))); path.getElements().add(new ClosePath()); path.setStroke(Color.GREEN); // Path must be filled to allow Shape.intersect path.setFill(Color.RED); return path; } }
gpl-3.0
NEMESIS13cz/Evercraft
java/evercraft/NEMESIS13cz/Items/Sticks/ItemGoldStick.java
682
package evercraft.NEMESIS13cz.Items.Sticks; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.Item; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import evercraft.NEMESIS13cz.ModInformation; import evercraft.NEMESIS13cz.Main.ECTabs; public class ItemGoldStick extends Item { public ItemGoldStick() { setCreativeTab(ECTabs.tabECMisc); //Tells the game what creative mode tab it goes in } @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister par1IconRegister) { this.itemIcon = par1IconRegister.registerIcon(ModInformation.TEXTUREPATH + ":" + ModInformation.GOLD_STICK); } }
gpl-3.0
GregoryGoldshteyn/MTG_RPG
src/mtg_rpg/CardListInternalFrame.java
1310
package mtg_rpg; import java.awt.Dimension; import javax.swing.*; public class CardListInternalFrame extends JInternalFrame{ static final int xOffset = 30, yOffset = 30; public int numberOfCards; public Card[] cardArray; public JLayeredPane cardStack; private JScrollPane scrollPane; public CardListInternalFrame(String windowTitle, int insetx, int insety, Card[] cards){ super(windowTitle, true, false, false, true); this.cardArray = cards; setLocation(insetx, insety); setSize(180, 360); this.setResizable(false); this.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); cardStack = new JLayeredPane(); cardStack.setPreferredSize(new Dimension(180, 135)); scrollPane = new JScrollPane(cardStack); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); setContentPane(scrollPane); } public Card getCardByID(int id){ for(Card c : cardArray){ if(c.id == id){ return c; } } return null; } public void addCard(CardSmallLayered c){ c.setBounds(0, numberOfCards * 20, 170, 135); cardStack.add(c, new Integer(numberOfCards)); cardStack.setPreferredSize(new Dimension(180, 135 + (numberOfCards * 20))); numberOfCards += 1; } }
gpl-3.0
MinestrapTeam/Minestrappolation-4
src/main/java/minestrapteam/mods/minestrappolation/inventory/container/ContainerBarrel.java
745
package minestrapteam.mods.minestrappolation.inventory.container; import minestrapteam.mods.minestrappolation.tileentity.TileEntityBarrel; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; public class ContainerBarrel extends MinestrappolationContainer { public ContainerBarrel(EntityPlayer player, TileEntityBarrel barrel) { super(player, barrel); for (int j = 0; j < 4; ++j) { for (int k = 0; k < 9; ++k) { this.addSlotToContainer(new Slot(barrel, k + j * 9, 8 + k * 18, 18 + j * 18)); } } this.addInventorySlots(0, 20); } @Override public int[] merge(EntityPlayer player, int slot, ItemStack stack) { return new int[] { 0, 36 }; } }
gpl-3.0
zpxocivuby/freetong_mobile_server
itaf-aggregator/itaf-ws-simulator/src/test/java/itaf/WsSearchService/BaseTreeDto.java
2707
package itaf.WsSearchService; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for baseTreeDto complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="baseTreeDto"> * &lt;complexContent> * &lt;extension base="{itaf.framework.ws.server.search}baseDto"> * &lt;sequence> * &lt;element name="parentId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="orderNo" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="isLeaf" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "baseTreeDto", propOrder = { "parentId", "orderNo", "isLeaf" }) @XmlSeeAlso({ SysResourceDto.class, BzServiceProviderTypeDto.class, BzProductCategoryDto.class }) public abstract class BaseTreeDto extends BaseDto { protected Long parentId; protected Long orderNo; protected Boolean isLeaf; /** * Gets the value of the parentId property. * * @return * possible object is * {@link Long } * */ public Long getParentId() { return parentId; } /** * Sets the value of the parentId property. * * @param value * allowed object is * {@link Long } * */ public void setParentId(Long value) { this.parentId = value; } /** * Gets the value of the orderNo property. * * @return * possible object is * {@link Long } * */ public Long getOrderNo() { return orderNo; } /** * Sets the value of the orderNo property. * * @param value * allowed object is * {@link Long } * */ public void setOrderNo(Long value) { this.orderNo = value; } /** * Gets the value of the isLeaf property. * * @return * possible object is * {@link Boolean } * */ public Boolean isIsLeaf() { return isLeaf; } /** * Sets the value of the isLeaf property. * * @param value * allowed object is * {@link Boolean } * */ public void setIsLeaf(Boolean value) { this.isLeaf = value; } }
gpl-3.0
AdiSai/Computer-Science-AP
Review/2014 FRQ (Old Practice)/Drink.java
115
public class Drink extends SimpleLunchItem { public Drink(String name, double price) { super(name, price); } }
gpl-3.0
shamim8888/FXyz
Fxyz-Samples/src/main/java/org/fxyz/controls/SectionLabel.java
2422
/** * SectionLabel.java * * Copyright (c) 2013-2015, F(X)yz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the organization nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.fxyz.controls; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.control.Label; import javafx.scene.layout.StackPane; /** * * @author Jason Pollastrini aka jdub1581 */ public class SectionLabel extends StackPane{ @FXML private Label sectionLabel; public SectionLabel(String text) { try { final FXMLLoader loader = new FXMLLoader(getClass().getResource("/org/fxyz/controls/SectionLabel.fxml")); loader.setRoot(SectionLabel.this); loader.setController(SectionLabel.this); loader.load(); } catch (IOException ex) { Logger.getLogger(CheckBoxControl.class.getName()).log(Level.SEVERE, null, ex); } sectionLabel.setText(text); } }
gpl-3.0
DavidVieiro/Java-3
VentanaDialog/src/paquete/Ventana1.java
4303
/* * 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 paquete; /** * * @author dam132 */ public class Ventana1 extends javax.swing.JFrame { private Dialogo1 d1; /** * Creates new form Ventana1 */ public Ventana1() { initComponents(); d1 = new Dialogo1 ( this, true ); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jButton1.setText("Ir al dialogo"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(78, 78, 78) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(85, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(87, 87, 87) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(107, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed d1.setVisible( true ); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Ventana1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Ventana1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Ventana1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Ventana1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Ventana1().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; // End of variables declaration//GEN-END:variables }
gpl-3.0
enoy19/keyboard-light-composer
keyboard-light-composer-controller/src/main/java/org/enoy/klc/control/valuestrategies/ExternalBoolean.java
521
package org.enoy.klc.control.valuestrategies; import org.enoy.klc.common.factories.FactoryGenericType; import org.enoy.klc.common.factories.Name; @FactoryGenericType(Boolean.class) @Name("External Boolean") public class ExternalBoolean extends ExternalValue<Boolean> { private static final long serialVersionUID = -4388835305379695481L; @Override protected Class<Boolean> getType() { return Boolean.class; } @Override public Boolean getValue() { return getExternalValue(); } }
gpl-3.0
G2159687/espd
app/src/main/java/com/github/epd/sprout/sprites/PoisonGooSprite.java
2139
package com.github.epd.sprout.sprites; import com.github.epd.sprout.Assets; import com.watabou.noosa.TextureFilm; import com.watabou.noosa.particles.Emitter; import com.watabou.noosa.particles.Emitter.Factory; import com.watabou.noosa.particles.PixelParticle; import com.watabou.utils.PointF; import com.watabou.utils.Random; public class PoisonGooSprite extends MobSprite { private Animation pump; private Animation pumpAttack; public PoisonGooSprite() { super(); texture(Assets.POISONGOO); TextureFilm frames = new TextureFilm(texture, 20, 14); idle = new Animation(10, true); idle.frames(frames, 2, 1, 0, 0, 1); run = new Animation(15, true); run.frames(frames, 3, 2, 1, 2); pump = new Animation(20, true); pump.frames(frames, 4, 3, 2, 1, 0); pumpAttack = new Animation(20, false); pumpAttack.frames(frames, 4, 3, 2, 1, 0, 7); attack = new Animation(10, false); attack.frames(frames, 8, 9, 10); die = new Animation(10, false); die.frames(frames, 5, 6, 7); play(idle); } public void pumpUp() { play(pump); } public void pumpAttack() { play(pumpAttack); } @Override public void play(Animation anim, boolean force) { super.play(anim, force); } @Override public int blood() { return 0xFF000000; } public static class GooParticle extends PixelParticle.Shrinking { public static final Emitter.Factory FACTORY = new Factory() { @Override public void emit(Emitter emitter, int index, float x, float y) { ((GooParticle) emitter.recycle(GooParticle.class)).reset(x, y); } }; public GooParticle() { super(); color(0x000000); lifespan = 0.3f; acc.set(0, +50); } public void reset(float x, float y) { revive(); this.x = x; this.y = y; left = lifespan; size = 4; speed.polar(-Random.Float(PointF.PI), Random.Float(32, 48)); } @Override public void update() { super.update(); float p = left / lifespan; am = p > 0.5f ? (1 - p) * 2f : 1; } } @Override public void onComplete(Animation anim) { super.onComplete(anim); if (anim == pumpAttack) { idle(); ch.onAttackComplete(); } } }
gpl-3.0
fppt/mindmapsdb
grakn-test/src/test/java/ai/grakn/test/graql/reasoner/inference/SNBInferenceTest.java
21843
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Grakn 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package ai.grakn.test.graql.reasoner.inference; import ai.grakn.GraknGraph; import ai.grakn.graql.MatchQuery; import ai.grakn.graql.Reasoner; import ai.grakn.graql.internal.reasoner.query.Query; import ai.grakn.graql.internal.reasoner.query.QueryAnswers; import ai.grakn.test.AbstractEngineTest; import ai.grakn.test.graql.reasoner.graphs.SNBGraph; import com.google.common.collect.Sets; import ai.grakn.graql.QueryBuilder; import org.junit.BeforeClass; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assume.assumeTrue; public class SNBInferenceTest extends AbstractEngineTest{ @BeforeClass public static void onStartup(){ assumeTrue(usingTinker()); } /** * Tests transitivity */ @Test public void testTransitivity() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match " + "$x isa university;$y isa country;(located-subject: $x, subject-location: $y) isa resides;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match $x isa university, has name 'University of Cambridge';" + "$y isa country, has name 'UK';"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } @Test public void testTransitivityPrime() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match " + "$x isa university;$y isa country;($x, $y) isa resides;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match $x isa university, has name 'University of Cambridge';" + "$y isa country, has name 'UK';"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } /** * Tests transitivity */ @Test public void testTransitivity2() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match $x isa company;$y isa country;" + "(located-subject: $x, subject-location: $y) isa resides;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match " + "$x isa company, has name 'Grakn';" + "$y isa country, has name 'UK';"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } @Test public void testTransitivity2Prime() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match $x isa company;$y isa country;" + "($x, $y) isa resides;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match " + "$x isa company, has name 'Grakn';" + "$y isa country, has name 'UK';"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } /** * Tests relation filtering and rel vars matching */ @Test public void testTag() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match " + "$x isa person;$y isa tag;($x, $y) isa recommendation;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match " + "$x isa person, has name $xName;$y isa tag, has name $yName;" + "{$xName value 'Charlie';" + "{$yName value 'Yngwie Malmsteen';} or {$yName value 'Cacophony';} or" + "{$yName value 'Steve Vai';} or {$yName value 'Black Sabbath';};} or " + "{$xName value 'Gary';$yName value 'Pink Floyd';};select $x, $y;"; //assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } @Test public void testTagVarSub() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match " + "$y isa person;$t isa tag;($y, $t) isa recommendation;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match $y isa person, has name $yName;$t isa tag, has name $tName;" + "{$yName value 'Charlie';" + "{$tName value 'Yngwie Malmsteen';} or {$tName value 'Cacophony';} or" + "{$tName value 'Steve Vai';} or {$tName value 'Black Sabbath';};} or " + "{$yName value 'Gary';$tName value 'Pink Floyd';};select $y, $t;"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } /** * Tests relation filtering and rel vars matching */ @Test public void testProduct() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match " + "$x isa person;$y isa product;($x, $y) isa recommendation;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match $x isa person, has name $xName;$y isa product, has name $yName;" + "{$xName value 'Alice';$yName value 'War of the Worlds';} or" + "{$xName value 'Bob';{$yName value 'Ducatti 1299';} or {$yName value 'The Good the Bad the Ugly';};} or" + "{$xName value 'Charlie';{$yName value 'Blizzard of Ozz';} or {$yName value 'Stratocaster';};} or " + "{$xName value 'Denis';{$yName value 'Colour of Magic';} or {$yName value 'Dorian Gray';};} or"+ "{$xName value 'Frank';$yName value 'Nocturnes';} or" + "{$xName value 'Karl Fischer';{$yName value 'Faust';} or {$yName value 'Nocturnes';};} or " + "{$xName value 'Gary';$yName value 'The Wall';};select $x, $y;"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } @Test public void testProductVarSub() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match " + "$y isa person;$yy isa product;($y, $yy) isa recommendation;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match $y isa person, has name $ny; $yy isa product, has name $nyy;" + "{$ny value 'Alice';$nyy value 'War of the Worlds';} or" + "{$ny value 'Bob';{$nyy value 'Ducatti 1299';} or {$nyy value 'The Good the Bad the Ugly';};} or" + "{$ny value 'Charlie';{$nyy value 'Blizzard of Ozz';} or {$nyy value 'Stratocaster';};} or " + "{$ny value 'Denis';{$nyy value 'Colour of Magic';} or {$nyy value 'Dorian Gray';};} or"+ "{$ny value 'Frank';$nyy value 'Nocturnes';} or" + "{$ny value 'Karl Fischer';{$nyy value 'Faust';} or {$nyy value 'Nocturnes';};} or " + "{$ny value 'Gary';$nyy value 'The Wall';};select $y, $yy;"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } @Test public void testCombinedProductTag() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match " + "$x isa person;{$y isa product;} or {$y isa tag;};($x, $y) isa recommendation;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match $x isa person;" + "{$x has name 'Alice';$y has name 'War of the Worlds';} or" + "{$x has name 'Bob';{$y has name 'Ducatti 1299';} or {$y has name 'The Good the Bad the Ugly';};} or" + "{$x has name 'Charlie';{$y has name 'Blizzard of Ozz';} or {$y has name 'Stratocaster';};} or " + "{$x has name 'Denis';{$y has name 'Colour of Magic';} or {$y has name 'Dorian Gray';};} or"+ "{$x has name 'Frank';$y has name 'Nocturnes';} or" + "{$x has name 'Karl Fischer';{$y has name 'Faust';} or {$y has name 'Nocturnes';};} or " + "{$x has name 'Gary';$y has name 'The Wall';} or" + "{$x has name 'Charlie';" + "{$y has name 'Yngwie Malmsteen';} or {$y has name 'Cacophony';} or {$y has name 'Steve Vai';} or {$y has name 'Black Sabbath';};} or " + "{$x has name 'Gary';$y has name 'Pink Floyd';};"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } @Test public void testCombinedProductTag2() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match " + "{$p isa person;$r isa product;($p, $r) isa recommendation;} or" + "{$p isa person;$r isa tag;($p, $r) isa recommendation;};"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match $p isa person;" + "{$p has name 'Alice';$r has name 'War of the Worlds';} or" + "{$p has name 'Bob';{$r has name 'Ducatti 1299';} or {$r has name 'The Good the Bad the Ugly';};} or" + "{$p has name 'Charlie';{$r has name 'Blizzard of Ozz';} or {$r has name 'Stratocaster';};} or " + "{$p has name 'Denis';{$r has name 'Colour of Magic';} or {$r has name 'Dorian Gray';};} or"+ "{$p has name 'Frank';$r has name 'Nocturnes';} or" + "{$p has name 'Karl Fischer';{$r has name 'Faust';} or {$r has name 'Nocturnes';};} or " + "{$p has name 'Gary';$r has name 'The Wall';} or" + "{$p has name 'Charlie';" + "{$r has name 'Yngwie Malmsteen';} or {$r has name 'Cacophony';} or {$r has name 'Steve Vai';} or {$r has name 'Black Sabbath';};} or " + "{$p has name 'Gary';$r has name 'Pink Floyd';};"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } @Test public void testBook() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match $x isa person;" + "($x, $y) isa recommendation;" + "$c isa category;$c has name 'book';" + "($y, $c) isa typing; select $x, $y;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match $x isa person, has name $nx;$y isa product, has name $ny;" + "{$nx value 'Alice';$ny value 'War of the Worlds';} or" + "{$nx value 'Karl Fischer';$ny value 'Faust';} or " + "{$nx value 'Denis';{$ny value 'Colour of Magic';} or {$ny value 'Dorian Gray';};};select $x, $y;"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } @Test public void testBand() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match $x isa person;" + "($x, $y) isa recommendation;" + "$c isa category;$c has name 'Band';" + "($y, $c) isa grouping; select $x, $y;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match " + "{$x has name 'Charlie';{$y has name 'Cacophony';} or {$y has name 'Black Sabbath';};} or " + "{$x has name 'Gary';$y has name 'Pink Floyd';}; select $x, $y;"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } /** * Tests global variable consistency (Bug #7344) */ @Test public void testVarConsistency(){ GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match $x isa person;$y isa product;" + "($x, $y) isa recommendation;" + "$z isa category;$z has name 'motorbike';" + "($y, $z) isa typing; select $x, $y;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match $x isa person;$y isa product;" + "{$x has name 'Bob';$y has name 'Ducatti 1299';};"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } /** * tests whether rules are filtered correctly (rules recommending products other than Chopin should not be attached) */ @Test public void testVarConsistency2(){ GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); //select people that have Chopin as a recommendation String queryString = "match $x isa person; $y isa tag; ($x, $y) isa tagging;" + "$z isa product;$z has name 'Nocturnes'; ($x, $z) isa recommendation; select $x, $y;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match " + "{$x has name 'Frank';$y has name 'Ludwig van Beethoven';} or" + "{$x has name 'Karl Fischer';" + "{$y has name 'Ludwig van Beethoven';} or {$y has name 'Johann Wolfgang von Goethe';} or" + "{$y has name 'Wolfgang Amadeus Mozart';};};"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } @Test public void testVarConsistency3(){ GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match $x isa person;$pr isa product, has name 'Nocturnes';($x, $pr) isa recommendation; select $x;"; Query query = new Query(queryString, graph); String explicitQuery = "match {$x has name 'Frank';} or {$x has name 'Karl Fischer';};"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } /** * Tests transitivity and Bug #7416 */ @Test public void testQueryConsistency() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); String queryString = "match $x isa person; $y isa place; ($x, $y) isa resides;" + "$z isa person;$z has name 'Miguel Gonzalez'; ($x, $z) isa knows; select $x, $y;"; MatchQuery query = qb.parse(queryString); QueryAnswers answers = new QueryAnswers(reasoner.resolve(query)); String queryString2 = "match $x isa person; $y isa person;$y has name 'Miguel Gonzalez';" + "$z isa place; ($x, $y) isa knows; ($x, $z) isa resides; select $x, $z;"; MatchQuery query2 = qb.parse(queryString2); Map<String, String> unifiers = new HashMap<>(); unifiers.put("z", "y"); QueryAnswers answers2 = (new QueryAnswers(reasoner.resolve(query2))).unify(unifiers); assertEquals(answers, answers2); } /** * Tests Bug #7416 * the $t variable in the query matches with $t from rules so if the rule var is not changed an extra condition is created * which renders the query unsatisfiable */ @Test public void testOrdering() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); //select recommendationS of Karl Fischer and their types String queryString = "match $p isa product;$x isa person;$x has name 'Karl Fischer';" + "($x, $p) isa recommendation; ($p, $t) isa typing; select $p, $t;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match $p isa product;" + "$x isa person;$x has name 'Karl Fischer';{($x, $p) isa recommendation;} or" + "{$x isa person;$tt isa tag;$tt has name 'Johann Wolfgang von Goethe';" + "($x, $tt) isa tagging;$p isa product;$p has name 'Faust';} or" + "{$x isa person; $p isa product;$p has name 'Nocturnes'; $tt isa tag; ($tt, $x), isa tagging;};" + "($p, $t) isa typing; select $p, $t;"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } @Test public void testOrdering2() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); //select recommendationS of Karl Fischer and their types String queryString2 = "match $p isa product;$x isa person;$x has name 'Karl Fischer';" + "($p, $c) isa typing; ($x, $p) isa recommendation; select $p, $c;"; MatchQuery query2 = qb.parse(queryString2); String explicitQuery2 = "match $p isa product;\n" + "$x isa person;$x has name 'Karl Fischer';{($x, $p) isa recommendation;} or" + "{$x isa person;$t isa tag, has name 'Johann Wolfgang von Goethe';" + "($x, $t) isa tagging;$p isa product;$p has name 'Faust';} or" + "{$x isa person; $p isa product;$p has name 'Nocturnes'; $t isa tag; ($t, $x), isa tagging;};" + "($p, $c) isa typing; select $p, $c;"; assertEquals(reasoner.resolve(query2), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery2))); assertQueriesEqual(reasoner.resolveToQuery(query2), qb.parse(explicitQuery2)); } /** * Tests Bug #7422 */ @Test public void testInverseVars() { GraknGraph graph = SNBGraph.getGraph(); QueryBuilder qb = graph.graql(); Reasoner reasoner = new Reasoner(graph); //select recommendation of Karl Fischer and their types String queryString = "match $p isa product;" + "$x isa person;$x has name 'Karl Fischer'; ($p, $x) isa recommendation; ($p, $t) isa typing; select $p, $t;"; MatchQuery query = qb.parse(queryString); String explicitQuery = "match $p isa product;" + "$x isa person;$x has name 'Karl Fischer';{($x, $p) isa recommendation;} or" + "{$x isa person; $p isa product;$p has name 'Nocturnes'; $tt isa tag; ($tt, $x), isa tagging;} or" + "{$x isa person;$tt isa tag;$tt has name 'Johann Wolfgang von Goethe';($x, $tt) isa tagging;" + "$p isa product;$p has name 'Faust';};" + "($p, $t) isa typing; select $p, $t;"; assertEquals(reasoner.resolve(query), Sets.newHashSet(qb.<MatchQuery>parse(explicitQuery))); assertQueriesEqual(reasoner.resolveToQuery(query), qb.parse(explicitQuery)); } private void assertQueriesEqual(MatchQuery q1, MatchQuery q2) { assertEquals(Sets.newHashSet(q1), Sets.newHashSet(q2)); } }
gpl-3.0
AshourAziz/EchoPet-1
modules/API/src/com/dsh105/echopet/compat/api/entity/type/nms/IEntityVexPet.java
334
package com.dsh105.echopet.compat.api.entity.type.nms; import com.dsh105.echopet.compat.api.entity.IEntityPet; /** * @Author Borlea * @Github https://github.com/borlea/ * @Website http://codingforcookies.com/ * @since Nov 19, 2016 */ public interface IEntityVexPet extends IEntityPet{ public void setPowered(boolean flag); }
gpl-3.0
Estada1401/anuwhscript
GameServer/src/com/aionemu/gameserver/network/aion/serverpackets/SM_PACKAGE_INFO_NOTIFY.java
749
package com.aionemu.gameserver.network.aion.serverpackets; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.AionConnection; import com.aionemu.gameserver.network.aion.AionServerPacket; public class SM_PACKAGE_INFO_NOTIFY extends AionServerPacket { private int count; private int packId; private int time; public SM_PACKAGE_INFO_NOTIFY(int count, int packId, int time) { this.count = count; this.packId = packId; this.time = time; } @Override protected void writeImpl(AionConnection con) { Player activePlayer = con.getActivePlayer(); writeH(count); writeC(packId); writeD(time); } }
gpl-3.0
romankl/bc-tracker-android
app/src/main/java/io/github/romankl/bitcoinvalue/data/model/ModelEndpointOperations.java
1891
/************************************************************************************************************ * Copyright (C) 2014 - 2015 Roman Klauke * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program 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 General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************************************************/ package io.github.romankl.bitcoinvalue.data.model; public interface ModelEndpointOperations { public void fetchNewData(); }
gpl-3.0
nickbattle/vdmj
vdmj/src/main/java/com/fujitsu/vdmj/ast/statements/ASTExternalClause.java
1785
/******************************************************************************* * * Copyright (c) 2016 Fujitsu Services Ltd. * * Author: Nick Battle * * This file is part of VDMJ. * * VDMJ is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VDMJ 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with VDMJ. If not, see <http://www.gnu.org/licenses/>. * SPDX-License-Identifier: GPL-3.0-or-later * ******************************************************************************/ package com.fujitsu.vdmj.ast.statements; import com.fujitsu.vdmj.ast.ASTNode; import com.fujitsu.vdmj.ast.lex.LexNameList; import com.fujitsu.vdmj.ast.lex.LexToken; import com.fujitsu.vdmj.ast.types.ASTType; import com.fujitsu.vdmj.ast.types.ASTUnknownType; public class ASTExternalClause extends ASTNode { private static final long serialVersionUID = 1L; public final LexToken mode; public final LexNameList identifiers; public final ASTType type; public ASTExternalClause(LexToken mode, LexNameList names, ASTType type) { this.mode = mode; this.identifiers = names; this.type = (type == null) ? new ASTUnknownType(names.get(0).location) : type; } @Override public String toString() { return mode.toString() + " " + identifiers + (type == null ? "" : ":" + type); } }
gpl-3.0
myfreeweb/antigravity
src/main/java/com/floatboth/antigravity/ui/BaseActivity.java
844
package com.floatboth.antigravity.ui; import android.annotation.TargetApi; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.os.Build; import android.view.Window; import android.view.WindowManager; import com.octo.android.robospice.SpiceManager; import com.floatboth.antigravity.net.ADNSpiceService; import com.floatboth.antigravity.R; public abstract class BaseActivity extends ActionBarActivity { private SpiceManager spiceManager = new SpiceManager(ADNSpiceService.class); @Override protected void onCreate(Bundle savedInstanceState) { spiceManager.start(this); super.onCreate(savedInstanceState); } @Override protected void onDestroy() { spiceManager.shouldStop(); super.onDestroy(); } protected SpiceManager getSpiceManager() { return spiceManager; } }
gpl-3.0
LilyPad/Bukkit-Connect
src/main/java/lilypad/bukkit/connect/login/LoginPayload.java
1832
package lilypad.bukkit.connect.login; import com.google.gson.Gson; import java.util.UUID; public class LoginPayload { private static final Gson gson = new Gson(); public static LoginPayload decode(String string) throws Exception { return gson.fromJson(string, LoginPayload.class); } public static String encode(LoginPayload payload) throws Exception { return gson.toJson(payload); } public static class Property { private String n; private String v; private String s; public Property() { // empty } public Property(String name, String value, String signature) { this.n = name; this.v = value; this.s = signature; } public String getName() { return this.n; } public String getValue() { return this.v; } public String getSignature() { return this.s; } } private String s; private String h; private String rIp; private int rP; private String n; private String u; private Property[] p; public LoginPayload() { // empty } public LoginPayload(String securityKey, String host, String realIp, int realPort, String name, String uuid, Property[] properties) { this.s = securityKey; this.h = host; this.rIp = realIp; this.rP = realPort; this.n = name; this.u = uuid; this.p = properties; } public String getSecurityKey() { return this.s; } public String getHost() { return this.h; } public String getRealIp() { return this.rIp; } public int getRealPort() { return this.rP; } public String getName() { return this.n; } public UUID getUUID() { return UUID.fromString(this.u.substring(0, 8) + "-" + this.u.substring(8, 12) + "-" + this.u.substring(12, 16) + "-" + this.u.substring(16, 20) + "-" + this.u.substring(20, 32)); } public Property[] getProperties() { return this.p; } }
gpl-3.0
CCAFS/MARLO
marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/RepIndGenderYouthFocusLevelDAO.java
2937
/***************************************************************** * This file is part of Managing Agricultural Research for Learning & * Outcomes Platform (MARLO). * MARLO is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * at your option) any later version. * MARLO 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 General Public License for more details. * You should have received a copy of the GNU General Public License * along with MARLO. If not, see <http://www.gnu.org/licenses/>. *****************************************************************/ package org.cgiar.ccafs.marlo.data.dao; import org.cgiar.ccafs.marlo.data.model.RepIndGenderYouthFocusLevel; import java.util.List; public interface RepIndGenderYouthFocusLevelDAO { /** * This method removes a specific repIndGenderYouthFocusLevel value from the database. * * @param repIndGenderYouthFocusLevelId is the repIndGenderYouthFocusLevel identifier. * @return true if the repIndGenderYouthFocusLevel was successfully deleted, false otherwise. */ public void deleteRepIndGenderYouthFocusLevel(long repIndGenderYouthFocusLevelId); /** * This method validate if the repIndGenderYouthFocusLevel identify with the given id exists in the system. * * @param repIndGenderYouthFocusLevelID is a repIndGenderYouthFocusLevel identifier. * @return true if the repIndGenderYouthFocusLevel exists, false otherwise. */ public boolean existRepIndGenderYouthFocusLevel(long repIndGenderYouthFocusLevelID); /** * This method gets a repIndGenderYouthFocusLevel object by a given repIndGenderYouthFocusLevel identifier. * * @param repIndGenderYouthFocusLevelID is the repIndGenderYouthFocusLevel identifier. * @return a RepIndGenderYouthFocusLevel object. */ public RepIndGenderYouthFocusLevel find(long id); /** * This method gets a list of repIndGenderYouthFocusLevel that are active * * @return a list from RepIndGenderYouthFocusLevel null if no exist records */ public List<RepIndGenderYouthFocusLevel> findAll(); /** * This method saves the information of the given repIndGenderYouthFocusLevel * * @param repIndGenderYouthFocusLevel - is the repIndGenderYouthFocusLevel object with the new information to be added/updated. * @return a number greater than 0 representing the new ID assigned by the database, 0 if the repIndGenderYouthFocusLevel was * updated * or -1 is some error occurred. */ public RepIndGenderYouthFocusLevel save(RepIndGenderYouthFocusLevel repIndGenderYouthFocusLevel); }
gpl-3.0
JTR8655/Meituan
meituan/src/main/java/com/yc/meituan/entity/SellerInfo.java
3146
package com.yc.meituan.entity; public class SellerInfo { private Integer sid; private String saccounts; private String spwd; private String saddress; private String sshopname; private String stype; private String sname; private String semail; private String slicense; private String sphone; private Integer status; private String temp1; private String temp2; public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getSaccounts() { return saccounts; } public void setSaccounts(String saccounts) { this.saccounts = saccounts == null ? null : saccounts.trim(); } public String getSpwd() { return spwd; } public void setSpwd(String spwd) { this.spwd = spwd == null ? null : spwd.trim(); } public String getSaddress() { return saddress; } public void setSaddress(String saddress) { this.saddress = saddress == null ? null : saddress.trim(); } public String getSshopname() { return sshopname; } public void setSshopname(String sshopname) { this.sshopname = sshopname == null ? null : sshopname.trim(); } public String getStype() { return stype; } public void setStype(String stype) { this.stype = stype == null ? null : stype.trim(); } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname == null ? null : sname.trim(); } public String getSemail() { return semail; } public void setSemail(String semail) { this.semail = semail == null ? null : semail.trim(); } public String getSlicense() { return slicense; } public void setSlicense(String slicense) { this.slicense = slicense == null ? null : slicense.trim(); } public String getSphone() { return sphone; } public void setSphone(String sphone) { this.sphone = sphone == null ? null : sphone.trim(); } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getTemp1() { return temp1; } public void setTemp1(String temp1) { this.temp1 = temp1 == null ? null : temp1.trim(); } public String getTemp2() { return temp2; } public void setTemp2(String temp2) { this.temp2 = temp2 == null ? null : temp2.trim(); } @Override public String toString() { return "SellerInfo [sid=" + sid + ", saccounts=" + saccounts + ", spwd=" + spwd + ", saddress=" + saddress + ", sshopname=" + sshopname + ", stype=" + stype + ", sname=" + sname + ", semail=" + semail + ", slicense=" + slicense + ", sphone=" + sphone + ", status=" + status + ", temp1=" + temp1 + ", temp2=" + temp2 + "]"; } }
gpl-3.0
kellerkindt/ShowCaseStandalone
src/com/kellerkindt/scs/listeners/CommandExecutorListener.java
8656
/* * ShowCaseStandalone - A Minecraft-Bukkit-API Shop Plugin * Copyright (C) 2016-08-16 22:43 +02 kellerkindt (Michael Watzko) <copyright at kellerkindt.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.kellerkindt.scs.listeners; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.kellerkindt.scs.commands.*; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.entity.Player; import com.kellerkindt.scs.Properties; import com.kellerkindt.scs.ShowCaseStandalone; import com.kellerkindt.scs.exceptions.MissingOrIncorrectArgumentException; import com.kellerkindt.scs.utilities.Term; public class CommandExecutorListener implements CommandExecutor, TabCompleter { private ShowCaseStandalone scs; private List<com.kellerkindt.scs.commands.Command> commands = new ArrayList<com.kellerkindt.scs.commands.Command>(); public CommandExecutorListener (ShowCaseStandalone scs) { this.scs = scs; // TODO commands.add(new Abort (scs, Properties.PERMISSION_USE)); commands.add(new About (scs, Properties.PERMISSION_USE)); commands.add(new Add (scs, Properties.PERMISSION_USE)); commands.add(new Amount (scs, Properties.PERMISSION_MANAGE)); commands.add(new Buy (scs, Properties.PERMISSION_CREATE_BUY)); commands.add(new Clear (scs, Properties.PERMISSION_ADMIN)); commands.add(new Destroy (scs, Properties.PERMISSION_ADMIN)); commands.add(new Disable (scs, Properties.PERMISSION_ADMIN)); commands.add(new Display (scs, Properties.PERMISSION_CREATE_DISPLAY)); commands.add(new Exchange (scs, Properties.PERMISSION_CREATE_EXCHANGE)); commands.add(new That (scs, Properties.PERMISSION_CREATE_EXCHANGE)); commands.add(new Get (scs, Properties.PERMISSION_MANAGE)); commands.add(new Help (scs, Properties.PERMISSION_USE, Properties.PERMISSION_ADMIN)); commands.add(new HoverText (scs, Properties.PERMISSION_MANAGE)); commands.add(new Last (scs, Properties.PERMISSION_USE)); commands.add(new com.kellerkindt.scs.commands.List (scs, Properties.PERMISSION_ADMIN)); commands.add(new Member (scs, Properties.PERMISSION_MANAGE)); commands.add(new Message (scs, Properties.PERMISSION_USE)); commands.add(new Owner (scs, Properties.PERMISSION_ADMIN)); commands.add(new Price (scs, Properties.PERMISSION_MANAGE)); commands.add(new Prune (scs, Properties.PERMISSION_ADMIN)); commands.add(new Purge (scs, Properties.PERMISSION_ADMIN)); commands.add(new Range (scs, Properties.PERMISSION_ADMIN)); commands.add(new Reload (scs, Properties.PERMISSION_ADMIN)); commands.add(new Remove (scs, Properties.PERMISSION_REMOVE)); commands.add(new Repair (scs, Properties.PERMISSION_REPAIR)); commands.add(new Report (scs, Properties.PERMISSION_ADMIN)); commands.add(new Sell (scs, Properties.PERMISSION_CREATE_SELL)); commands.add(new Undo (scs, Properties.PERMISSION_USE)); commands.add(new Unit (scs, Properties.PERMISSION_USE)); commands.add(new Version (scs, Properties.PERMISSION_USE)); } @Override public List<String> onTabComplete(CommandSender sender, Command command, String lable, String[] args) { List<String> list = null; // hasn't found a sub-command yet if (args.length < 1) { list = new ArrayList<String>(); for (com.kellerkindt.scs.commands.Command cmd : commands) { list.add(cmd.getName()); } } else if (args.length == 1) { list = new ArrayList<String>(); for (com.kellerkindt.scs.commands.Command cmd : commands) { if (cmd.getName().startsWith(args[0]) && cmd.hasPermissions(sender)) { list.add(cmd.getName()); } } } else if (args.length > 1) { com.kellerkindt.scs.commands.Command cmd = null; // check whether there is a suitable command for (com.kellerkindt.scs.commands.Command c : commands) { if (c.getName().equals(args[0]) && c.hasPermissions(sender)) { cmd = c; break; } } // get the commands tab complete if found if (cmd != null) { list = cmd.getTabCompletions(sender, Arrays.copyOfRange(args, 1, args.length)); } } return list; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { try { com.kellerkindt.scs.commands.Command cmd = null; // try to find the command if (args != null && args.length > 0) { for (com.kellerkindt.scs.commands.Command c : commands) { if (c.getName().equals(args[0])) { cmd = c; break; } } } if (cmd == null) { // let the sender know scs.sendMessage(sender, Term.ERROR_COMMAND_UNKNOWN.get()); return true; } if (!cmd.hasPermissions(sender)) { // let the sender know scs.sendMessage(sender, Term.ERROR_INSUFFICIENT_PERMISSION.get()); return true; } if (cmd.hasToBeAPlayer() && !(sender instanceof Player)) { // let the sender know scs.sendMessage(sender, Term.ERROR_EXECUTE_AS_PLAYER.get()); return true; } if (cmd.getMinArgumentCount() > (args.length-1)) { // let the sender know scs.sendMessage(sender, Term.ERROR_MISSING_OR_INCORRECT_ARGUMENT.get()); return true; } // execute it cmd.execute(sender, Arrays.copyOfRange(args, 1, args.length)); } catch (Throwable t) { // only print the exception if somehow expected if (!(t instanceof MissingOrIncorrectArgumentException)) { t.printStackTrace(); scs.sendMessage(sender, Term.ERROR_MISSING_OR_INCORRECT_ARGUMENT.get()); } else { scs.getLogger().warning("Invalid command call by "+sender.getName()+": "+command); scs.sendMessage(sender, t.getMessage()); } } return true; } }
gpl-3.0
infoneershalin/qaf
src/com/qmetry/qaf/automation/testng/dataprovider/QAFDataProvider.java
4307
/******************************************************************************* * QMetry Automation Framework provides a powerful and versatile platform to author * Automated Test Cases in Behavior Driven, Keyword Driven or Code Driven approach * * Copyright 2016 Infostretch Corporation * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. * * This program 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 General Public License for more details. * * 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 * * You should have received a copy of the GNU General Public License along with this program in the name of LICENSE.txt in the root folder of the distribution. If not, see https://opensource.org/licenses/gpl-3.0.html * * See the NOTICE.TXT file in root folder of this source files distribution * for additional information regarding copyright ownership and licenses * of other open source software / files used by QMetry Automation Framework. * * For any inquiry or need additional information, please contact support-qaf@infostretch.com *******************************************************************************/ package com.qmetry.qaf.automation.testng.dataprovider; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Values of this annotation parameters can be overridden by providing property * <code>&lt;tc_name&gt;.testdata</code>=&lt;value&gt; * <p> * The value contains comma separated parameter and value combination: * <code>&lt;tc_name&gt;.testdata</code>=&lt;param&gt;=value,&lt;param&gt;=value * Supported parameters are * <ul> * <li>datafile : data file url, csv or excel file url * <li>sheetname: sheet name for excel data file, default is the first sheet * <li>labelname: name of label, if data start and end cell marked with label in * excel sheet * <li>hasheaderrow: true/false, indicates excel sheet has header row * <li>sqlquery: database query, will not be used if data file provided. Must * required other db properties * </ul> * com.qmetry.qaf.automation.testng.dataprovider.QAFDataProvider.java * * @author chirag */ @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({ METHOD, TYPE }) public @interface QAFDataProvider { public enum params { DATAFILE, SHEETNAME, KEY, HASHEADERROW, SQLQUERY, BEANCLASS, JSON_DATA_TABLE, DATAPROVIDER, DATAPROVIDERCLASS; } public enum dataproviders { isfw_csv, isfw_database, isfw_excel, isfw_excel_table, isfw_json, isfw_property; } /** * Used to provide csv or excel file. Can be overridden by property * <code>&lt;tc_name&gt;.testdata</code> * * @return */ String dataFile() default ""; /** * Optional sheet name (value or property) for excel file. If not provided * first sheet will be considered. Can be overridden by property * <code>&lt;tc_name&gt;.testdata</code> * * @return */ String sheetName() default ""; /** * Optional flag to indicate excel data contains header row that need to be * skipped. Default value is false. Can be overridden by property * <code>&lt;tc_name&gt;.testdata</code> * * @return */ boolean hasHeaderRow() default false; /*** * Optional data label name in excel sheet. Required if want to provide data * start/end cell marked with label. Can be overridden by property * <code>&lt;tc_name&gt;.testdata</code> * * @return */ String key() default ""; /** * Used to provide database query. Will not be considered if data file is * provided. * * @return */ String sqlQuery() default ""; }
gpl-3.0
apycazo/playground
playground-snippets/src/main/java/com/github/apycazo/playground/snippets/SpringScheduler.java
1647
package com.github.apycazo.playground.snippets; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.stereotype.Component; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; @Slf4j @Configuration @EnableScheduling @PropertySource("classpath:application.properties") public class SpringScheduler implements SchedulingConfigurer { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(SpringScheduler.class); ctx.refresh(); } @Override public void configureTasks(ScheduledTaskRegistrar taskRegister) { taskRegister.setScheduler(taskExecutor()); } @Bean(destroyMethod="shutdown") public Executor taskExecutor() { return Executors.newScheduledThreadPool(100); } @Component public static class Task { private AtomicInteger count = new AtomicInteger(0); @Scheduled(cron = "${cli.cron}") public void scheduledAction () { log.info("Scheduler action run: {}", count.incrementAndGet()); } } }
gpl-3.0
simeaol/lojaspringmvc
.metadata/.plugins/org.eclipse.wst.server.core/tmp0/work/Catalina/localhost/loja/org/apache/jsp/WEB_002dINF/views/produtos/ok_jsp.java
3426
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/7.0.47 * Generated at: 2017-07-10 02:20:47 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp.WEB_002dINF.views.produtos; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class ok_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public void _jspInit() { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=utf-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n"); out.write("<!DOCTYPE html>\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\r\n"); out.write("<title>Livros de Java, Android, iPhone, PHP, Ruby e muito mais - Loja</title>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write("\t<h1>Produto cadastrado com sucesso !</h1>\r\n"); out.write("</body>\r\n"); out.write("</html>"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
gpl-3.0
gkeele21/topdawgsports
src/java/tds/commissioner/fantasy/control/fsLeague_modifyDraftView.java
3438
/* * registerView.java * * Created on July 3, 2008, 10:16 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package tds.commissioner.fantasy.control; import bglib.tags.ListBoxItem; import bglib.util.FSUtils; import tds.main.bo.*; import tds.main.control.BaseView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.List; /** * * @author grant.keele */ public class fsLeague_modifyDraftView extends BaseView { @Override public String process(HttpServletRequest request, HttpServletResponse response) { String page = super.process(request, response); if (page != null) { return page; } page = htmlPage; UserSession userSession = UserSession.getUserSession(request, response); HttpSession session = userSession.getHttpSession(); int fsLeagueID = FSUtils.getIntSessionAttribute(session, "commFSLeagueID", 0); if (fsLeagueID <= 0) { userSession.setErrorMessage("You have to select a league first."); return "fsLeagueView"; } FSLeague fsLeague = (FSLeague)session.getAttribute("commFSLeague"); String action = FSUtils.getRequestParameter(request, "action", ""); if (action.equals("delete")) { int round = FSUtils.getIntRequestParameter(request, "round", 0); int place = FSUtils.getIntRequestParameter(request, "place", 0); if (round > 0 && place > 0) { FSFootballDraft draftEntry = new FSFootballDraft(fsLeagueID, round, place); int retVal = draftEntry.deletePick(); } } // Retrieve draft results List<FSFootballDraft> leagueDraft = FSFootballDraft.getDraftResults(fsLeagueID); session.setAttribute("leagueDraft", leagueDraft); // Round List<ListBoxItem> items = new ArrayList<ListBoxItem>(); for (int x=0; x<=20; x++) { items.add(new ListBoxItem(""+x, ""+x, false)); } session.setAttribute("roundList", items); // Place items = new ArrayList<ListBoxItem>(); for (int x=1; x<=10; x++) { items.add(new ListBoxItem(""+x, ""+x, false)); } session.setAttribute("placeList", items); // Retrieve league teams List<FSTeam> teams = fsLeague.GetTeams(); items = new ArrayList<ListBoxItem>(); for (FSTeam team : teams) { items.add(new ListBoxItem(team.getTeamName(), ""+team.getFSTeamID(), false)); } session.setAttribute("teamList", items); // Players try { List<Player> players = Player.getPlayerList(null, " ps.PositionName,tm.DisplayName,p.LastName", null, fsLeague.getFSSeason().getSeasonID(),false); items = new ArrayList<ListBoxItem>(); for (Player player : players) { items.add(new ListBoxItem("(" + player.getPosition().getPositionName() + ") " + player.getTeam().getAbbreviation() + " - " + player.getFullName(), ""+player.getPlayerID(), false)); } session.setAttribute("playerList", items); } catch (Exception e) { e.printStackTrace(); } return page; } }
gpl-3.0
potty-dzmeia/db4o
src/db4oj.tests/src/com/db4o/test/TestHashMap.java
2123
/* This file is part of the db4o object database http://www.db4o.com Copyright (C) 2004 - 2011 Versant Corporation http://www.versant.com db4o is free software; you can redistribute it and/or modify it under the terms of version 3 of the GNU General Public License as published by the Free Software Foundation. db4o 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ package com.db4o.test; import java.util.*; import com.db4o.*; /** */ @decaf.Ignore(decaf.Platform.JDK11) public class TestHashMap { HashMap hm; public void configure(){ Db4o.configure().objectClass(this).cascadeOnUpdate(true); Db4o.configure().objectClass(this).cascadeOnDelete(true); } public void store(){ Test.deleteAllInstances(this); Test.deleteAllInstances(new Atom()); Test.deleteAllInstances(new com.db4o.config.Entry()); TestHashMap thm = new TestHashMap(); thm.hm = new HashMap(); thm.hm.put("t1", new Atom("t1")); thm.hm.put("t2", new Atom("t2")); Test.store(thm); } public void test(){ com.db4o.config.Entry checkEntries = new com.db4o.config.Entry(); TestHashMap thm = (TestHashMap)Test.getOne(this); Test.ensure(thm.hm.size() == 2); Test.ensure(thm.hm.get("t1").equals(new Atom("t1"))); Test.ensure(thm.hm.get("t2").equals(new Atom("t2"))); thm.hm.put("t2", new Atom("t3")); Test.store(thm); // System.out.println(Test.occurrences(checkEntries)); if(Test.COMPARE_INTERNAL_OK){ Test.ensureOccurrences(checkEntries, 2); Test.commit(); Test.ensureOccurrences(checkEntries, 2); Test.deleteAllInstances(this); Test.ensureOccurrences(checkEntries, 0); Test.rollBack(); Test.ensureOccurrences(checkEntries, 2); Test.deleteAllInstances(this); Test.ensureOccurrences(checkEntries, 0); Test.commit(); Test.ensureOccurrences(checkEntries, 0); } } }
gpl-3.0