hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
99e5783e58df742a6e7f2ce290df439e30039697
4,214
package com.xlite.codec; import com.xlite.bean.PersonBean; import com.xlite.codec.impl.DefaultRpcCodec; import com.xlite.common.ReflectUtil; import com.xlite.remoting.exchange.Request; import com.xlite.remoting.exchange.Response; import com.xlite.rpc.RpcRequest; import com.xlite.rpc.RpcResponse; import com.xlite.service.TestService; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import java.lang.reflect.Method; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; /** * <p> * 编解码测试类 * </p> * * @author gallenzhang * @since 2020/4/4 **/ public class DefaultRpcCodecTest { private Codec codec = new DefaultRpcCodec(); private Request request = null; private Request emptyParamRequest = null; private Response response = null; private PersonBean personBean = new PersonBean("吴轩",46); @Before public void request(){ String methodName = "testMethod"; request = new RpcRequest(); ((RpcRequest) request).setInterfaceName(TestService.class.getName()); ((RpcRequest) request).setMethodName(methodName); Method method = null; for(Method m : TestService.class.getDeclaredMethods()){ if(m.getName().equals(methodName)){ method = m; break; } } String parametersDesc = ReflectUtil.getMethodParamDesc(method); ((RpcRequest) request).setParametersDesc(parametersDesc); ((RpcRequest) request).setArguments(new Object[]{personBean,new Date(),33518L,new int[][]{}}); Map<String,String > attachments = new HashMap<>(); attachments.put("version","1.0"); attachments.put("group","test"); ((RpcRequest) request).setAttachments(attachments); } @Before public void emptyParamRequest(){ String methodName = "buildPerson"; emptyParamRequest = new RpcRequest(); ((RpcRequest) emptyParamRequest).setInterfaceName(TestService.class.getName()); ((RpcRequest) emptyParamRequest).setMethodName(methodName); Method method = null; for(Method m : TestService.class.getDeclaredMethods()){ if(m.getName().equals(methodName)){ method = m; break; } } String parametersDesc = ReflectUtil.getMethodParamDesc(method); ((RpcRequest) emptyParamRequest).setParametersDesc(parametersDesc); ((RpcRequest) emptyParamRequest).setArguments(new Object[0]); } @Before public void buildResponse(){ response = new RpcResponse(); ((RpcResponse) response).setProcessTime(1000); ((RpcResponse) response).setRequestId(new AtomicLong().getAndIncrement()); ((RpcResponse) response).setValue("响应成功啦"); } @After public void destroy(){ request = null; response = null; } /** * request 编码 */ @Test public void testEncodeRequest() throws IOException { byte[] bytes = codec.encode(request); System.out.println("request编码后长度:" + bytes.length); } /** * request 编码 */ @Test public void testEmptyParamEncodeRequest() throws IOException { byte[] bytes = codec.encode(emptyParamRequest); System.out.println("request编码后长度:" + bytes.length); } /** * request 解码 */ @Test public void testEmptyParamDecodeRequest() throws IOException { System.out.println(codec.decode(codec.encode(emptyParamRequest))); } /** * request 解码 */ @Test public void testDecodeRequest() throws IOException { System.out.println(codec.decode(codec.encode(request))); } /** * response 编码 */ @Test public void testEncodeResponse() throws IOException { byte[] bytes = codec.encode(response); System.out.println("response编码后长度:" + bytes.length); } /** * response 解码 */ @Test public void testDecodeResponse() throws IOException { System.out.println(codec.decode(codec.encode(response))); } }
27.363636
102
0.64262
708086105148daa55bc2ef0b0453d89a4fff95d6
12,986
package com.appier.sampleapp.common; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.AppOpsManager; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.net.Uri; import android.os.Build; import android.provider.Settings; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.LinearLayout; import com.appier.sampleapp.R; import java.util.Timer; import java.util.TimerTask; import static android.content.Context.WINDOW_SERVICE; public class FloatViewManager { private static final int REQUEST_CODE_DRAW_OVERLAY_PERMISSION = 5; private static boolean mIsFloatViewShowing; public static WindowManager.LayoutParams getLayoutParams() { WindowManager.LayoutParams floatViewLayoutParams = new WindowManager.LayoutParams(); floatViewLayoutParams.format = PixelFormat.TRANSLUCENT; floatViewLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; /* * Floating window requires different permissions in different API levels. * Be careful about setting correct permission. * Otherwise, the app will crash with WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running? * * References: * - https://blog.csdn.net/ltym2014/article/details/78860620 * - https://blog.csdn.net/ajgjagdasnbd/article/details/77982472 */ if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) { // <= Android 4.3 (API 18) floatViewLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE; } else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) { // Android 4.4 (API 19) to 7.0 (API 24) floatViewLayoutParams.type = WindowManager.LayoutParams.TYPE_TOAST; } else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N_MR1) { // Android 7.1 (API 25) floatViewLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE; } else { // >= Android 8.0 (API 26) floatViewLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; } floatViewLayoutParams.gravity = Gravity.CENTER; floatViewLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT; floatViewLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT; return floatViewLayoutParams; } /** * @return isPermissionGranted * This permission cannot be trusted on Android 8.0 and some devices of Android 8.1. * Please refer to the comments inside the implementation for more details. */ public static boolean canDrawOverlays(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { /* * < Android 6.0 (API 23) * ====================== * The permission is automatically granted for older APIs */ return true; } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { /* * Android 6.0 (API 23) to 7.1 (API 25) * ==================================== * `Settings.canDrawOverlays` is introduced since android M. */ return Settings.canDrawOverlays(context); } else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O_MR1) { /* * Android 8.0 (API 26) to 8.1 (API 27) * ==================================== * On 8.0, `Settings.canDrawOverlays` returns true but only when you wait for 5 to 15 seconds. [^1] * On 8.1 on some devices, we still can get false even if the permission was just received. [^2] * * To workaround, we firstly use `AppOpsManager`. [^3] * If it doesn't work, we can fall back to add an invisible overlay. * If an exception is thrown, the permission isn't granted. [^4][^5] * * References: * [1]: https://stackoverflow.com/a/49328532 * [2]: https://stackoverflow.com/a/55581534 * [3]: https://stackoverflow.com/a/51249708 * [4]: https://stackoverflow.com/a/46174872 * [5]: https://stackoverflow.com/questions/46173460/why-in-android-8-method-settings-candrawoverlays-returns-false-when-user-has */ if (Settings.canDrawOverlays(context)) { return true; } AppOpsManager appOpsMgr = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); int mode = appOpsMgr.checkOpNoThrow(AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW, android.os.Process.myUid(), context.getPackageName()); switch (mode) { case AppOpsManager.MODE_ALLOWED: // when granted and reopen the app return true; case AppOpsManager.MODE_ERRORED: // when the application does not have this permission return false; case AppOpsManager.MODE_IGNORED: // returned from permission request prompt to the application /* * For this case, the permission may or may not be granted. */ break; case AppOpsManager.MODE_DEFAULT: break; } try { WindowManager mgr = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // getSystemService might return null if (mgr == null) { return false; } View viewToAdd = new View(context); WindowManager.LayoutParams params = FloatViewManager.getLayoutParams(); viewToAdd.setLayoutParams(params); mgr.addView(viewToAdd, params); mgr.removeView(viewToAdd); /* * If the permission is not granted and user ignores the permission request prompt directly, there will be no exception. * In such special case (Android O & MODE_IGNORED & no exception thrown), * floating window totally works and bypass granting both `SYSTEM_ALERT_WINDOW` and `ACTION_MANAGE_OVERLAY_PERMISSION` permissions. */ return true; } catch (WindowManager.BadTokenException e) {} return false; } else { /* * > Android 8.1 (API 27) */ return Settings.canDrawOverlays(context); } } private Activity mActivity; private OnFloatViewEventListener mEventListener; private View mFloatView; private LinearLayout mContentContainer; private WindowManager mWindowManager; private WindowManager.LayoutParams mFloatViewLayoutParams; private boolean mFloatViewTouchConsumedByMove = false; private int mFloatViewLastX; private int mFloatViewLastY; private int mFloatViewFirstX; private int mFloatViewFirstY; @SuppressLint("InflateParams") public FloatViewManager(Activity activity, OnFloatViewEventListener eventListener) { this.mActivity = activity; this.mEventListener = eventListener; this.mFloatView = LayoutInflater .from(activity) .inflate(R.layout.template_floating_window, null); this.mContentContainer = this.mFloatView.findViewById(R.id.content_container); this.mFloatViewLayoutParams = FloatViewManager.getLayoutParams(); this.initializeEventBinding(); } private void initializeEventBinding() { Button buttonDismiss = this.mFloatView.findViewById(R.id.button_dismiss); buttonDismiss.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { close(); } }); this.mFloatView.setOnTouchListener(this.mFloatViewOnTouchListener); } public void requestDrawOverlayPermission() { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + mActivity.getPackageName())); mActivity.startActivityForResult(intent, REQUEST_CODE_DRAW_OVERLAY_PERMISSION); } public void handleActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_CODE_DRAW_OVERLAY_PERMISSION: { mEventListener.onDrawOverlayPermissionResult(FloatViewManager.canDrawOverlays(mActivity)); } } } public void open() { if (!mIsFloatViewShowing) { mIsFloatViewShowing = true; mActivity.runOnUiThread(new Runnable() { @Override public void run() { if (!mActivity.isFinishing()) { mWindowManager = (WindowManager) mActivity.getSystemService(WINDOW_SERVICE); if (mWindowManager != null) { mWindowManager.addView(mFloatView, mFloatViewLayoutParams); mEventListener.onOpen(mContentContainer); } } } }); } } public void openWithPermissionCheck() { if (FloatViewManager.canDrawOverlays(mActivity)) { try { open(); } catch (Exception e) { requestDrawOverlayPermission(); } } else { requestDrawOverlayPermission(); } } public void close() { close(0); } public void close(int closeDelay) { if (mIsFloatViewShowing) { mIsFloatViewShowing = false; new Timer().schedule(new TimerTask() { @Override public void run() { mActivity.runOnUiThread(new Runnable() { @Override public void run() { if (mWindowManager != null) { mWindowManager.removeViewImmediate(mFloatView); } mEventListener.onClose(mContentContainer); } }); } }, closeDelay); } } @SuppressWarnings("FieldCanBeLocal") private View.OnTouchListener mFloatViewOnTouchListener = new View.OnTouchListener() { @SuppressLint("ClickableViewAccessibility") @TargetApi(Build.VERSION_CODES.FROYO) @Override public boolean onTouch(View v, MotionEvent event) { WindowManager.LayoutParams prm = mFloatViewLayoutParams; int totalDeltaX = mFloatViewLastX - mFloatViewFirstX; int totalDeltaY = mFloatViewLastY - mFloatViewFirstY; switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: mFloatViewLastX = (int) event.getRawX(); mFloatViewLastY = (int) event.getRawY(); mFloatViewFirstX = mFloatViewLastX; mFloatViewFirstY = mFloatViewLastY; break; case MotionEvent.ACTION_UP: break; case MotionEvent.ACTION_MOVE: int deltaX = (int) event.getRawX() - mFloatViewLastX; int deltaY = (int) event.getRawY() - mFloatViewLastY; mFloatViewLastX = (int) event.getRawX(); mFloatViewLastY = (int) event.getRawY(); if (Math.abs(totalDeltaX) >= 5 || Math.abs(totalDeltaY) >= 5) { if (event.getPointerCount() == 1) { prm.x += deltaX; prm.y += deltaY; mFloatViewTouchConsumedByMove = true; if (mWindowManager != null) { mWindowManager.updateViewLayout(mFloatView, prm); } } else { mFloatViewTouchConsumedByMove = false; } } else { mFloatViewTouchConsumedByMove = false; } break; default: break; } return mFloatViewTouchConsumedByMove; } }; public interface OnFloatViewEventListener { void onOpen(LinearLayout contentContainer); void onDrawOverlayPermissionResult(boolean isPermissionGranted); void onClose(LinearLayout contentContainer); } }
42.299674
153
0.587402
7397367bf4937a77eb2007367d07bbae2a03cf64
439
package net.saisimon.agtms.web.dto.req; import java.util.List; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import lombok.Data; /** * 角色参数对象 * * @author saisimon * */ @Data public class RoleParam { private Long id; @NotBlank private String name; @NotNull private String path; private List<String> resources; private String remark; }
13.71875
46
0.67426
c309418eef4a84ec47c4f38a204cb727af1f2371
475
/** * */ package is2011.reproductor.modelo.listeners; /** * Evento con toda la informacion necesaria para borrar una cancion. * * @author Administrator * */ public class BorrarCancionEvent { /** La posicion que ocupa esta cancion*/ private int posicion; public BorrarCancionEvent(int posicion) { super(); this.posicion = posicion; } /** * @return the posicion */ public int getPosicion() { return posicion; } }
15.322581
69
0.631579
e1e5e7c6c151bae3d04a1a527568bac0c127ab70
6,388
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.clustercontroller.core; import com.yahoo.vdslib.state.NodeState; import com.yahoo.vdslib.state.Node; import com.yahoo.vespa.clustercontroller.core.database.ZooKeeperDatabase; import java.util.Map; public class ZooKeeperStressTest extends junit.framework.TestCase { private Object lock = new Object(); private int waitTime = 0; class LoadGiver extends Thread { ZooKeeperDatabase db; public int count = 0; public int errors = 0; public int index; public boolean stopNow = false; LoadGiver(ZooKeeperDatabase db, int index) { this.db = db; this.index = index; } public void doStop() { stopNow = true; } public void run() { try{ while (!this.isInterrupted() && !stopNow) { // Needs to take lock for each operation. Store new mastervote can not run at the same time as // another store new master vote as they kill the ephemeral node synchronized (lock) { if (db.isClosed()) { System.err.println(this + " Session broke"); break; } ++count; if (db.retrieveLatestSystemStateVersion() == null) { System.err.println("retrieveLatestSystemStateVersion() failed"); ++errors; } } Map<Node, NodeState> wantedStates; synchronized (lock) { if (db.isClosed()) { System.err.println(this + " Session broke"); break; } ++count; wantedStates = db.retrieveWantedStates(); if (wantedStates == null) { System.err.println("retrieveWantedStates() failed"); ++errors; } } synchronized (lock) { if (db.isClosed()) { System.err.println(this + " Session broke"); break; } ++count; if (!db.storeLatestSystemStateVersion(5)) { System.err.println("storeLastestSystemStateVersion() failed"); ++errors; } } synchronized (lock) { if (db.isClosed()) { System.err.println(this + " Session broke"); break; } ++count; if (!db.storeMasterVote(0)) { System.err.println("storeMasterVote() failed"); ++errors; } } synchronized (lock) { if (db.isClosed()) { System.err.println(this + " Session broke"); break; } if (wantedStates != null) { ++count; if (!db.storeWantedStates(wantedStates)) { System.err.println("storeWantedState() failed"); ++errors; } } } try{ Thread.sleep(waitTime); } catch (Exception e) {} } } catch (InterruptedException e) {} } public String toString() { return "LoadGiver(" + index + ": count " + count + ", errors " + errors + ")"; } } public void testNothing() throws Exception { // Stupid junit fails if there's testclass without tests } public void testZooKeeperStressed() throws Exception { // Disabled for now.: Unstable /* ZooKeeperTestServer zooKeeperServer = new ZooKeeperTestServer(); Database.DatabaseListener zksl = new Database.DatabaseListener() { public void handleZooKeeperSessionDown() { assertFalse("We lost session to ZooKeeper. Shouldn't happen", true); } public void handleMasterData(Map<Integer, Integer> data) { } }; VdsCluster cluster = new VdsCluster("mycluster", 10, 10, true); int timeout = 30000; ZooKeeperDatabase db = new ZooKeeperDatabase(cluster, 0, zooKeeperServer.getAddress(), timeout, zksl); Collection<LoadGiver> loadGivers = new ArrayList(); long time = System.currentTimeMillis(); for (int i = 0; i<10; ++i) { loadGivers.add(new LoadGiver(db, i)); } for (LoadGiver lg : loadGivers) { lg.start(); } for (int i = 0; i<30000; i += 100) { Thread.sleep(100); boolean failed = false; for (LoadGiver lg : loadGivers) { if (lg.errors > 0) { failed = true; } } if (failed) i += 5000; } int throughput = 0; int errors = 0; for (LoadGiver lg : loadGivers) { assertTrue("Error check prior to attempting to stop: " + lg.toString(), lg.errors == 0); } for (LoadGiver lg : loadGivers) { lg.doStop(); throughput += lg.count; errors += lg.errors; } time = System.currentTimeMillis() - time; Double timesecs = new Double(time / 1000.0); if (timesecs > 0.001) { System.err.println("Throughput is " + (throughput / timesecs) + "msgs/sec, " + errors + " errors, total messages sent: " + throughput + ", waittime = " + waitTime); } else { System.err.println("too small time period " + time + " to calculate throughput"); } //try{ Thread.sleep(5000); } catch (Exception e) {} for (LoadGiver lg : loadGivers) { lg.join(); } for (LoadGiver lg : loadGivers) { System.err.println(lg); } // Disabling test. This fails occasionally for some reason. for (LoadGiver lg : loadGivers) { // assertTrue("Error check after having stopped: " + lg.toString(), lg.errors == 0); } */ } }
40.43038
176
0.493425
30b0ca21238f98ba9ef17dee171d185c202af7f6
6,348
package net.buycraft.plugin.bukkit.signs.buynow; import lombok.Getter; import net.buycraft.plugin.bukkit.BuycraftPlugin; import net.buycraft.plugin.bukkit.tasks.BuyNowSignUpdater; import net.buycraft.plugin.bukkit.tasks.SendCheckoutLink; import net.buycraft.plugin.bukkit.tasks.SignUpdateApplication; import net.buycraft.plugin.bukkit.util.SerializedBlockLocation; import net.buycraft.plugin.data.Package; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerInteractEvent; import java.util.*; public class BuyNowSignListener implements Listener { @Getter private final Map<UUID, SerializedBlockLocation> settingUpSigns = new HashMap<>(); private final BuycraftPlugin plugin; private boolean signLimited = false; public BuyNowSignListener(BuycraftPlugin plugin) { this.plugin = plugin; } @EventHandler public void onSignChange(SignChangeEvent event) { boolean relevant; try { relevant = event.getLine(0).equalsIgnoreCase("[buycraft_buy]"); } catch (IndexOutOfBoundsException e) { return; } if (!relevant) return; if (!event.getPlayer().hasPermission("buycraft.admin")) { event.getPlayer().sendMessage(ChatColor.RED + "You don't have permission to create this sign."); return; } for (int i = 0; i < 4; i++) { event.setLine(i, ""); } settingUpSigns.put(event.getPlayer().getUniqueId(), SerializedBlockLocation.fromBukkitLocation(event.getBlock().getLocation())); event.getPlayer().sendMessage(ChatColor.GREEN + "Navigate to the item you want to set this sign for."); plugin.getViewCategoriesGUI().open(event.getPlayer()); } @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { if (event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock() != null) { Block b = event.getClickedBlock(); if (!(b.getType() == Material.WALL_SIGN || b.getType() == Material.SIGN_POST)) return; SerializedBlockLocation sbl = SerializedBlockLocation.fromBukkitLocation(event.getClickedBlock().getLocation()); for (SavedBuyNowSign s : plugin.getBuyNowSignStorage().getSigns()) { if (s.getLocation().equals(sbl)) { // Signs are rate limited in order to limit API calls issued. if (signLimited) { return; } signLimited = true; Bukkit.getScheduler().runTaskAsynchronously(plugin, new SendCheckoutLink(plugin, s.getPackageId(), event.getPlayer())); Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { @Override public void run() { signLimited = false; } }, 4); return; } } } } @EventHandler public void onInventoryClose(final InventoryCloseEvent event) { if (settingUpSigns.containsKey(event.getPlayer().getUniqueId())) { Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { @Override public void run() { if ((event.getPlayer().getOpenInventory().getTopInventory() == null || !event.getPlayer().getOpenInventory().getTopInventory().getTitle().startsWith("Buycraft: ")) && settingUpSigns.remove(event.getPlayer().getUniqueId()) != null) { event.getPlayer().sendMessage(ChatColor.RED + "Buy sign set up cancelled."); } } }, 3); } } @EventHandler public void onBlockBreak(BlockBreakEvent event) { if (event.getBlock().getType() == Material.WALL_SIGN || event.getBlock().getType() == Material.SIGN_POST) { if (plugin.getBuyNowSignStorage().containsLocation(event.getBlock().getLocation())) { if (!event.getPlayer().hasPermission("buycraft.admin")) { event.getPlayer().sendMessage(ChatColor.RED + "You don't have permission to break this sign."); event.setCancelled(true); return; } if (plugin.getBuyNowSignStorage().removeSign(event.getBlock().getLocation())) { event.getPlayer().sendMessage(ChatColor.RED + "Removed buy now sign!"); } } return; } for (BlockFace face : SignUpdateApplication.FACES) { Location onFace = event.getBlock().getRelative(face).getLocation(); if (plugin.getBuyNowSignStorage().containsLocation(onFace)) { if (!event.getPlayer().hasPermission("buycraft.admin")) { event.getPlayer().sendMessage(ChatColor.RED + "You don't have permission to break this sign."); event.setCancelled(true); return; } if (plugin.getBuyNowSignStorage().removeSign(onFace)) { event.getPlayer().sendMessage(ChatColor.RED + "Removed buy now sign!"); } } } } public void doSignSetup(Player player, Package p) { SerializedBlockLocation sbl = settingUpSigns.remove(player.getUniqueId()); if (sbl == null) return; Block b = sbl.toBukkitLocation().getBlock(); if (!(b.getType() == Material.WALL_SIGN || b.getType() == Material.SIGN_POST)) return; plugin.getBuyNowSignStorage().addSign(new SavedBuyNowSign(sbl, p.getId())); Bukkit.getScheduler().runTask(plugin, new BuyNowSignUpdater(plugin)); } }
39.428571
136
0.603655
e1ec79c09c1da0beccf9723b0246cfa4a698d66b
208
package heranca.cenario1; public class Passaro extends Animal { public void voar() { System.out.println("Voando!"); } public void piar() { System.out.println("Piando!"); } }
17.333333
38
0.600962
60382d1145a79e0a5677c9a093ab3dccf98f7605
2,972
/* MIT License Copyright(c) 2021 Kyle Givler https://github.com/JoyfulReaper 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.kgivler.javabot; import com.kgivler.javabot.command.CommandContext; import com.kgivler.javabot.command.ICommand; import com.kgivler.javabot.command.commands.PingCommand; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; public class CommandManager { private final List<ICommand> commands = new ArrayList<>(); // TODO USE MAP public CommandManager() { addCommand(new PingCommand()); } private void addCommand(ICommand cmd) { boolean nameFound = this.commands.stream().anyMatch((it) -> it.getName().equalsIgnoreCase(cmd.getName())); if(nameFound) { throw new IllegalArgumentException("A command with this name is already present"); } commands.add(cmd); } @Nullable private ICommand getCommand(String search) { String searchLower = search.toLowerCase(); for (ICommand cmd : this.commands) { if (cmd.getName().equals(searchLower) || cmd.getAliases().contains(searchLower)) { return cmd; } } return null; } void handle(GuildMessageReceivedEvent event) { String[] split = event.getMessage().getContentRaw() .replaceFirst("(?i)" + Pattern.quote(System.getProperty("prefix")), "") .split("\\s+"); String invoke = split[0].toLowerCase(); ICommand cmd = this.getCommand(invoke); if(cmd != null) { event.getChannel().sendTyping().queue(); List<String> args = Arrays.asList(split).subList(1, split.length); CommandContext ctx = new CommandContext(event, args); cmd.handle(ctx); } } }
33.772727
114
0.696837
f055850bd8863f8064e5deb4e92918e80d37d2d5
1,070
public class MainClass { public static void main(String[] args) { // TODO Auto-generated method stub //Assuming stock of each sport is 2 Sports sp1=new IndoorSports(); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Billiards(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Carrom(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Badminton(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); Sports sp2=new OutdoorSports(); System.out.println("\nTotal Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new Trekking(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new Cricket(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new HighJump(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new LongJump(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); } }
35.666667
76
0.729907
e89c4cb3ff93e8bfb6e306cc98ea9193f3e9e630
3,575
package com.verdantartifice.primalmagick.client.gui.widgets.grimoire; import java.util.Collections; import javax.annotation.Nonnull; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import com.verdantartifice.primalmagick.PrimalMagick; import com.verdantartifice.primalmagick.client.util.GuiUtils; import com.verdantartifice.primalmagick.common.attunements.AttunementThreshold; import com.verdantartifice.primalmagick.common.items.ItemsPM; import com.verdantartifice.primalmagick.common.sources.Source; import com.verdantartifice.primalmagick.common.wands.WandCap; import com.verdantartifice.primalmagick.common.wands.WandCore; import com.verdantartifice.primalmagick.common.wands.WandGem; import net.minecraft.Util; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.components.AbstractWidget; import net.minecraft.client.gui.narration.NarrationElementOutput; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; /** * Display widget for showing attunement threshold bonuses. * * @author Daedalus4096 */ public class AttunementThresholdWidget extends AbstractWidget { protected static final ItemStack WAND_STACK = Util.make(new ItemStack(ItemsPM.MODULAR_WAND.get()), stack -> { ItemsPM.MODULAR_WAND.get().setWandCore(stack, WandCore.HEARTWOOD); ItemsPM.MODULAR_WAND.get().setWandCap(stack, WandCap.IRON); ItemsPM.MODULAR_WAND.get().setWandGem(stack, WandGem.APPRENTICE); }); protected final Source source; protected final AttunementThreshold threshold; protected final ResourceLocation texture; protected final Component tooltipText; public AttunementThresholdWidget(@Nonnull Source source, @Nonnull AttunementThreshold threshold, int x, int y) { super(x, y, 18, 18, Component.empty()); this.source = source; this.threshold = threshold; this.texture = new ResourceLocation(PrimalMagick.MODID, "textures/attunements/threshold_" + source.getTag() + "_" + threshold.getTag() + ".png"); this.tooltipText = Component.translatable("primalmagick.attunement.threshold." + source.getTag() + "." + threshold.getTag()); } @Override public void renderButton(PoseStack matrixStack, int p_renderButton_1_, int p_renderButton_2_, float p_renderButton_3_) { Minecraft mc = Minecraft.getInstance(); if (this.threshold == AttunementThreshold.MINOR) { // Render casting wand into GUI mc.getItemRenderer().renderGuiItem(WAND_STACK, this.x + 1, this.y + 1); } else { // Render the icon appropriate for this widget's source and threshold matrixStack.pushPose(); RenderSystem.setShaderTexture(0, this.texture); matrixStack.translate(this.x, this.y, 0.0F); matrixStack.scale(0.0703125F, 0.0703125F, 0.0703125F); this.blit(matrixStack, 0, 0, 0, 0, 255, 255); matrixStack.popPose(); } if (this.isHoveredOrFocused()) { // Render tooltip GuiUtils.renderCustomTooltip(matrixStack, Collections.singletonList(this.tooltipText), this.x, this.y); } } @Override public boolean mouseClicked(double p_mouseClicked_1_, double p_mouseClicked_3_, int p_mouseClicked_5_) { // Disable click behavior return false; } @Override public void updateNarration(NarrationElementOutput output) { } }
42.559524
153
0.726434
774cfe946c3fa434200ca452c88b76e84ff9b11f
1,104
package server.rest.responses; import server.model.HRPositionRole; import java.util.ArrayList; /** * Response Object for HR Position Role REST API view link */ public class HRPositionRoleResponse extends Response { private ArrayList<HRPositionRole> data; /** * Creates an error response object * @param msg Error message * @return Error response object */ public static HRPositionRoleResponse positionRoleFailure(String msg) { ArrayList<HRPositionRole> roles = new ArrayList<HRPositionRole>(); HRPositionRoleResponse response = new HRPositionRoleResponse(roles); response.setError(true); response.setErrorMessage(msg); return response; } /** * Creates a HRPositionRole object * @param roles The roles that are supposed to be part of the Response */ public HRPositionRoleResponse(ArrayList<HRPositionRole> roles) { this.data = roles; } /** * Gets all the roles * @return List of roles */ public ArrayList<HRPositionRole> getData() { return data; } }
25.674419
76
0.675725
19a2a6f3835bbef3521f737bf6a5864ae3055c9a
949
package com.ldtteam.animatrix.handler; import com.ldtteam.animatrix.entity.IEntityAnimatrix; import net.minecraft.client.Minecraft; import net.minecraft.entity.Entity; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class ClientTickEventHandler { @SubscribeEvent public void onTickClientTick(final TickEvent.ClientTickEvent event) { if (Minecraft.getMinecraft().world == null) return; Minecraft.getMinecraft() .world .getEntities(Entity.class, IEntityAnimatrix.class::isInstance) .forEach(e -> { ((IEntityAnimatrix)e) .getAnimatrixModel() .getAnimator() .onUpdate(); } ); } }
27.911765
72
0.672287
6bc7389a837daf0ba84c4ddbaf8702ffc7581f07
497
package com.hexagonaldemo.ticketapi.common.model; import java.util.stream.Stream; public enum Status { ACTIVE(1), PASSIVE(0), DELETED(-1); private final Integer value; Status(Integer value) { this.value = value; } public Integer getValue() { return value; } public static Status of(Integer value) { return Stream.of(Status.values()) .filter(status -> status.value.equals(value)).findFirst().orElseThrow(); } }
19.115385
88
0.619718
d482de9359ee484fc05e6fa2718d077b2108a8a6
6,343
/* * Copyright 2017 NEOautus Ltd. (http://neoautus.com) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.lucidj.displaymanager.renderer; import com.vaadin.server.ClientConnector; import com.vaadin.ui.AbstractComponent; import com.vaadin.ui.AbstractOrderedLayout; import com.vaadin.ui.VerticalLayout; import com.ejt.vaadin.sizereporter.ComponentResizeEvent; import com.ejt.vaadin.sizereporter.ComponentResizeListener; import com.ejt.vaadin.sizereporter.SizeReporter; import org.lucidj.api.core.DisplayManager; import org.lucidj.api.core.ServiceContext; import org.lucidj.api.vui.ObjectRenderer; import org.lucidj.api.vui.Renderer; import org.lucidj.api.vui.RendererFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.vaadin.jouni.restrain.Restrain; import java.util.HashMap; import java.util.Map; import org.osgi.framework.BundleContext; public class DisplayManagerRenderer implements Renderer, DisplayManager.ObjectEventListener, ComponentResizeListener { private final static Logger log = LoggerFactory.getLogger (DisplayManagerRenderer.class); private DisplayManagerRenderer self = this; private Map<Object, ObjectRenderer> active_renderers = new HashMap<> (); private AbstractOrderedLayout layout; private SizeReporter sizeReporter; private Restrain restrain; private int current_height = -1; private RendererFactory rendererFactory; public DisplayManagerRenderer (BundleContext bundleContext, ServiceContext serviceContext) { rendererFactory = serviceContext.getService (bundleContext, RendererFactory.class); layout = new VerticalLayout (); layout.addStyleName ("renderer-layout"); layout.addAttachListener (new ClientConnector.AttachListener () { @Override public void attach (ClientConnector.AttachEvent attachEvent) { // Enable SizeReporter for the whole DisplayManagerRenderer sizeReporter = new SizeReporter (layout); sizeReporter.addResizeListener (self); // Minimum size restrain = new Restrain (layout); } }); layout.addDetachListener (new ClientConnector.DetachListener () { @Override public void detach (ClientConnector.DetachEvent detachEvent) { sizeReporter.removeResizeListener (self); } }); log.info ("new DisplayManagerRenderer () base_layout={}", layout); } private String get_object_hash (Object obj) { return (obj.getClass().getName() + "#" + Integer.toHexString (obj.hashCode())); } @Override // ObjectEventListener public void restrain () { if (current_height != -1) { log.info ("<<RESTRAIN>> height={}", current_height); restrain.setMinHeight (current_height + "px"); } } @Override // ObjectEventListener public void release () { log.info ("<<RELEASE>> height={}", current_height); restrain.setMinHeight ("auto"); } @Override // ObjectEventListener public Object addingObject (Object obj, int index) { ObjectRenderer renderer = rendererFactory.newRenderer (obj); // TODO: VAADIN SESSION HANDLING layout.addComponent (renderer, index); active_renderers.put (get_object_hash (obj), renderer); log.info ("<<RENDERER>> addingObject() layout height = {} {}", layout.getHeight (), layout.getHeightUnits ().toString ()); log.info ("Add new renderer {}: obj={} or={} /// active_renderers={}", this, get_object_hash (obj), renderer, active_renderers); return (obj); } @Override // ObjectEventListener public void changingObject (Object obj) { ObjectRenderer or = active_renderers.get (get_object_hash (obj)); log.info ("changingObject: active_renderers={} obj={} or={} /// active_renderers={}", get_object_hash (obj), or, active_renderers); or.updateComponent (); log.info ("<<RENDERER>> changingObject() layout height = {} {}", layout.getHeight (), layout.getHeightUnits ().toString ()); } @Override // ObjectEventListener public void removingObject (Object obj, int index) { String hash = get_object_hash (obj); ObjectRenderer renderer = active_renderers.get (hash); log.info ("removingObject: obj={} or={} layout={} /// active_renderers={}", hash, renderer, layout, active_renderers); // Only deal with valid renderers if (renderer != null) { // TODO: VAADIN SESSION HANDLING layout.removeComponent (renderer); log.info ("<<RENDERER>> removingObject() layout height = {} {}", layout.getHeight (), layout.getHeightUnits ().toString ()); } active_renderers.remove (hash); } public static boolean isCompatible (Object object) { return (object instanceof DisplayManager); } @Override // Renderer public void objectLinked (Object obj) { DisplayManager om = (DisplayManager)obj; om.setObjectEventListener (this); } @Override // Renderer public void objectUnlinked () { // Not used } @Override // Renderer public AbstractComponent renderingComponent () { return (layout); } @Override // Renderer public void objectUpdated () { // Not used } @Override // ComponentResizeListener public void sizeChanged (ComponentResizeEvent componentResizeEvent) { log.debug ("<<RESIZE>> width={} height={}", componentResizeEvent.getWidth(), componentResizeEvent.getHeight()); current_height = componentResizeEvent.getHeight(); } } // EOF
32.528205
139
0.668138
5be1824331471b14f6b88a67b382e4f3b4a9e953
1,278
/* * Copyright 2016 lizhaotailang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.marktony.zhihudaily.data.source.datasource; import android.support.annotation.NonNull; import com.marktony.zhihudaily.data.GuokrHandpickContentResult; /** * Created by lizhaotailang on 2017/5/26. * * Main entry point for accessing {@link GuokrHandpickContentResult} data. */ public interface GuokrHandpickContentDataSource { interface LoadGuokrHandpickContentCallback { void onContentLoaded(@NonNull GuokrHandpickContentResult content); void onDataNotAvailable(); } void getGuokrHandpickContent(int id, @NonNull LoadGuokrHandpickContentCallback callback); void saveContent(@NonNull GuokrHandpickContentResult content); }
29.045455
93
0.763693
c712ac876fb877eefba69698d212a6aaee970d46
404
package multpoo; import java.util.Scanner; import mult.multNum; public class multpoo { public static void main(String[] args) { int valor; Scanner sc = new Scanner(System.in); System.out.println("Digite o valor da tabuada:"); valor=sc.nextInt(); multNum novomultNum=new multNum(); novomultNum.mult(valor); sc.close(); } }
22.444444
59
0.596535
fc0feb347c1015a1f7284510a373dc469885d430
1,838
package graphql.kickstart.servlet.core; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** @author Andrew Potter */ public interface GraphQLServletListener { /** * Called this method when the request started processing. * @param request http request * @param response http response * @return request callback or {@literal null} */ default RequestCallback onRequest(HttpServletRequest request, HttpServletResponse response) { return null; } /** * The callback which used to add additional listeners for GraphQL request execution. */ interface RequestCallback { /** * Called right before the response will be written and flushed. Can be used for applying some * changes to the response object, like adding response headers. * @param request http request * @param response http response */ default void beforeFlush(HttpServletRequest request, HttpServletResponse response) {} /** * Called when GraphQL invoked successfully and the response was written already. * @param request http request * @param response http response */ default void onSuccess(HttpServletRequest request, HttpServletResponse response) {} /** * Called when GraphQL was failed and the response was written already. * @param request http request * @param response http response */ default void onError( HttpServletRequest request, HttpServletResponse response, Throwable throwable) {} /** * Called finally once on both success and failed GraphQL invocation. The response is also * already written. * @param request http request * @param response http response */ default void onFinally(HttpServletRequest request, HttpServletResponse response) {} } }
32.821429
98
0.718716
90713d0de581ca4f582f824baf5e0a6e4f090948
705
package com.skytala.eCommerce.domain.humanres.relations.responsibilityType.event; import com.skytala.eCommerce.framework.pubsub.Event; import com.skytala.eCommerce.domain.humanres.relations.responsibilityType.model.ResponsibilityType; public class ResponsibilityTypeAdded implements Event{ private ResponsibilityType addedResponsibilityType; private boolean success; public ResponsibilityTypeAdded(ResponsibilityType addedResponsibilityType, boolean success){ this.addedResponsibilityType = addedResponsibilityType; this.success = success; } public boolean isSuccess() { return success; } public ResponsibilityType getAddedResponsibilityType() { return addedResponsibilityType; } }
28.2
99
0.836879
ae68e74391ac6c89a2ba608f3b0644296e90d3b4
509
package ru.swayfarer.swl2.asm.transfomer.injection; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Отметить параметер как ссылку, по которой будет доступна работа с результатом работы метода-цели иньекции * <br> См {@link InjectionAsm} * @author swayfarer * */ @Retention(RUNTIME) @Target(PARAMETER) public @interface ReturnRef {}
28.277778
109
0.764244
0e9ca5ed9ebb02b46047d4ec96962cf01572a4ed
266
package local.kmcgeeka.javaorders.repositories; import local.kmcgeeka.javaorders.models.Payments; import org.springframework.data.repository.CrudRepository; public interface PaymentsRepository extends CrudRepository<Payments, Long> { //custom methods only }
22.166667
74
0.827068
b0fd74638fe55042e633116b375ef745be592e5f
790
package com.bdxh.school.service; import com.bdxh.common.support.IService; import com.bdxh.school.dto.BlackUrlQueryDto; import com.bdxh.school.entity.BlackUrl; import com.bdxh.school.vo.BlackUrlShowVo; import com.github.pagehelper.PageInfo; import org.springframework.stereotype.Service; import java.util.List; /** * @Description: 业务层接口 * @Author Kang * @Date 2019-04-11 09:56:14 */ @Service public interface BlackUrlService extends IService<BlackUrl> { /** * 查询所有数量 */ Integer getBlackUrlAllCount(); /** * 批量删除方法 */ Boolean batchDelBlackUrlInIds(List<Long> id); /** * 分页查询黑名单信息 */ PageInfo<BlackUrlShowVo> findBlackInConditionPaging(BlackUrlQueryDto blackQueryDto); List<BlackUrl> findBlackInList(String schoolCode); }
20.25641
88
0.718987
154baa6eb9909cef70a61b20226cf203cca87387
616
package io.apicurio.bot.util; import io.apicurio.bot.cache.IssueNotification; import io.apicurio.bot.cache.PullRequestNotification; import io.quarkus.qute.CheckedTemplate; import io.quarkus.qute.TemplateInstance; import java.util.Set; @CheckedTemplate public final class Templates { public static native TemplateInstance triageIssueWelcome(Set<String> reviewers); public static native TemplateInstance triagePRWelcome(Set<String> reviewers); public static native TemplateInstance chatNotifyReview(Set<IssueNotification> issues, Set<PullRequestNotification> prs); private Templates() { } }
28
124
0.805195
11a02b3776d1adf22d62105d8c12db42ba9160cd
5,724
/* * Copyright 2018 The GraphicsFuzz Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphicsfuzz.reducer.reductionopportunities; import com.graphicsfuzz.common.ast.TranslationUnit; import com.graphicsfuzz.common.ast.decl.ScalarInitializer; import com.graphicsfuzz.common.ast.expr.BinOp; import com.graphicsfuzz.common.ast.expr.BinaryExpr; import com.graphicsfuzz.common.ast.expr.IntConstantExpr; import com.graphicsfuzz.common.ast.expr.VariableIdentifierExpr; import com.graphicsfuzz.common.ast.stmt.BlockStmt; import com.graphicsfuzz.common.ast.stmt.DeclarationStmt; import com.graphicsfuzz.common.ast.stmt.ForStmt; import com.graphicsfuzz.common.ast.stmt.Stmt; import com.graphicsfuzz.common.transformreduce.ShaderJob; import com.graphicsfuzz.common.typing.ScopeTreeBuilder; import com.graphicsfuzz.common.util.ListConcat; import com.graphicsfuzz.util.Constants; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Optional; public class LoopMergeReductionOpportunities extends ScopeTreeBuilder { private final List<LoopMergeReductionOpportunity> opportunities; private LoopMergeReductionOpportunities() { this.opportunities = new LinkedList<>(); } static List<LoopMergeReductionOpportunity> findOpportunities( ShaderJob shaderJob, ReducerContext context) { return shaderJob.getShaders() .stream() .map(item -> findOpportunitiesForShader(item)) .reduce(Arrays.asList(), ListConcat::concatenate); } private static List<LoopMergeReductionOpportunity> findOpportunitiesForShader( TranslationUnit tu) { LoopMergeReductionOpportunities finder = new LoopMergeReductionOpportunities(); finder.visit(tu); return finder.opportunities; } @Override public void visitBlockStmt(BlockStmt block) { enterBlockStmt(block); checkForLoopMergeReductionOpportunities(block); for (Stmt child : block.getStmts()) { visit(child); } leaveBlockStmt(block); } private void checkForLoopMergeReductionOpportunities(BlockStmt block) { Optional<Stmt> prev = Optional.empty(); for (Stmt current : block.getStmts()) { if (prev.isPresent() && canMergeLoops(prev.get(), current)) { opportunities.add(new LoopMergeReductionOpportunity((ForStmt) prev.get(), (ForStmt) current, block, getVistitationDepth())); } prev = Optional.of(current); } } private boolean canMergeLoops(Stmt first, Stmt second) { if (!(first instanceof ForStmt && second instanceof ForStmt)) { return false; } ForStmt firstLoop = (ForStmt) first; ForStmt secondLoop = (ForStmt) second; Optional<String> commonLoopCounter = checkForCommonLoopCounter(firstLoop, secondLoop); if (!commonLoopCounter.isPresent()) { return false; } if (!commonLoopCounter.get().startsWith(Constants.SPLIT_LOOP_COUNTER_PREFIX)) { return false; } if (!hasRegularLoopGuard(firstLoop, commonLoopCounter.get())) { return false; } if (!hasRegularLoopGuard(secondLoop, commonLoopCounter.get())) { return false; } final Integer firstLoopEnd = new Integer(((IntConstantExpr) ((BinaryExpr) firstLoop.getCondition()).getRhs()).getValue()); final BinOp firstLoopOp = ((BinaryExpr) firstLoop.getCondition()).getOp(); final Integer secondLoopStart = new Integer(((IntConstantExpr) ((ScalarInitializer) ((DeclarationStmt) secondLoop.getInit()).getVariablesDeclaration().getDeclInfo(0) .getInitializer()).getExpr()).getValue()); assert firstLoopOp == BinOp.LT || firstLoopOp == BinOp.GT : "Unexpected operator in split loops."; return firstLoopEnd.equals(secondLoopStart); } private boolean hasRegularLoopGuard(ForStmt loop, String counterName) { if (!(loop.getCondition() instanceof BinaryExpr)) { return false; } final BinaryExpr guard = (BinaryExpr) loop.getCondition(); if (!(guard.getOp() == BinOp.LT || guard.getOp() == BinOp.GT)) { return false; } if (!(guard.getLhs() instanceof VariableIdentifierExpr)) { return false; } if (!(guard.getRhs() instanceof IntConstantExpr)) { return false; } return ((VariableIdentifierExpr) guard.getLhs()).getName().equals(counterName); } private Optional<String> checkForCommonLoopCounter(ForStmt firstLoop, ForStmt secondLoop) { Optional<String> firstLoopCounter = extractLoopCounter(firstLoop); Optional<String> secondLoopCounter = extractLoopCounter(secondLoop); return firstLoopCounter.isPresent() && secondLoopCounter.isPresent() && firstLoopCounter.get().equals(secondLoopCounter.get()) ? firstLoopCounter : Optional.empty(); } private Optional<String> extractLoopCounter(ForStmt loop) { if (!(loop.getInit() instanceof DeclarationStmt)) { return Optional.empty(); } final DeclarationStmt init = (DeclarationStmt) loop.getInit(); if (init.getVariablesDeclaration().getNumDecls() != 1) { return Optional.empty(); } return Optional.of(init.getVariablesDeclaration().getDeclInfo(0).getName()); } }
36.227848
100
0.72327
0a5feea6afb9a1810a557f782b69b0d7333d2213
2,612
package org.zenframework.easyservices.net; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Collection; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.zenframework.easyservices.util.ThreadUtil; import org.zenframework.easyservices.util.io.BlockInputStream; import org.zenframework.easyservices.util.io.BlockOutputStream; import org.zenframework.easyservices.util.thread.Task; @RunWith(Parameterized.class) public class TcpServerTest extends AbstractTcpServerTest { private static final int DATA_SIZE = 15000; private static final int THREADS = 100; @Parameterized.Parameters(name = "#{index} server-blocking: {0}, client-blocking: {1}") public static Collection<Object[]> params() { return Arrays.asList(new Object[] { false, false }, new Object[] { false, true }, new Object[] { true, false }, new Object[] { true, true }); } private final boolean clientBlocking; private final byte[] data = new byte[DATA_SIZE]; public TcpServerTest(boolean serverBlocking, boolean clientBlocking) { super(serverBlocking); this.clientBlocking = clientBlocking; } @Override public void setUp() throws Exception { super.setUp(); for (int i = 0; i < DATA_SIZE; i++) data[i] = (byte) (i % 255); } @Override public void tearDown() throws Exception { super.tearDown(); } @Test public void testEchoServer() throws Exception { server.setRequestHandler(ECHO_HANDLER); ThreadUtil.runMultiThreadTask(new Task() { @Override public void run(int taskNumber) throws Exception { TcpClient client = getClient("localhost", PORT, clientBlocking); InputStream in = new BlockInputStream(client.getInputStream()); OutputStream out = new BlockOutputStream(client.getOutputStream()); try { out.write(data); out.close(); assertTrue(Arrays.equals(data, IOUtils.toByteArray(in))); in.close(); } finally { IOUtils.closeQuietly(client); } } }, THREADS, "TcpServerTestWorker"); } private static TcpClient getClient(String host, int port, boolean blocking) throws IOException { return blocking ? new SimpleTcpClient(host, port) : new NioTcpClient(host, port); } }
33.922078
149
0.653905
0d9f289ef45086f8a5ee0ab42eda3934e6845bc9
908
package de.mc_anura.eisenbahn; public class DataContainer { private String name; private Object value; private DataType datatype; public DataContainer(String name, Object value, DataType datatype) { this.name = name; this.value = value; this.datatype = datatype; } public String getName() { return name; } public <T> T getValue() { return (T) value; } public DataType getDataType() { return datatype; } public enum DataType { BOOLEAN(Boolean.class), INT(Integer.class), ; private final Class<?> clazz; DataType(Class<?> clazz) { this.clazz = clazz; } public Class<?> getClazz() { return clazz; } public static DataType getDataTypeById(int id) { return DataType.values()[id]; } } }
19.319149
72
0.555066
2cf8226d67a977cb7c5b3af5d55ed090e4641288
3,130
package com.xrz.demo.client; import com.xrz.demo.common.Constants; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.frame.LineBasedFrameDecoder; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @description: NettyClient * @author: JZG * @date: 2018/1/31 15:58 * @version: v1.0.0 */ public class NettyClient implements Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see Thread#run() */ @Override public void run() { ExecutorService bossExecutor = Executors.newFixedThreadPool(1); ExecutorService workerExecutor = Executors.newFixedThreadPool(10); ClientSocketChannelFactory clientSocketChannelFactory = new NioClientSocketChannelFactory(bossExecutor, workerExecutor); ClientBootstrap clientBootstrap = new ClientBootstrap(clientSocketChannelFactory); clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { ChannelPipeline channelPipeline = Channels.pipeline(); //可以添加多个同名解码器 channelPipeline.addLast("frameDecoder", new LineBasedFrameDecoder(1024)); channelPipeline.addLast("decoder", new StringDecoder()); channelPipeline.addLast("encoder", new StringEncoder()); channelPipeline.addLast("handler", new ClientLogicHandler()); return channelPipeline; } }); InetSocketAddress inetSocketAddress = new InetSocketAddress(Constants.HOST, Constants.PORT); clientBootstrap.connect(inetSocketAddress); System.out.println("client start success!"); } public static void main(String[] args) { try { Scanner sc = new Scanner(System.in); System.out.println("输入第一个字符:"); System.out.println("输入字符串:" + sc.next()); BufferedReader strin = new BufferedReader(new InputStreamReader(System.in)); System.out.print("请输入一个字符串:"); String str = strin.readLine(); System.out.println("第一个:" + str); } catch (IOException e) { e.printStackTrace(); } } }
37.261905
128
0.694569
f8314e362bbb06a3a85671942fd588b82efc08d3
1,013
package src.Command_Line_Version; public class Combinations { public static int[][] combinations(int n, int k) {//subsets of size k from [0,n-1] int c = (int) binomial(n, k); int[][] res = new int[c][Math.max(0, k)]; int[] ind = k < 0 ? null : new int[k]; for (int i = 0; i < k; ++i) { ind[i] = i; } for (int i = 0; i < c; ++i) { for (int j = 0; j < k; ++j) { res[i][j] = ind[j]; } int x = ind.length - 1; boolean loop; do { loop = false; ind[x] = ind[x] + 1; if (ind[x] > n - (k - x)) { x--; loop = x >= 0; } else { for (int x1 = x + 1; x1 < ind.length; ++x1) { ind[x1] = ind[x1 - 1] + 1; } } } while (loop); } return res; } public static long binomial(int n, int k) { if (k < 0 || k > n) return 0; if (k > n - k) { // take advantage of symmetry k = n - k; } long c = 1; for (int i = 1; i < k+1; ++i) { c = c * (n - (k - i)); c = c / i; } return c; } }
22.511111
84
0.435341
d40c528c474a7ab2b39f2aa10be2efdd126d94a1
665
package entity; import org.joml.Vector2f; import render.Animation; import world.World; public class GenericPlant extends Plant { private boolean hasFruit; public GenericPlant(World world, Vector2f position) { super("generic-plant", world, new Vector2f(2, 3), position); this.hasFruit = true; updateAnimation(); } public boolean hasFruit() { return this.hasFruit; } public void setHasFruit(boolean hasFruit) { this.hasFruit = hasFruit; updateAnimation(); } private void updateAnimation() { String fruit = this.hasFruit? "fruit" : "no-fruit"; setAnimation(0, new Animation(1, 1, "entities/" + getName() + "/fruit")); } }
18.472222
62
0.697744
4e8f50bb903b67aa312f64250abfbe168f162510
1,796
/* * Copyright (c) 2004, 2008, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package sun.management; import javax.management.MBeanRegistration; import javax.management.MBeanServer; import javax.management.ObjectName; /** * Implementation class of HotspotInternalMBean interface. * * <p> This is designed for internal customer use to create * this MBean dynamically from an agent which will then register * all internal MBeans to the platform MBeanServer. */ public class HotspotInternal implements HotspotInternalMBean, MBeanRegistration { private final static String HOTSPOT_INTERNAL_MBEAN_NAME = "sun.management:type=HotspotInternal"; private static ObjectName objName = Util.newObjectName(HOTSPOT_INTERNAL_MBEAN_NAME); private MBeanServer server = null; /** * Default constructor that registers all hotspot internal MBeans * to the MBeanServer that creates this MBean. */ public HotspotInternal() { } public ObjectName preRegister(MBeanServer server, ObjectName name) throws java.lang.Exception { // register all internal MBeans when this MBean is instantiated // and to be registered in a MBeanServer. ManagementFactoryHelper.registerInternalMBeans(server); this.server = server; return objName; } public void postRegister(Boolean registrationDone) {}; public void preDeregister() throws java.lang.Exception { // unregister all internal MBeans when this MBean is unregistered. ManagementFactoryHelper.unregisterInternalMBeans(server); } public void postDeregister() {}; }
24.60274
88
0.701002
e7c0a4094f7485ff014a9bd28318959448a6db97
4,380
package com.airsim.view; import org.controlsfx.dialog.Dialogs; import com.airsim.MainApp; import com.airsim.model.Airplane; import com.airsim.model.Airport; import com.airsim.model.AssetLoader; import com.airsim.model.FlightPath; import com.airsim.model.HoverPath; import com.airsim.model.World; import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.fxml.FXML; import javafx.scene.Group; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.image.ImageView; import javafx.util.Duration; public class RootLayoutController { @FXML private TableView<Airport> airportTable; @FXML private TableColumn<Airport, String> nameColumn; @FXML private TableColumn<Airport, Number> emptyPlacesColumn; @FXML private TableView<Airplane> airplaneTable; @FXML private TableColumn<Airplane, String> nameAriplaneColumn; @FXML private TableColumn<Airplane, String> AirplaneStateColumn; @FXML private Group groupDraw; @FXML private Label daysLabel; @FXML private Label hoursLabel; @FXML private Label minutesLabel; @FXML private Label secondsLabel; @FXML private Label scaleTimeLabel; @FXML private Label crashesLabel; private MainApp mainApp; private Timeline timeline; final public static int MILLIUPDATE = 34; public void setMainApp(MainApp mainApp) { this.mainApp = mainApp; airportTable.setItems(World.getAirportData()); airplaneTable.setItems(World.getAirplaneData()); } public RootLayoutController() { this.timeline = new Timeline(new KeyFrame( Duration.millis(MILLIUPDATE), ae -> update())); timeline.setCycleCount(Animation.INDEFINITE); } @FXML private void initialize() { nameColumn.setCellValueFactory( cellData -> cellData.getValue().nameProperty()); emptyPlacesColumn.setCellValueFactory( cellData -> cellData.getValue().emptyPlacesProperty()); nameAriplaneColumn.setCellValueFactory( cellData -> cellData.getValue().nameProperty()); AirplaneStateColumn.setCellValueFactory( cellData -> cellData.getValue().strStateProperty()); secondsLabel.textProperty().bind(World.clock.timeProperty()); crashesLabel.textProperty().bind(World.crashesProperty()); } @FXML private void showAirportView() { Airport selectedAirport = airportTable.getSelectionModel().getSelectedItem(); if (selectedAirport != null) { mainApp.showAirportView(selectedAirport); } else { // Nothing selected. Dialogs.create() .title("No Selection") .masthead("No Airport Selected") .message("Please select an airport in the table.") .showWarning(); } } @FXML private void showAirplaneView() { Airplane selectedAirplane = airplaneTable.getSelectionModel().getSelectedItem(); if (selectedAirplane != null) { mainApp.showAirplaneView(selectedAirplane); } else { // Nothing selected. Dialogs.create() .title("No Selection") .masthead("No Airplane Selected") .message("Please select an airplane in the table.") .showWarning(); } } @FXML private void showAbout() { mainApp.showAboutView(); } public void start() { timeline.play(); } public void update() { World.clock.addMilliseconds(MILLIUPDATE); try { for(Airplane airplane: World.getAirplaneData()) { airplane.update(groupDraw); } } catch(Exception e) { System.out.println("Dead Airplane"); } } public void drawStatics() { drawBackground(); drawAirports(); drawPaths(); } private void drawBackground() { ImageView imageView = new ImageView(); imageView.setImage(AssetLoader.background); imageView.setFitWidth(900); imageView.setFitHeight(550); groupDraw.getChildren().add(imageView); } private void drawAirports() { for(Airport airport: World.getAirportData()) { groupDraw.getChildren().add(airport.getImageView()); groupDraw.getChildren().add(airport.getTextName()); } } private void drawPaths() { for(FlightPath flightPath: World.pathManager.getFlightPaths().values()) { flightPath.drawPath(groupDraw); } for(HoverPath hoverPath: World.pathManager.getHoverPaths().values()) { hoverPath.drawPath(groupDraw); } } }
25.465116
82
0.71758
8a0d155fd34805284df8e74f36346aea8a1664a4
11,623
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.yarn.server.nodemanager.containermanager.queuing; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.UnsupportedFileSystemException; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerStatusesRequest; import org.apache.hadoop.yarn.api.protocolrecords.StartContainerRequest; import org.apache.hadoop.yarn.api.protocolrecords.StartContainersRequest; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.ContainerStatus; import org.apache.hadoop.yarn.api.records.ExecutionType; import org.apache.hadoop.yarn.api.records.LocalResource; import org.apache.hadoop.yarn.api.records.LocalResourceType; import org.apache.hadoop.yarn.api.records.LocalResourceVisibility; import org.apache.hadoop.yarn.api.records.URL; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.security.NMTokenIdentifier; import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor; import org.apache.hadoop.yarn.server.nodemanager.Context; import org.apache.hadoop.yarn.server.nodemanager.DeletionService; import org.apache.hadoop.yarn.server.nodemanager.containermanager.ContainerManagerImpl; import org.apache.hadoop.yarn.server.nodemanager.containermanager.TestContainerManager; import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container; import org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.ContainersMonitor; import org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor .ContainersMonitorImpl; import org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.MockResourceCalculatorPlugin; import org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.MockResourceCalculatorProcessTree; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.util.ConverterUtils; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class TestQueuingContainerManager extends TestContainerManager { interface HasResources { boolean decide(Context context, ContainerId cId); } public TestQueuingContainerManager() throws UnsupportedFileSystemException { super(); } static { LOG = LogFactory.getLog(TestQueuingContainerManager.class); } boolean shouldDeleteWait = false; @Override protected ContainerManagerImpl createContainerManager( DeletionService delSrvc) { return new QueuingContainerManagerImpl(context, exec, delSrvc, nodeStatusUpdater, metrics, dirsHandler) { @Override public void serviceInit(Configuration conf) throws Exception { conf.set( YarnConfiguration.NM_CONTAINER_MON_RESOURCE_CALCULATOR, MockResourceCalculatorPlugin.class.getCanonicalName()); conf.set( YarnConfiguration.NM_CONTAINER_MON_PROCESS_TREE, MockResourceCalculatorProcessTree.class.getCanonicalName()); super.serviceInit(conf); } @Override public void setBlockNewContainerRequests(boolean blockNewContainerRequests) { // do nothing } @Override protected UserGroupInformation getRemoteUgi() throws YarnException { ApplicationId appId = ApplicationId.newInstance(0, 0); ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(appId, 1); UserGroupInformation ugi = UserGroupInformation.createRemoteUser(appAttemptId.toString()); ugi.addTokenIdentifier(new NMTokenIdentifier(appAttemptId, context .getNodeId(), user, context.getNMTokenSecretManager().getCurrentKey() .getKeyId())); return ugi; } @Override protected void authorizeGetAndStopContainerRequest( ContainerId containerId, Container container, boolean stopRequest, NMTokenIdentifier identifier) throws YarnException { if (container == null || container.getUser().equals("Fail")) { throw new YarnException("Reject this container"); } } @Override protected ContainersMonitor createContainersMonitor( ContainerExecutor exec) { return new ContainersMonitorImpl(exec, dispatcher, this.context) { // Define resources available for containers to be executed. @Override public long getPmemAllocatedForContainers() { return 2048 * 1024 * 1024L; } @Override public long getVmemAllocatedForContainers() { float pmemRatio = getConfig().getFloat( YarnConfiguration.NM_VMEM_PMEM_RATIO, YarnConfiguration.DEFAULT_NM_VMEM_PMEM_RATIO); return (long) (pmemRatio * getPmemAllocatedForContainers()); } @Override public long getVCoresAllocatedForContainers() { return 2; } }; } }; } @Override protected DeletionService createDeletionService() { return new DeletionService(exec) { @Override public void delete(String user, Path subDir, Path... baseDirs) { // Don't do any deletions. if (shouldDeleteWait) { try { Thread.sleep(10000); LOG.info("\n\nSleeping Pseudo delete : user - " + user + ", " + "subDir - " + subDir + ", " + "baseDirs - " + Arrays.asList(baseDirs)); } catch (InterruptedException e) { e.printStackTrace(); } } else { LOG.info("\n\nPseudo delete : user - " + user + ", " + "subDir - " + subDir + ", " + "baseDirs - " + Arrays.asList(baseDirs)); } } }; } @Override public void setup() throws IOException { super.setup(); shouldDeleteWait = false; } /** * Test to verify that an OPPORTUNISTIC container is killed when * a GUARANTEED container arrives and all the Node Resources are used up * * For this specific test case, 4 containers are requested (last one being * guaranteed). Assumptions : * 1) The first OPPORTUNISTIC Container will start running * 2) The second and third OPP containers will be queued * 3) When the GUARANTEED container comes in, the running OPP container * will be killed to make room * 4) After the GUARANTEED container finishes, the remaining 2 OPP * containers will be dequeued and run. * 5) Only the first OPP container will be killed. * * @throws Exception */ @Test public void testSimpleOpportunisticContainer() throws Exception { shouldDeleteWait = true; containerManager.start(); // ////// Create the resources for the container File dir = new File(tmpDir, "dir"); dir.mkdirs(); File file = new File(dir, "file"); PrintWriter fileWriter = new PrintWriter(file); fileWriter.write("Hello World!"); fileWriter.close(); // ////// Construct the container-spec. ContainerLaunchContext containerLaunchContext = recordFactory.newRecordInstance(ContainerLaunchContext.class); URL resource_alpha = ConverterUtils.getYarnUrlFromPath(localFS .makeQualified(new Path(file.getAbsolutePath()))); LocalResource rsrc_alpha = recordFactory.newRecordInstance(LocalResource.class); rsrc_alpha.setResource(resource_alpha); rsrc_alpha.setSize(-1); rsrc_alpha.setVisibility(LocalResourceVisibility.APPLICATION); rsrc_alpha.setType(LocalResourceType.FILE); rsrc_alpha.setTimestamp(file.lastModified()); String destinationFile = "dest_file"; Map<String, LocalResource> localResources = new HashMap<String, LocalResource>(); localResources.put(destinationFile, rsrc_alpha); containerLaunchContext.setLocalResources(localResources); // Start 3 OPPORTUNISTIC containers and 1 GUARANTEED container List<StartContainerRequest> list = new ArrayList<>(); list.add(StartContainerRequest.newInstance( containerLaunchContext, createContainerToken(createContainerId(0), DUMMY_RM_IDENTIFIER, context.getNodeId(), user, BuilderUtils.newResource(1024, 1), context.getContainerTokenSecretManager(), null, ExecutionType.OPPORTUNISTIC))); list.add(StartContainerRequest.newInstance( containerLaunchContext, createContainerToken(createContainerId(1), DUMMY_RM_IDENTIFIER, context.getNodeId(), user, BuilderUtils.newResource(1024, 1), context.getContainerTokenSecretManager(), null, ExecutionType.OPPORTUNISTIC))); list.add(StartContainerRequest.newInstance( containerLaunchContext, createContainerToken(createContainerId(2), DUMMY_RM_IDENTIFIER, context.getNodeId(), user, BuilderUtils.newResource(1024, 1), context.getContainerTokenSecretManager(), null, ExecutionType.OPPORTUNISTIC))); // GUARANTEED list.add(StartContainerRequest.newInstance( containerLaunchContext, createContainerToken(createContainerId(3), DUMMY_RM_IDENTIFIER, context.getNodeId(), user, BuilderUtils.newResource(1024, 1), context.getContainerTokenSecretManager(), null, ExecutionType.GUARANTEED))); StartContainersRequest allRequests = StartContainersRequest.newInstance(list); containerManager.startContainers(allRequests); Thread.sleep(10000); List<ContainerId> statList = new ArrayList<ContainerId>(); for (int i = 0; i < 4; i++) { statList.add(createContainerId(i)); } GetContainerStatusesRequest statRequest = GetContainerStatusesRequest.newInstance(statList); List<ContainerStatus> containerStatuses = containerManager .getContainerStatuses(statRequest).getContainerStatuses(); for (ContainerStatus status : containerStatuses) { // Ensure that the first opportunistic container is killed if (status.getContainerId().equals(createContainerId(0))) { Assert.assertTrue(status.getDiagnostics() .contains("Container killed by the ApplicationMaster")); } System.out.println("\nStatus : [" + status + "]\n"); } } }
39.804795
108
0.715048
a845ac31733f65688d743521762f8d31e437dd1b
7,041
package org.kettle.metastore.steps.writer; import org.pentaho.di.core.annotations.Step; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.Repository; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.metastore.api.IMetaStore; import org.w3c.dom.Node; import java.util.List; /* @Step( id = "MetastoreWriter", name = "Metastore Writer", description = "Writes to the metastore", image = "MetastoreWriter.svg", categoryDescription = "Output", documentationUrl = "https://github.com/mattcasters/kettle-metastore" ) */ public class MetastoreWriterMeta extends BaseStepMeta implements StepMetaInterface { public static final String NAMESPACE_FIELD = "namespace_field"; public static final String ELEMENT_TYPE_FIELD = "element_type_field"; public static final String ELEMENT_NAME_FIELD = "element_name_field"; public static final String ATTRIBUTE_PATH_FIELD = "attribute_path_field"; public static final String ATTRIBUTE_INDEX_FIELD = "attribute_index_field"; public static final String ATTRIBUTE_VALUE_FIELD = "attribute_value_field"; private String namespaceField; private String elementTypeField; private String elementNameField; private String attributePathField; private String attributeIndexField; private String attributeValueField; public MetastoreWriterMeta() { super(); } @Override public String getXML() throws KettleException { StringBuilder xml = new StringBuilder(); xml.append( XMLHandler.addTagValue( NAMESPACE_FIELD, namespaceField) ); xml.append( XMLHandler.addTagValue( ELEMENT_TYPE_FIELD, elementTypeField) ); xml.append( XMLHandler.addTagValue( ELEMENT_NAME_FIELD, elementNameField) ); xml.append( XMLHandler.addTagValue( ATTRIBUTE_PATH_FIELD, attributePathField ) ); xml.append( XMLHandler.addTagValue( ATTRIBUTE_INDEX_FIELD, attributeIndexField ) ); xml.append( XMLHandler.addTagValue( ATTRIBUTE_VALUE_FIELD, attributeValueField ) ); return xml.toString(); } @Override public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException { namespaceField = XMLHandler.getTagValue( stepnode, NAMESPACE_FIELD); elementTypeField = XMLHandler.getTagValue( stepnode, ELEMENT_TYPE_FIELD ); elementNameField = XMLHandler.getTagValue( stepnode, ELEMENT_NAME_FIELD ); attributePathField = XMLHandler.getTagValue( stepnode, ATTRIBUTE_PATH_FIELD ); attributeIndexField = XMLHandler.getTagValue( stepnode, ATTRIBUTE_INDEX_FIELD ); attributeValueField = XMLHandler.getTagValue( stepnode, ATTRIBUTE_VALUE_FIELD ); } @Override public void saveRep( Repository rep, IMetaStore metaStore, ObjectId transformationId, ObjectId stepId ) throws KettleException { rep.saveStepAttribute( transformationId, stepId, NAMESPACE_FIELD, namespaceField); rep.saveStepAttribute( transformationId, stepId, ELEMENT_TYPE_FIELD, elementTypeField ); rep.saveStepAttribute( transformationId, stepId, ELEMENT_NAME_FIELD, elementNameField ); rep.saveStepAttribute( transformationId, stepId, ATTRIBUTE_PATH_FIELD, attributePathField ); rep.saveStepAttribute( transformationId, stepId, ATTRIBUTE_INDEX_FIELD, attributeIndexField ); rep.saveStepAttribute( transformationId, stepId, ATTRIBUTE_VALUE_FIELD, attributeValueField ); } @Override public void readRep( Repository rep, IMetaStore metaStore, ObjectId stepId, List<DatabaseMeta> databases ) throws KettleException { namespaceField = rep.getStepAttributeString( stepId, NAMESPACE_FIELD ); elementTypeField = rep.getStepAttributeString( stepId, ELEMENT_TYPE_FIELD ); elementNameField = rep.getStepAttributeString( stepId, ELEMENT_NAME_FIELD ); attributePathField = rep.getStepAttributeString( stepId, ATTRIBUTE_PATH_FIELD ); attributeIndexField = rep.getStepAttributeString( stepId, ATTRIBUTE_INDEX_FIELD ); attributeValueField = rep.getStepAttributeString( stepId, ATTRIBUTE_VALUE_FIELD ); } @Override public void setDefault() { } @Override public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans ) { return new MetastoreWriter( stepMeta, stepDataInterface, copyNr, transMeta, trans ); } @Override public StepDataInterface getStepData() { return new MetastoreWriterData(); } @Override public String getDialogClassName() { return MetastoreWriterDialog.class.getName(); } /** * Gets namespaceField * * @return value of namespaceField */ public String getNamespaceField() { return namespaceField; } /** * @param namespaceField The namespaceField to set */ public void setNamespaceField( String namespaceField ) { this.namespaceField = namespaceField; } /** * Gets elementTypeField * * @return value of elementTypeField */ public String getElementTypeField() { return elementTypeField; } /** * @param elementTypeField The elementTypeField to set */ public void setElementTypeField( String elementTypeField ) { this.elementTypeField = elementTypeField; } /** * Gets elementNameField * * @return value of elementNameField */ public String getElementNameField() { return elementNameField; } /** * @param elementNameField The elementNameField to set */ public void setElementNameField( String elementNameField ) { this.elementNameField = elementNameField; } /** * Gets attributePathField * * @return value of attributePathField */ public String getAttributePathField() { return attributePathField; } /** * @param attributePathField The attributePathField to set */ public void setAttributePathField( String attributePathField ) { this.attributePathField = attributePathField; } /** * Gets attributeIndexField * * @return value of attributeIndexField */ public String getAttributeIndexField() { return attributeIndexField; } /** * @param attributeIndexField The attributeIndexField to set */ public void setAttributeIndexField( String attributeIndexField ) { this.attributeIndexField = attributeIndexField; } /** * Gets attributeValueField * * @return value of attributeValueField */ public String getAttributeValueField() { return attributeValueField; } /** * @param attributeValueField The attributeValueField to set */ public void setAttributeValueField( String attributeValueField ) { this.attributeValueField = attributeValueField; } }
35.029851
146
0.766368
11faabc45883f3d0b11ccd2af0cad5a2300a7c8c
1,127
package com.justwayward.book.ui.adapter; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import java.util.List; /** * Created by gaoyuan on 2017/11/17. */ public class ViewPagerAdapter extends FragmentPagerAdapter { private List<Fragment> mList; private List<String> mTitles; public ViewPagerAdapter(FragmentManager fm, Context context, List<Fragment> mList, List<String> mTitles) { super(fm); this.mList = mList; this.mTitles = mTitles; } public ViewPagerAdapter(FragmentManager fm, Context context, List<Fragment> mList) { super(fm); this.mList = mList; } @Override public Fragment getItem(int position) { return mList.get(position); } @Override public int getCount() { return mList == null ? 0 : mList.size(); } @Override public CharSequence getPageTitle(int position) { if(mTitles==null){ return ""; } return mTitles.get(position); } }
23.479167
110
0.661934
1b1cf5883e8c889a9a21daccf7a140e3a91542ac
3,569
package com.lt.sisyphus.rpc.server; import com.lt.sisyphus.rpc.codec.RpcDecoder; import com.lt.sisyphus.rpc.codec.RpcEncoder; import com.lt.sisyphus.rpc.codec.RpcRequest; import com.lt.sisyphus.rpc.codec.RpcResponse; import com.lt.sisyphus.rpc.config.provider.ProviderConfig; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import lombok.extern.slf4j.Slf4j; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; @Slf4j public class RpcServer { private String serverAddress; private EventLoopGroup bossGroup = new NioEventLoopGroup(); private EventLoopGroup workGroup = new NioEventLoopGroup(); private volatile Map<String, Object> handlerMap = new HashMap<String, Object>(); public RpcServer(String serverAddress) throws InterruptedException { this.serverAddress = serverAddress; this.start(); } public void start() throws InterruptedException { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline cp = ch.pipeline(); // 编解码Handler cp.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 0)); cp.addLast(new RpcDecoder(RpcRequest.class)); cp.addLast(new RpcEncoder(RpcResponse.class)); // 添加实际的业务处理器RpcClientHandler cp.addLast(new RpcServerHandler(handlerMap)); } }); String[] array = serverAddress.split(":"); String host = array[0]; int port = Integer.parseInt(array[1]); ChannelFuture channelFuture = serverBootstrap.bind(host, port).sync(); // 异步 channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { log.info("server success bing to " + serverAddress); } else { log.info("server fail bing to " + serverAddress); throw new Exception("server start fail, cause:" + future.cause()); } } }); // 同步 TODO 与异步二选一(未来成为配置项) try { channelFuture.await(5000, TimeUnit.MILLISECONDS); if (channelFuture.isSuccess()) { log.info("start sysphus rpc success bing to " + serverAddress); } } catch (InterruptedException e) { log.error("start sysphus rpc occur Interrupted ex" + e); } } public void registerProcessor(ProviderConfig providerConfig) { handlerMap.put(providerConfig.getInterfaceClass(), providerConfig.getRef()); } public void close() { bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); } public String getServerAddress() { return serverAddress; } }
36.793814
86
0.626786
066791250aa3d48a70a33be1d941b02e7c4d8888
1,065
package ru.ok.android.sdk.util; /** * A list of currently available scopes * <p/> * Methods <b>users.getLoggedInUser</b> и <b>users.getCurrentUser</b> do not require any scopes */ public class OkScope { /** * Grants access to API methods. */ public static final String VALUABLE_ACCESS = "VALUABLE_ACCESS"; /** * Grants permission to set user status. */ public static final String SET_STATUS = "SET_STATUS"; /** * Grants access to photo content. */ public static final String PHOTO_CONTENT = "PHOTO_CONTENT"; /** * Grants access to group content. */ public static final String GROUP_CONTENT = "GROUP_CONTENT"; /** * Grants access to video content. */ public static final String VIDEO_CONTENT = "VIDEO_CONTENT"; /** * Grants access to invite to app. */ public static final String APP_INVITE = "APP_INVITE"; /** * Grants access to receive long access tokens */ public static final String LONG_ACCESS_TOKEN = "LONG_ACCESS_TOKEN"; }
24.204545
95
0.643192
812e585aff3edc7d63275fef0864c879afd2afbd
23,801
package rlaproject; import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; import javax.swing.JOptionPane; import java.text.SimpleDateFormat; import javax.swing.JFileChooser; import org.apache.commons.io.FileUtils; /** * * @author Avi Kathuria */ public class form26 extends javax.swing.JFrame { /** Creates new form form26 */ Connection con; public form26() { initComponents(); this.setLocationRelativeTo(null); myconnection_class mycon1=new myconnection_class(); if(mycon1.my_connection_status()==true) { con=mycon1.get_my_connection(); // JOptionPane.showMessageDialog(rootPane, "connected"); } else { JOptionPane.showMessageDialog(rootPane, mycon1.errmsg().toString()); } } /** 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() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); t1 = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); t2 = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); t3 = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); t4 = new javax.swing.JTextField(); jLabel20 = new javax.swing.JLabel(); Submit = new javax.swing.JButton(); Clear = new javax.swing.JButton(); jLabel22 = new javax.swing.JLabel(); t5 = new javax.swing.JTextField(); jLabel23 = new javax.swing.JLabel(); t6 = new javax.swing.JTextField(); jLabel25 = new javax.swing.JLabel(); jLabel27 = new javax.swing.JLabel(); jButton3 = new javax.swing.JButton(); certificate = new javax.swing.JButton(); jLabel36 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Registration Form"); setResizable(false); jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N jLabel1.setText("FORM 26"); jLabel2.setFont(jLabel2.getFont().deriveFont(jLabel2.getFont().getStyle() | java.awt.Font.BOLD)); jLabel2.setText("Intimation of loss or Destruction etc. of the Certificate of Registration and Application for the "); jLabel5.setFont(jLabel5.getFont().deriveFont(jLabel5.getFont().getStyle() | java.awt.Font.BOLD)); jLabel5.setText("issue of Duplicate Certificate of Registration"); jLabel7.setText("To"); jLabel8.setText("The registering Authority"); jLabel9.setText("Sir,"); jLabel10.setText("The Certificate of Registration of my/our Motor Vehicle the Registration make of which is"); jLabel11.setText("has been lost / destroyed /completely written of / soiled / torn mutilated in the"); jLabel12.setText("following circumstances:"); jLabel13.setText("I / We hereby declare that to the best of my / our knowledge the registration of vehicle has not been"); jLabel14.setText("suspended or cancelled under the provisions of the Act or Rules made there under and the circumstances"); jLabel15.setText("explained above are true."); jLabel16.setText("- I/We do hereby apply for the issue of a duplicate Certificate of Registration."); jLabel17.setText("- The written off / soiled / torn mutilated Certificates of Registration is enclosed."); jLabel18.setText("- The vehicle is not held under any agreement of Hire Purchase / Lease / Hypothecation."); jLabel19.setText("- I/We have reported the loss to the Police Station on"); jLabel20.setText("(date)"); Submit.setText("Submit"); Submit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SubmitActionPerformed(evt); } }); Clear.setText("Clear"); Clear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ClearActionPerformed(evt); } }); jLabel22.setText("Name"); jLabel23.setText("Address"); jLabel25.setText("- The vehicle is held under Hire/Purchase/Lease /Hypothecation agreement with and the 'No Objection"); jLabel27.setText("Certificate' obtained from the financier is enclosed."); jButton3.setText("Back"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); certificate.setText("File Upload"); certificate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { certificateActionPerformed(evt); } }); jLabel36.setIcon(new javax.swing.ImageIcon(getClass().getResource("/rlaproject/rla_images/Icon.jpg"))); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 512, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(34, 34, 34) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 524, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 435, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(t3, javax.swing.GroupLayout.PREFERRED_SIZE, 548, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 487, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 524, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel18, javax.swing.GroupLayout.PREFERRED_SIZE, 540, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel19, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(t4, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel27, javax.swing.GroupLayout.PREFERRED_SIZE, 547, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 596, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 586, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel25, javax.swing.GroupLayout.PREFERRED_SIZE, 586, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(33, 33, 33) .addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(certificate) .addGap(226, 226, 226) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel23, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(t5, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(t6, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 512, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(33, 33, 33) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 586, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(t2, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 416, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(23, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(263, 263, 263) .addComponent(jLabel1)) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 265, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 549, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel36)))) .addGroup(layout.createSequentialGroup() .addGap(218, 218, 218) .addComponent(Submit) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(Clear) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton3) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(6, 6, 6) .addComponent(jLabel2) .addGap(6, 6, 6) .addComponent(jLabel5)) .addComponent(jLabel36)) .addGap(27, 27, 27) .addComponent(jLabel7) .addGap(6, 6, 6) .addComponent(jLabel8) .addGap(6, 6, 6) .addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(11, 11, 11) .addComponent(jLabel9) .addGap(6, 6, 6) .addComponent(jLabel10) .addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(t2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(2, 2, 2) .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(6, 6, 6) .addComponent(jLabel12) .addGap(6, 6, 6) .addComponent(t3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(6, 6, 6) .addComponent(jLabel13) .addGap(6, 6, 6) .addComponent(jLabel14) .addGap(6, 6, 6) .addComponent(jLabel15) .addGap(6, 6, 6) .addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(6, 6, 6) .addComponent(jLabel17) .addGap(6, 6, 6) .addComponent(jLabel18) .addGap(10, 10, 10) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel19) .addComponent(t4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel20)) .addGap(18, 18, 18) .addComponent(jLabel25) .addGap(6, 6, 6) .addComponent(jLabel27) .addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(t5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel22) .addComponent(certificate)) .addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(t6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel23)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Clear) .addComponent(Submit) .addComponent(jButton3)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void SubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SubmitActionPerformed try { int d1_len=t1.getText().length(); int d2_len=t2.getText().length(); int d3_len=t3.getText().length(); int d4_len=t4.getText().length(); int d5_len=t5.getText().length(); int d6_len=t6.getText().length(); if(d1_len==0 || d2_len==0 || d3_len==0 || d4_len==0 || d5_len==0 || d6_len==0) { JOptionPane.showMessageDialog(rootPane, "Please Fill Required Fields to Submit the Form"); if(d1_len==0) { JOptionPane.showMessageDialog(rootPane, "Please insert Authority Name "); } else if(d2_len==0) { JOptionPane.showMessageDialog(rootPane, "Please insert Reg. Make"); } else if(d3_len==0) { JOptionPane.showMessageDialog(rootPane, "Please insert Circumstances"); } else if(d4_len==0) { JOptionPane.showMessageDialog(rootPane, "Please insert Date of Report"); } else if(d5_len==0) { JOptionPane.showMessageDialog(rootPane, "Please insert your Name"); } else if(d6_len==0) { JOptionPane.showMessageDialog(rootPane, "Please insert your Address"); } } else { int res=JOptionPane.showConfirmDialog(null,"Want to Submit Form","Info",JOptionPane.OK_OPTION,JOptionPane.INFORMATION_MESSAGE); if(res==JOptionPane.OK_OPTION) { PreparedStatement pstmt=con.prepareStatement("insert into form26 values(?,?,?,?,?,?,?,?)"); pstmt.setString(1,(t1.getText())); pstmt.setString(2,(t2.getText())); pstmt.setString(3,(t3.getText())); pstmt.setString(4,(t4.getText())); java.util.Date d1=new java.util.Date(); String newdate=new SimpleDateFormat("dd/MM/yyyy").format(d1); pstmt.setString(5,newdate); pstmt.setString(6,(t5.getText())); pstmt.setString(7,(t6.getText())); pstmt.setString(8,(f2.getPath())); pstmt.executeUpdate(); FileUtils.copyFileToDirectory(f1, f2); new main().setVisible(true); dispose(); } } } catch(Exception obj) { System.out.println(obj.toString()); JOptionPane.showMessageDialog(rootPane, "Please Upload Required File in the Form"); } }//GEN-LAST:event_SubmitActionPerformed private void ClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClearActionPerformed t1.setText(""); t2.setText(""); t3.setText(""); t4.setText(""); t5.setText(""); t6.setText(""); }//GEN-LAST:event_ClearActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed new main().setVisible(true); dispose(); }//GEN-LAST:event_jButton3ActionPerformed File f1,f2; private void certificateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_certificateActionPerformed JFileChooser JFC = new JFileChooser(); if( JFC.showOpenDialog(null)==0) { f1=new File(JFC.getSelectedFile().toString()); f2=new File("C:\\rlaproject\\Uploaded_Files"); } }//GEN-LAST:event_certificateActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { //<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(form25.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(form25.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(form25.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(form25.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new form26().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton Clear; private javax.swing.JButton Submit; private javax.swing.JButton certificate; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel36; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JTextField t1; private javax.swing.JTextField t2; private javax.swing.JTextField t3; private javax.swing.JTextField t4; private javax.swing.JTextField t5; private javax.swing.JTextField t6; // End of variables declaration//GEN-END:variables }
51.184946
155
0.607916
87f49d8109444485726675a654244dec26bfab89
4,935
package com.example.rxjavawithcallback; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ProgressBar; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers; import io.reactivex.rxjava3.annotations.NonNull; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.core.ObservableEmitter; import io.reactivex.rxjava3.core.ObservableOnSubscribe; import io.reactivex.rxjava3.observers.DisposableObserver; import io.reactivex.rxjava3.schedulers.Schedulers; public class MainActivity extends AppCompatActivity { private final static int INVALID = -1; private interface ITaskCallback { void setUpdate(Integer progress); } /** * ProgressEmitter is basically the callback registered to get the progress * It also emits onNext, onComplete, onError for the Observer to get the update */ private class ProgressEmitter implements ITaskCallback { final private ObservableEmitter<Integer> emitter; private ProgressEmitter(ObservableEmitter<Integer> emitter) { this.emitter = emitter; } @Override public void setUpdate(Integer progress) { if (progress.intValue() >= 0) { emitter.onNext(progress); } else if(progress.intValue() == 100) { emitter.onNext(progress); emitter.onComplete(); } else { emitter.onError(new Exception(progress.toString())); } } } /** * ProgressObserver is the Observer responsible to update UI with the progress */ private class ProgressObserver extends DisposableObserver<Integer> { private ProgressBar pb; private ProgressObserver(ProgressBar pb) { this.pb = pb; } @Override public void onNext(@NonNull Integer integer) { pb.setProgress(integer.intValue()); } @Override public void onError(@NonNull Throwable e) { } @Override public void onComplete() { } } private int getRandomNumber(int min, int max) { return (int) ((Math.random() * (max - min)) + min); } private class ObservableTask { /** * This function returns the Observable to the registered Observer and calls update function * It also creates and passes the Callback needed in update function * @return : Observable with progress amount */ public Observable<Integer> observableUpdate() { return Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable { update(new ProgressEmitter(emitter)); } }); } /** * This is the function, whose progress we need to show * @param callback : It's the callback, whom progress is returned */ public void update(ITaskCallback callback) { for (int i = 0; i <= 100; i += 10) { try { Thread.sleep(getRandomNumber(10, 1000)); callback.setUpdate(Integer.valueOf(i)); } catch (Exception e) { System.out.println(e.getStackTrace().toString()); callback.setUpdate(Integer.valueOf(INVALID)); } } } } private ProgressBar pb1; private ProgressBar pb2; private ExecutorService executorService; private ObservableTask task1; private ObservableTask task2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pb1 = findViewById(R.id.progressBar1); pb2 = findViewById(R.id.progressBar2); pb1.setProgress(0); pb2.setProgress(0); executorService = new ThreadPoolExecutor(4, 5, 60L, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>()); task1 = new ObservableTask(); task2 = new ObservableTask(); task1.observableUpdate() .subscribeOn(Schedulers.from(executorService)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ProgressObserver(pb1)); task2.observableUpdate() .subscribeOn(Schedulers.from(executorService)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ProgressObserver(pb2)); } @Override protected void onDestroy() { super.onDestroy(); executorService.shutdown(); } }
31.433121
115
0.630193
f89d70e8f0140c8900ced581821d36083f617ae2
294
package limax.provider; import limax.codec.Octets; public interface TunnelSupport { void onTunnel(long sessionid, int label, Octets data) throws Exception; default void onException(long sessionid, int label, TunnelException exception) throws Exception { throw exception; } }
24.5
99
0.761905
973d947fd25db270834939e58ca93f01cbbb988b
2,063
package net.sourceforge.kolmafia.textui.command; import net.sourceforge.kolmafia.RequestLogger; public class PlayerSnapshotCommand extends AbstractCommand { public PlayerSnapshotCommand() { this.usage = " [status],[equipment],[effects],[<etc>.] - record data, \"log snapshot\" for all common data."; } @Override public void run(final String cmd, final String parameters) { if (parameters.equals("snapshot")) { this.snapshot("moon, status, equipment, skills, effects, modifiers"); return; } this.snapshot(parameters); } private void snapshot(final String parameters) { RequestLogger.updateSessionLog(); RequestLogger.updateSessionLog("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); RequestLogger.getDebugStream().println(); RequestLogger.getDebugStream().println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); StringBuffer title = new StringBuffer("Player Snapshot"); int leftIndent = (46 - title.length()) / 2; for (int i = 0; i < leftIndent; ++i) { title.insert(0, ' '); } RequestLogger.updateSessionLog(title.toString()); RequestLogger.updateSessionLog("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); RequestLogger.getDebugStream().println(title.toString()); RequestLogger.getDebugStream().println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); String[] options = parameters.split("\\s*,\\s*"); for (int i = 0; i < options.length; ++i) { RequestLogger.updateSessionLog(); RequestLogger.updateSessionLog(" > " + options[i]); ShowDataCommand.show(options[i], true); } RequestLogger.updateSessionLog(); RequestLogger.updateSessionLog("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); RequestLogger.getDebugStream().println(); RequestLogger.getDebugStream().println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); RequestLogger.updateSessionLog(); RequestLogger.updateSessionLog(); RequestLogger.getDebugStream().println(); RequestLogger.getDebugStream().println(); } }
32.746032
104
0.592826
87e034073fbbab51e4b82cba20a4c603a28d37b7
353
package com.github.httpflowlabs.httpflow.core; import com.github.httpflowlabs.httpflow.resource.HttpFlowResource; import com.github.httpflowlabs.httpflow.resource.parser.model.HttpFlowDocument; public interface IHttpFlowCore extends HttpFlowConfigurable { void execute(HttpFlowResource resource); void execute(HttpFlowDocument document); }
27.153846
79
0.832861
feea0153f81ea0148219ae7e4f8022502adab01f
5,280
package com.composum.pages.commons.service; import com.composum.pages.commons.model.ContentVersion; import com.composum.pages.commons.model.SiteRelease; import com.composum.sling.core.BeanContext; import com.composum.sling.core.filter.ResourceFilter; import com.composum.sling.platform.staging.versions.PlatformVersionsService; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.jcr.RepositoryException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; /** * */ public interface VersionsService { /** * a filter interface for the version search operations */ @FunctionalInterface interface ContentVersionFilter { boolean accept(@Nullable ContentVersion version); /** Combines this and {otherFilter} conjunctively. If {otherFilter}=null it's ignored. */ default ContentVersionFilter and(@Nullable ContentVersionFilter otherFilter) { return otherFilter != null ? (version) -> this.accept(version) && otherFilter.accept(version) : this; } } @Nullable Resource getResource(@Nonnull BeanContext context, @Nonnull PlatformVersionsService.Status status); /** * Resets a versionable to a version, but deletes all versions after that version. */ void rollbackVersion(BeanContext context, String path, String versionName) throws RepositoryException; /** * Returns a collection of all versionables which are changed in a release in comparision to the release before, * ordered by path. */ @Nonnull List<ContentVersion> findReleaseChanges(@Nonnull BeanContext context, @Nullable SiteRelease release, @Nullable ContentVersionFilter filter) throws RepositoryException; /** * Returns all pages that are modified wrt. the current release (that is, either not there, have a new version * that isn't in the current release, are modified wrt. the last version, or have been moved or deleted), * ordered by path. */ @Nonnull List<ContentVersion> findModifiedContent(@Nonnull BeanContext context, @Nullable SiteRelease siteRelease, @Nullable ContentVersionFilter filter) throws RepositoryException; /** * Retrieves a historical version of a versionable / a resource within that versionable. * * @param path path according to the workspace location of a page, may reach into the page * @param versionUuid the uuid of a historical version of a page * @return the resource ( {@link com.composum.sling.platform.staging.impl.StagingResource} ) as it was at the * checkin for version {versionUuid}, or null if there was no corresponding resource in the page at that time * or if the path doesn't resolve into the version {versionUuid} (e.g. is outside of the versionable) * @see com.composum.sling.platform.staging.impl.StagingResource * @see com.composum.sling.platform.staging.impl.VersionSelectResourceResolver */ Resource historicalVersion(@Nonnull ResourceResolver resolver, @Nonnull String path, @Nonnull String versionUuid) throws RepositoryException; /** * a filter implementation using a set of activation state options */ class ActivationStateFilter implements ContentVersionFilter { private final List<PlatformVersionsService.ActivationState> options; public ActivationStateFilter(PlatformVersionsService.ActivationState... options) { this.options = new ArrayList<>(); addOption(options); } public void addOption(PlatformVersionsService.ActivationState... options) { this.options.addAll(Arrays.asList(options)); } @Override public boolean accept(@Nullable ContentVersion version) { PlatformVersionsService.ActivationState contentActivationState; return version != null && (contentActivationState = version.getContentActivationState()) != null && options.contains(contentActivationState); } } /** * A {@link ContentVersionFilter} that filters for {@link ContentVersion#getResource()} matching a * {@link ResourceFilter}. */ class ContentVersionByResourceFilter implements ContentVersionFilter { @Nonnull private final ResourceFilter resourceFilter; public ContentVersionByResourceFilter(@Nonnull ResourceFilter resourceFilter) { this.resourceFilter = Objects.requireNonNull(resourceFilter); } /** True if {@link ContentVersion#getResource()} matches our {@link ResourceFilter} */ @Override public boolean accept(@Nullable ContentVersion version) { Resource resource; return version != null && (resource = version.getResource()) != null && resourceFilter.accept(resource); } } }
40.305344
116
0.67822
4230d01db0bdd82a82e41f6681acd62d98a293cb
1,303
package com.wqlin.android.sample.refresh; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import com.wqlin.android.sample.R; import com.wqlin.widget.irecyclerview.ALoadMoreFooterLayout; /** * Created by 汪倾林 on 2018/2/3. */ public class LoadMoreFooterLayout extends ALoadMoreFooterLayout { public LoadMoreFooterLayout(@NonNull Context context) { this(context,null); } public LoadMoreFooterLayout(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public LoadMoreFooterLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { inflate(getContext(), R.layout.item_text, this); } @Override public void onReset() { } @Override public void onReleaseToRefresh() { } @Override public void onGone() { } @Override public void onLoding() { } @Override public void onComplete() { } @Override public void onError() { } @Override public void onEnd() { } @Override public void onNull() { } }
17.849315
107
0.660783
1160359f46adbf11210657075be39d48858941f2
2,962
package org.junit.runner; import org.junit.internal.Classes; import org.junit.runner.FilterFactory.FilterNotCreatedException; import org.junit.runner.manipulation.Filter; /** * Utility class whose methods create a {@link FilterFactory}. */ class FilterFactories { /** * Creates a {@link Filter}. * * A filter specification is of the form "package.of.FilterFactory=args-to-filter-factory" or * "package.of.FilterFactory". * * @param request the request that will be filtered * @param filterSpec the filter specification * @throws org.junit.runner.FilterFactory.FilterNotCreatedException */ public static Filter createFilterFromFilterSpec(Request request, String filterSpec) throws FilterFactory.FilterNotCreatedException { Description topLevelDescription = request.getRunner().getDescription(); String[] tuple; if (filterSpec.contains("=")) { tuple = filterSpec.split("=", 2); } else { tuple = new String[]{ filterSpec, "" }; } return createFilter(tuple[0], new FilterFactoryParams(topLevelDescription, tuple[1])); } /** * Creates a {@link Filter}. * * @param filterFactoryFqcn The fully qualified class name of the {@link FilterFactory} * @param params The arguments to the {@link FilterFactory} */ public static Filter createFilter(String filterFactoryFqcn, FilterFactoryParams params) throws FilterFactory.FilterNotCreatedException { FilterFactory filterFactory = createFilterFactory(filterFactoryFqcn); return filterFactory.createFilter(params); } /** * Creates a {@link Filter}. * * @param filterFactoryClass The class of the {@link FilterFactory} * @param params The arguments to the {@link FilterFactory} * */ public static Filter createFilter(Class<? extends FilterFactory> filterFactoryClass, FilterFactoryParams params) throws FilterFactory.FilterNotCreatedException { FilterFactory filterFactory = createFilterFactory(filterFactoryClass); return filterFactory.createFilter(params); } static FilterFactory createFilterFactory(String filterFactoryFqcn) throws FilterNotCreatedException { Class<? extends FilterFactory> filterFactoryClass; try { filterFactoryClass = Classes.getClass(filterFactoryFqcn).asSubclass(FilterFactory.class); } catch (Exception e) { throw new FilterNotCreatedException(e); } return createFilterFactory(filterFactoryClass); } static FilterFactory createFilterFactory(Class<? extends FilterFactory> filterFactoryClass) throws FilterNotCreatedException { try { return filterFactoryClass.getConstructor().newInstance(); } catch (Exception e) { throw new FilterNotCreatedException(e); } } }
35.686747
116
0.68366
e2811146b7c9b56242c0f349e5110b4edf088f81
21,269
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tomitribe.churchkey.jwk; import org.tomitribe.churchkey.Key; import org.tomitribe.churchkey.dsa.Dsa; import org.tomitribe.churchkey.ec.Curve; import org.tomitribe.churchkey.ec.ECParameterSpecs; import org.tomitribe.churchkey.ec.Ecdsa; import org.tomitribe.churchkey.ec.UnsupportedCurveException; import org.tomitribe.churchkey.util.Bytes; import org.tomitribe.churchkey.util.Utils; import org.tomitribe.util.IO; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonReader; import javax.json.JsonReaderFactory; import javax.json.JsonValue; import java.math.BigInteger; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; import java.security.interfaces.RSAPrivateCrtKey; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.security.spec.InvalidKeySpecException; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; public class JwkParser implements Key.Format.Parser { @Override public Key decode(final byte[] bytes) { byte[] decoded = normalize(bytes); if (!Utils.startsWith("{", decoded)) return null; final String rawJson = new String(decoded); final HashMap<String, Object> config = new HashMap<>(); config.put("org.apache.johnzon.buffer-strategy", "BY_INSTANCE"); final JsonReaderFactory factory = Json.createReaderFactory(config); final JsonReader reader = factory.createReader(IO.read(decoded)); try { final JsonObject jsonObject = reader.readObject(); final JsonObject jwk = getJwk(jsonObject); final String kty; if (!jwk.containsKey("kty")) { throw new MissingKtyException(); } kty = jwk.getString("kty"); if ("RSA".equalsIgnoreCase(kty)) { return asRsaKey(jwk); } if ("OCT".equalsIgnoreCase(kty)) { return asOctKey(jwk); } if ("DSA".equals(kty)) { return asDsaKey(jwk); } if ("EC".equals(kty)) { return asEcKey(jwk); } throw new UnsupportedKtyAlgorithmException(kty); } catch (Exception e) { throw new InvalidJwkException(e, rawJson); } } private Key asDsaKey(final JsonObject jsonObject) { final Jwk jwk = new Jwk(jsonObject); final BigInteger p = jwk.getBigInteger("p"); final BigInteger q = jwk.getBigInteger("q"); final BigInteger g = jwk.getBigInteger("g"); final BigInteger x = jwk.getBigInteger("x"); final BigInteger y = jwk.getBigInteger("y"); final List<String> missing = new ArrayList<>(); if (p == null) missing.add("p"); if (q == null) missing.add("q"); if (g == null) missing.add("g"); if (missing.size() != 0) { throw new InvalidJwkKeySpecException("DSA", missing); } if (x != null) { final Dsa.Private build = Dsa.Private.builder() .p(p) .q(q) .g(g) .x(x) .build(); final DSAPrivateKey privateKey = build.toKey(); final DSAPublicKey publicKey = build.toPublic().toKey(); final Map<String, String> attributes = getAttributes(jsonObject, "kty", "p", "q", "q", "x", "y"); return new Key(privateKey, publicKey, Key.Type.PRIVATE, Key.Algorithm.DSA, Key.Format.JWK, attributes); } if (y != null) { final DSAPublicKey publicKey = Dsa.Public.builder() .p(p) .q(q) .g(g) .y(y) .build() .toKey(); final Map<String, String> attributes = getAttributes(jsonObject, "kty", "p", "q", "q", "x", "y"); return new Key(publicKey, Key.Type.PUBLIC, Key.Algorithm.DSA, Key.Format.JWK, attributes); } throw new InvalidJwkKeySpecException("DSA", "x", "y"); } /** * { * "kty": "EC", * "crv": "P-256", * "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", * "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", * "d": "870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE", * "use": "enc", * "kid": "1" * } */ private Key asEcKey(final JsonObject jsonObject) { final Jwk jwk = new Jwk(jsonObject); final String crv = jwk.getString("crv"); final BigInteger d = jwk.getBigInteger("d"); final BigInteger x = jwk.getBigInteger("x"); final BigInteger y = jwk.getBigInteger("y"); if (crv == null) throw new InvalidJwkKeySpecException("EC", "crv"); final Curve curve = Curve.resolve(crv); if (d != null) { final Ecdsa.Private build = Ecdsa.Private.builder() .curve(curve) .d(d) .x(x) .y(y) .build(); final ECPrivateKey privateKey = build.toKey(); final ECPublicKey publicKey = build.getX() != null && build.getY() != null ? build.toPublic().toKey() : null; final Map<String, String> attributes = getAttributes(jsonObject, "kty", "crv", "d"); return new Key(privateKey, publicKey, Key.Type.PRIVATE, Key.Algorithm.EC, Key.Format.JWK, attributes); } final List<String> missing = new ArrayList<String>(); if (y == null) missing.add("y"); if (x == null) missing.add("x"); if (missing.size() != 0) { throw new InvalidJwkKeySpecException("EC", missing); } final ECPublicKey publicKey = Ecdsa.Public.builder() .curve(curve) .x(x) .y(y) .build() .toKey(); final Map<String, String> attributes = getAttributes(jsonObject, "kty", "crv", "x", "y"); return new Key(publicKey, Key.Type.PUBLIC, Key.Algorithm.EC, Key.Format.JWK, attributes); } private Key asRsaKey(final JsonObject jsonObject) throws NoSuchAlgorithmException, InvalidKeySpecException { final Jwk jwk = new Jwk(jsonObject); final BigInteger modulus = jwk.getBigInteger("n"); final BigInteger publicExp = jwk.getBigInteger("e"); final BigInteger privateExp = jwk.getBigInteger("d"); final BigInteger primeP = jwk.getBigInteger("p"); final BigInteger primeQ = jwk.getBigInteger("q"); final BigInteger primeExponentP = jwk.getBigInteger("dp"); final BigInteger primeExponentQ = jwk.getBigInteger("dq"); final BigInteger crtCoef = jwk.getBigInteger("qi"); final RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, publicExp); final RSAPrivateCrtKeySpec rsaPrivateKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, primeP, primeQ, primeExponentP, primeExponentQ, crtCoef); checkPublicKey(rsaPublicKeySpec); checkPrivateKey(rsaPrivateKeySpec); final KeyFactory result = KeyFactory.getInstance("RSA"); final PublicKey publicKey = result.generatePublic(rsaPublicKeySpec); if (privateExp != null) { final PrivateKey privateKey = result.generatePrivate(rsaPrivateKeySpec); final Map<String, String> attributes = getAttributes(jsonObject, "kty", "n", "e", "d", "p", "q", "dp", "dq", "qi"); return new Key(privateKey, publicKey, Key.Type.PRIVATE, Key.Algorithm.RSA, Key.Format.JWK, attributes); } final Map<String, String> attributes = getAttributes(jsonObject, "kty", "n", "e"); return new Key(publicKey, Key.Type.PUBLIC, Key.Algorithm.RSA, Key.Format.JWK, attributes); } private void toRsaKey(final Key key, final JsonObjectBuilder jwk) { if (key.getKey() instanceof RSAPrivateCrtKey) { final RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) key.getKey(); jwk.add("n", encode(privateKey.getModulus())); jwk.add("e", encode(privateKey.getPublicExponent())); jwk.add("d", encode(privateKey.getPrivateExponent())); jwk.add("p", encode(privateKey.getPrimeP())); jwk.add("q", encode(privateKey.getPrimeQ())); jwk.add("dp", encode(privateKey.getPrimeExponentP())); jwk.add("dq", encode(privateKey.getPrimeExponentQ())); jwk.add("qi", encode(privateKey.getCrtCoefficient())); } else if (key.getKey() instanceof RSAPrivateKey) { final RSAPrivateKey privateKey = (RSAPrivateKey) key.getKey(); jwk.add("n", encode(privateKey.getModulus())); jwk.add("d", encode(privateKey.getPrivateExponent())); } else if (key.getKey() instanceof RSAPublicKey) { final RSAPublicKey publicKey = (RSAPublicKey) key.getKey(); jwk.add("n", encode(publicKey.getModulus())); jwk.add("e", encode(publicKey.getPublicExponent())); } else { throw new UnsupportedOperationException("Unkown RSA Key type: " + key.getKey().getClass().getName()); } jwk.add("kty", "RSA"); } private void toDsaKey(final Key key, final JsonObjectBuilder jwk) { if (key.getKey() instanceof DSAPrivateKey) { final DSAPrivateKey privateKey = (DSAPrivateKey) key.getKey(); jwk.add("x", encode(privateKey.getX())); jwk.add("p", encode(privateKey.getParams().getP())); jwk.add("q", encode(privateKey.getParams().getQ())); jwk.add("g", encode(privateKey.getParams().getG())); } else if (key.getKey() instanceof DSAPublicKey) { final DSAPublicKey privateKey = (DSAPublicKey) key.getKey(); jwk.add("y", encode(privateKey.getY())); jwk.add("p", encode(privateKey.getParams().getP())); jwk.add("q", encode(privateKey.getParams().getQ())); jwk.add("g", encode(privateKey.getParams().getG())); } else { throw new UnsupportedOperationException("Unkown DSA Key type: " + key.getKey().getClass().getName()); } jwk.add("kty", "DSA"); } private void toEcKey(final Key key, final JsonObjectBuilder jwk) { if (key.getKey() instanceof ECPrivateKey) { final ECPrivateKey privateKey = (ECPrivateKey) key.getKey(); jwk.add("d", encode(privateKey.getS())); jwk.add("crv", curveName(privateKey.getParams())); if (key.getPublicKey() != null) { final ECPublicKey publicKey = (ECPublicKey) key.getPublicKey().getKey(); final ECPoint point = publicKey.getW(); jwk.add("y", encode(point.getAffineY())); jwk.add("x", encode(point.getAffineX())); } } else if (key.getKey() instanceof ECPublicKey) { final ECPublicKey publicKey = (ECPublicKey) key.getKey(); final ECPoint point = publicKey.getW(); jwk.add("y", encode(point.getAffineY())); jwk.add("x", encode(point.getAffineX())); jwk.add("crv", curveName(publicKey.getParams())); } else { throw new UnsupportedOperationException("Unkown EC Key type: " + key.getKey().getClass().getName()); } jwk.add("kty", "EC"); } private String curveName(final ECParameterSpec spec) { // Try the most common cases first if (Curve.p256.isEqual(spec)) return "P-256"; if (Curve.p384.isEqual(spec)) return "P-384"; if (Curve.p521.isEqual(spec)) return "P-521"; for (final Curve curve : Curve.values()) { if (!curve.isEqual(spec)) continue; return curve.getName(); } // Unsupported curve // Print the curve information in the exception final String s = ECParameterSpecs.toString(spec); throw new UnsupportedCurveException(String.format("The specified ECParameterSpec has no known name. Params:%n%s", s)); } private Key asOctKey(final JsonObject jwkObject) { final Jwk jwk = new Jwk(jwkObject); final byte[] keyBytes = jwk.getBytes("k"); final String alg = jwk.getString("alg", "HS256").toUpperCase(); final String jmvAlg = alg.replace("HS", "HmacSHA"); final SecretKeySpec keySpec = new SecretKeySpec(keyBytes, jmvAlg); final Map<String, String> attributes = getAttributes(jwkObject, "kty", "k"); return new Key(keySpec, Key.Type.SECRET, Key.Algorithm.OCT, Key.Format.JWK, attributes); } private void toOctKey(final Key key, final JsonObjectBuilder jwk) { if (key.getKey() instanceof SecretKey) { final SecretKey publicKey = (SecretKey) key.getKey(); jwk.add("k", encode(publicKey.getEncoded())); } else { throw new UnsupportedOperationException("Unkown RSA Key type: " + key.getKey().getClass().getName()); } jwk.add("kty", "oct"); } private Map<String, String> getAttributes(final JsonObject jwkObject, final String... excludes) { return getAttributes(jwkObject, Arrays.asList(excludes)); } private Map<String, String> getAttributes(final JsonObject jwkObject, final Collection<String> excludes) { final Map<String, String> map = new HashMap<>(); for (final Map.Entry<String, JsonValue> entry : jwkObject.entrySet()) { if (excludes.contains(entry.getKey())) continue; map.put(entry.getKey(), toString(entry.getValue())); } return map; } private String toString(final JsonValue value) { switch (value.getValueType()) { case STRING: final String string = value.toString(); return string.substring(1, string.length() - 1); case NULL: return null; default: return value.toString(); } } private void checkPublicKey(final RSAPublicKeySpec spec) { final List<String> missing = new ArrayList<>(); if (spec.getModulus() == null) missing.add("n"); if (spec.getPublicExponent() == null) missing.add("e"); if (missing.size() > 0) throw new InvalidJwkKeySpecException("rsa", missing); } private void checkPrivateKey(final RSAPrivateCrtKeySpec spec) { final List<String> missing = new ArrayList<>(); if (spec.getPrivateExponent() == null) missing.add("d"); if (spec.getPrimeP() == null) missing.add("p"); if (spec.getPrimeQ() == null) missing.add("q"); if (spec.getPrimeExponentP() == null) missing.add("dp"); if (spec.getPrimeExponentQ() == null) missing.add("dq"); if (spec.getCrtCoefficient() == null) missing.add("qi"); /** * We want them to supply either all or none of the private key data */ if (missing.size() == 6) return; // they've supplied none - good if (missing.size() == 0) return; // they've supplied all - good /** * They supplied just some. This doesn't work and isn't likely what they want */ throw new InvalidJwkKeySpecException("rsa", missing); } public static String encode(final BigInteger bigInteger) { final Base64.Encoder urlEncoder = Base64.getUrlEncoder().withoutPadding(); final byte[] bytes = Bytes.trim(bigInteger.toByteArray()); return urlEncoder.encodeToString(bytes); } public static String encode(final byte[] bytes) { final Base64.Encoder urlEncoder = Base64.getUrlEncoder().withoutPadding(); return urlEncoder.encodeToString(bytes); } private static class Jwk { private final JsonObject jwk; public Jwk(final JsonObject jwk) { this.jwk = jwk; } public BigInteger getBigInteger(final String name) { if (!jwk.containsKey(name)) return null; final String string = jwk.getString(name); final java.util.Base64.Decoder urlDecoder = java.util.Base64.getUrlDecoder(); final byte[] bytes = urlDecoder.decode(string); return new BigInteger(1, bytes); } public byte[] getBytes(final String name) { if (!jwk.containsKey(name)) return null; final String string = jwk.getString(name); final java.util.Base64.Decoder urlDecoder = java.util.Base64.getUrlDecoder(); return urlDecoder.decode(string); } public String getString(final String s) { return jwk.getString(s); } public String getString(final String s, final String s1) { return jwk.getString(s, s1); } } private JsonObject getJwk(final JsonObject jsonObject) { if (jsonObject.containsKey("keys")) { return getJwkFromJwks(jsonObject); } if (jsonObject.containsKey("kty")) { return jsonObject; } throw new UnknownJsonFormatFoundException(); } private JsonObject getJwkFromJwks(final JsonObject jwks) { final JsonValue keys = jwks.getValue("keys"); if (keys == null) { throw new IllegalArgumentException("Invalid JWKS; 'keys' entry is missing."); } switch (keys.getValueType()) { case ARRAY: return getFirstJwk(jwks, keys.asJsonArray()); case OBJECT: return keys.asJsonObject(); default: throw new IllegalArgumentException("Invalid JWKS; 'keys' entry should be an array."); } } private JsonObject getFirstJwk(final JsonObject jwks, final JsonArray keys) { if (keys.size() == 0) { throw new IllegalArgumentException("Invalid JWKS; 'keys' entry is empty.\n" + jwks.toString()); } final JsonValue value = keys.get(0); if (!JsonValue.ValueType.OBJECT.equals(value.getValueType())) { throw new IllegalArgumentException("Invalid JWKS; 'keys' array should contain jwk objects.\n" + jwks.toString()); } return value.asJsonObject(); } /** * Base64 unencode the jwk key if needed */ private byte[] normalize(final byte[] bytes) { // Fun optimization, base64 json objects always happen to // start with 'e' due to always beginning with "{" in // unencoded form. If it doesn't start with 'e' then it // isn't base64 encoded or isn't a jwk. if (!Utils.startsWith("e", bytes)) return bytes; // But don't try to convert ecdsa SSH keys if (Utils.startsWith("ecdsa", bytes)) return bytes; return java.util.Base64.getUrlDecoder().decode(bytes); } @Override public byte[] encode(final Key key) { final JsonObjectBuilder builder = Json.createObjectBuilder(); for (final Map.Entry<String, String> entry : key.getAttributes().entrySet()) { builder.add(entry.getKey(), entry.getValue()); } switch (key.getAlgorithm()) { case RSA: toRsaKey(key, builder); break; case DSA: toDsaKey(key, builder); break; case EC: toEcKey(key, builder); break; case OCT: toOctKey(key, builder); break; default: throw new UnsupportedOperationException("Cannot encode key type: " + key.getAlgorithm()); } final JsonObject build = builder.build(); return build.toString().getBytes(); } }
38.812044
169
0.610137
b52e56f908e6125a35de14cc0fd82fb117bcd80c
485
package io.snice.networking.examples.echo; import com.fasterxml.jackson.annotation.JsonProperty; import io.snice.networking.app.NetworkAppConfig; public class EchoClientConfig extends NetworkAppConfig { @JsonProperty("remoteHost") private String echoServerIp; @JsonProperty("remoteIp") private int echoServerPort; public String getEchoServerIp() { return echoServerIp; } public int getEchoServerPort() { return echoServerPort; } }
22.045455
56
0.736082
7048afc5f17f2064f770e77dc9f5843e538daf71
5,650
package com.icm.sphynx.mystyles.ui.metro.manager; import com.icm.sphynx.mystyles.ui.metro.tools.MetroUIConfigTheme; import com.icm.sphynx.mystyles.ui.metro.tools.MetroUIStyleColors; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.basic.BasicCheckBoxMenuItemUI; /** * Asigna los estilos para los menús de tipo combobox * @author israel-icm */ public class UICheckBoxMenuItem extends BasicCheckBoxMenuItemUI{ private String COLOR_FOREGROUND = MetroUIStyleColors.MENU_FOREGROUND; private String COLOR_BACKGROUND = MetroUIStyleColors.MENU_BACKGROUND; private String COLOR_BACKGROUND_SELECT = UITools.colorToHex(MetroUIConfigTheme.getPrimaryColor()); private String COLOR_ICON_BACKGROUND = MetroUIStyleColors.CHECKBOX_ICON_BACKGROUND; private String COLOR_ICON_BORDER = MetroUIStyleColors.CHECKBOX_ICON_BORDER; private String COLOR_ICON_CHECK = MetroUIStyleColors.CHECKBOX_ICON_CHECK; public static ComponentUI createUI(JComponent c) { return new UICheckBoxMenuItem(); } @Override protected void installDefaults() { menuItem.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 5)); // menuItem.setFont(new Font(UITools.FONT_DEFAULT, Font.PLAIN, 13)); // Esto solo es un auxiliar para poder centrar el texto del menu super.installDefaults(); } @Override protected void paintBackground(Graphics g, JMenuItem menuItem, Color bgColor) { installColors(); menuItem.setBackground(Color.decode(COLOR_BACKGROUND)); menuItem.setForeground(Color.decode(COLOR_FOREGROUND)); bgColor = Color.decode(COLOR_BACKGROUND_SELECT); checkIcon = createCheckImage(20, 20, menuItem.isSelected()); super.paintBackground(g, menuItem, bgColor); } @Override protected void paintText(Graphics g, JMenuItem menuItem, Rectangle textRect, String text) { Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setFont(new Font(UITools.FONT_DEFAULT, Font.PLAIN, 14)); g2d.drawString(text, textRect.x, textRect.y + (textRect.height / 2) + 5); } private void installColors() { if (MetroUIConfigTheme.isDarkMode()) { COLOR_FOREGROUND = MetroUIStyleColors.MENU_FOREGROUND_DARK; COLOR_BACKGROUND_SELECT = UITools.colorToHex(MetroUIConfigTheme.getSecondColor()); COLOR_BACKGROUND = MetroUIStyleColors.MENU_BACKGROUND_DARK; COLOR_ICON_BACKGROUND = MetroUIStyleColors.CHECKBOX_ICON_BACKGROUND_DARK; COLOR_ICON_BORDER = MetroUIStyleColors.CHECKBOX_ICON_BORDER_DARK; COLOR_ICON_CHECK = MetroUIStyleColors.CHECKBOX_ICON_CHECK_DARK; } else { COLOR_BACKGROUND_SELECT = UITools.colorToHex(MetroUIConfigTheme.getPrimaryColor()); } } @Override protected Dimension getPreferredMenuItemSize(JComponent c, Icon checkIcon, Icon arrowIcon, int defaultTextIconGap) { Dimension size = super.getPreferredMenuItemSize(c, checkIcon, arrowIcon, defaultTextIconGap); size.width = size.width + 20; // Se agrega 20 por el tamaño del checkbox return size; } /** * Crea la imagen del checkbox * @param width Ancho de la imagen * @param height Alto de la imagen * @param checked Define si el checkbox esta seleccionado o no * @return Retorna la imagen generada */ private ImageIcon createCheckImage(int width, int height, boolean checked) { BufferedImage image = new BufferedImage(width + 5, height + 5, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = (Graphics2D)image.getGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (!checked) { // Fondo del check g2d.setColor(Color.decode(COLOR_ICON_BACKGROUND)); g2d.fillRect(1, 1, width, height); // Borde del check g2d.setColor(Color.decode(COLOR_ICON_BORDER)); g2d.setStroke(new BasicStroke(2)); g2d.drawRect(1, 1, width - 1, height - 1); } else { // Fondo del check g2d.setColor(Color.decode(COLOR_BACKGROUND_SELECT)); g2d.fillRect(1, 1, width, height); // Borde del check g2d.setColor(Color.decode(COLOR_BACKGROUND_SELECT)); g2d.setStroke(new BasicStroke(2)); g2d.drawRect(1, 1, width - 1, height - 1); // Icono del check activado g2d.setStroke(new BasicStroke(2)); // Las ubicaciones se miden en porcentaje para que no se deforme si crece int inicioX = (18 * width) / 100; int inicioY = (60 * height) / 100; int medioX = (40 * width) / 100; int medioY = (80 * height) / 100; int finalX = (90 * width) / 100; int finalY = (30 * height) / 100; g2d.setColor(Color.decode(COLOR_ICON_CHECK)); g2d.drawLine(inicioX, inicioY, medioX, medioY); g2d.drawLine(medioX, medioY, finalX, finalY); } return new ImageIcon(image); } }
42.164179
141
0.685664
cb7dc6ab24c7de7373bd239fe851f532cf53378a
4,238
package d2rq; import java.io.IOException; import jena.cmdline.ArgDecl; import jena.cmdline.CommandLine; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryCancelledException; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.sparql.resultset.ResultsFormat; import com.hp.hpl.jena.sparql.util.QueryExecUtils; import de.fuberlin.wiwiss.d2rq.CommandLineTool; import de.fuberlin.wiwiss.d2rq.D2RQException; import de.fuberlin.wiwiss.d2rq.SystemLoader; import de.fuberlin.wiwiss.d2rq.engine.QueryEngineD2RQ; import de.fuberlin.wiwiss.d2rq.jena.ModelD2RQ; /** * Command line utility for executing SPARQL queries * against a D2RQ-mapped database * * @author Richard Cyganiak ([email protected]) */ public class d2r_query extends CommandLineTool { private static final Log log = LogFactory.getLog(d2r_query.class); public static void main(String[] args) { new d2r_query().process(args); } public void usage() { System.err.println("usage:"); System.err.println(" d2r-query [query-options] mappingFile query"); System.err.println(" d2r-query [query-options] [connection-options] jdbcURL query"); System.err.println(" d2r-query [query-options] [connection-options] -l script.sql query"); System.err.println(); printStandardArguments(true); System.err.println(" query A SPARQL query, e.g., \"SELECT * {?s rdf:type ?o} LIMIT 10\""); System.err.println(" A value of @file.sparql reads the query from a file."); System.err.println(" Query options:"); System.err.println(" -b baseURI Base URI for RDF output (default: " + SystemLoader.DEFAULT_BASE_URI + ")"); System.err.println(" -f format One of text (default), xml, json, csv, tsv, srb, ttl"); System.err.println(" -t timeout Query timeout in seconds"); System.err.println(" --verbose Print debug information"); System.err.println(); System.err.println(" Database connection options (only with jdbcURL):"); printConnectionOptions(); System.err.println(); System.exit(1); } private ArgDecl baseArg = new ArgDecl(true, "b", "base"); private ArgDecl formatArg = new ArgDecl(true, "f", "format"); private ArgDecl timeoutArg = new ArgDecl(true, "t", "timeout"); public void initArgs(CommandLine cmd) { cmd.add(baseArg); cmd.add(formatArg); cmd.add(timeoutArg); setMinMaxArguments(1, 2); setSupportImplicitJdbcURL(true); } public void run(CommandLine cmd, SystemLoader loader) throws IOException { String query = null; if (cmd.numItems() == 1) { query = cmd.getItem(0, true); } else if (cmd.numItems() == 2) { loader.setMappingFileOrJdbcURL(cmd.getItem(0)); query = cmd.getItem(1, true); } String format = null; if (cmd.hasArg(formatArg)) { format = cmd.getArg(formatArg).getValue(); } if (cmd.hasArg(baseArg)) { loader.setSystemBaseURI(cmd.getArg(baseArg).getValue()); } double timeout = -1; if (cmd.hasArg(timeoutArg)) { try { timeout = Double.parseDouble(cmd.getArg(timeoutArg).getValue()); } catch (NumberFormatException ex) { throw new D2RQException("Timeout must be a number in seconds: '" + cmd.getArg(timeoutArg).getValue() + "'", D2RQException.MUST_BE_NUMERIC); } } loader.setFastMode(true); ModelD2RQ d2rqModel = loader.getModelD2RQ(); String prefixes = ""; for (String prefix: d2rqModel.getNsPrefixMap().keySet()) { prefixes += "PREFIX " + prefix + ": <" + d2rqModel.getNsPrefixURI(prefix) + ">\n"; } query = prefixes + query; log.info("Query:\n" + query); try { QueryEngineD2RQ.register(); Query q = QueryFactory.create(query, loader.getResourceBaseURI()); QueryExecution qe = QueryExecutionFactory.create(q, d2rqModel); if (timeout > 0) { qe.setTimeout(Math.round(timeout * 1000)); } QueryExecUtils.executeQuery(q, qe, ResultsFormat.lookup(format)); } catch(QueryCancelledException ex) { throw new D2RQException("Query timeout", ex, D2RQException.QUERY_TIMEOUT); } finally { d2rqModel.close(); } } }
34.737705
117
0.704106
8415b58dc12bcc66af42063c8425b7b56f1207eb
2,835
package analysis; import static util.ArrayOps.*; import static util.ArrayPool.*; import static util.ImageOps.*; import java.awt.Point; import java.awt.image.BufferedImage; public class RotationDetection { static final int imgType = BufferedImage.TYPE_BYTE_GRAY; public static double calculateRotation(double[] img1, double[] img2, int size){ double[] real1 = img1; double[] real2 = img2; double[] imag = alloc(real1.length, 0); double[] imag2 = alloc(real2.length, 0); long time = System.currentTimeMillis(); // FFT ft.FFT2D.doFFT2D(real1, imag, size); ft.FFT2D.doFFT2D(real2, imag2, size); System.out.format("%s: %dms%n", "FFT",System.currentTimeMillis()-time); // power spectrum complexSquare(real1, imag, real1); complexSquare(real2, imag2, real2); System.out.format("%s: %dms%n", "power spec",System.currentTimeMillis()-time); // shift to middle shift2D(real1, size/2, size/2, size, real1); shift2D(real2, size/2, size/2, size, real2); System.out.format("%s: %dms%n", "shift",System.currentTimeMillis()-time); displayLogNorm(real1, size, "power spec 1"); displayLogNorm(real2,size, "power spec 2"); // // polar transform // int angleSamples = size; // polarTransform(real1, real1, size, 0.1, 0.2); // polarTransform(real2, real2, size, 0.1, 0.2); // System.out.format("%s: %dms%n", "polar",System.currentTimeMillis()-time); // // displayLogNorm(real1, size, "polar 1"); // displayLogNorm(real2, size, "polar 2"); // // // translation of polar // Point p = TranslationDetection.calculateTranslation(real1, real2, size); // int min = p.x; // polar transform reduced to 1D int angleSamples = 1024; double[] polar1 = polarTransformAsLine(real1, null, size, 0.1, 0.6, size, angleSamples); double[] polar2 = polarTransformAsLine(real2, null, size, 0.1, 0.6, size, angleSamples); System.out.format("%s: %dms%n", "polar",System.currentTimeMillis()-time); displayLogNorm(polar1, polar1.length, "polar 1"); displayLogNorm(polar2, polar2.length, "polar 2"); // translation of polar int min = TranslationDetection.calculateTranslation1D(polar1, polar2); System.out.format("%s: %dms%n", "correlate",System.currentTimeMillis()-time); // ImageFrame.display(Converter.imageFromArray(normalize(logarithmize(result, result),result), size, imgType), String.format("cross corr (%.3f,%.3f)",max.val1*1.0/size,max.val2*1.0/size)); double degree = min*360.0/angleSamples; System.out.format("angle of %f or %f degree, [%.3fs]%n", degree, degree-360, (System.currentTimeMillis()-time)/1000.0); free(imag); free(imag2); return (min * Math.PI*2.0) / angleSamples; } static double sumAbs(double[] array, int offset, int size){ double sum = 0; for(int i = offset; i < offset+size; i++) sum += Math.abs(array[i]); return sum; } }
34.156627
189
0.688183
1ac167e228820154325457b0d2aa482e460ce453
4,803
package net.n2oapp.cache.template; import net.n2oapp.context.StaticSpringContext; import net.sf.ehcache.Element; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * User: iryabov * Date: 30.03.13 * Time: 10:52 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("test-two-level-cache-context.xml") public class TwoLevelCacheTemplateTest { @Test public void testFirstCacheMissAndSecondCacheMiss() { CacheManager cacheManager = StaticSpringContext.getBean(CacheManager.class); TwoLevelCacheTemplate<Integer, String, String> twoLevelCacheTemplate = new TwoLevelCacheTemplate<>(); twoLevelCacheTemplate.setCacheManager(cacheManager); String value = twoLevelCacheTemplate.execute("first", "second", 1, new TwoLevelCacheCallback<String, String>() { @Override public String doInFirstLevelCacheMiss(String valueFromSecondLevelCache) { return valueFromSecondLevelCache; } @Override public String doInSecondLevelCacheMiss() { return "test"; } }); assert "test".equals(value); } @Test public void testFirstCacheMissAndSecondCacheHit() { CacheManager cacheManager = StaticSpringContext.getBean(CacheManager.class); TwoLevelCacheTemplate<Integer, String, String> twoLevelCacheTemplate = new TwoLevelCacheTemplate<>(); twoLevelCacheTemplate.setCacheManager(cacheManager); cacheManager.getCache("second").put(1, "test"); String value = twoLevelCacheTemplate.execute("first", "second", 1, new TwoLevelCacheCallback<String, String>() { @Override public String doInFirstLevelCacheMiss(String valueFromSecondLevelCache) { return valueFromSecondLevelCache; } @Override public String doInSecondLevelCacheMiss() { throw new AssertionError("second level cache could not be invoked"); } }); assert "test".equals(value); } @Test public void testFirstCacheHit() { CacheManager cacheManager = StaticSpringContext.getBean(CacheManager.class); TwoLevelCacheTemplate<Integer, String, String> twoLevelCacheTemplate = new TwoLevelCacheTemplate<>(); twoLevelCacheTemplate.setCacheManager(cacheManager); cacheManager.getCache("first").put(1, "test"); String value = twoLevelCacheTemplate.execute("first", "second", 1, new TwoLevelCacheCallback<String, String>() { @Override public String doInFirstLevelCacheMiss(String valueFromSecondLevelCache) { throw new AssertionError("first level cache could not be invoked"); } @Override public String doInSecondLevelCacheMiss() { throw new AssertionError("second level cache could not be invoked"); } }); assert "test".equals(value); } @Test @Ignore public void testWriteBehindPutSyncEvictSync() throws InterruptedException { CacheManager cacheManager = StaticSpringContext.getBean(CacheManager.class); Cache cache = cacheManager.getCache("writeBehindCache"); net.sf.ehcache.Cache nativeCache = (net.sf.ehcache.Cache) cache.getNativeCache(); System.out.println("cache put:" + "test"); nativeCache.putWithWriter(new Element(1, "test")); System.out.println("cache get:" + cache.get(1).get()); System.out.println("sleep:" + 2 + "s"); Thread.sleep(2000); System.out.println("cache evict:" + 1); System.out.println("cache get:" + cache.get(1).get()); nativeCache.removeWithWriter(1); System.out.println("cache get:" + cache.get(1)); System.out.println("sleep:" + 2 + "s"); Thread.sleep(2000); } @Test @Ignore public void testWriteBehindPutEvictSync() throws InterruptedException { CacheManager cacheManager = StaticSpringContext.getBean(CacheManager.class); Cache cache = cacheManager.getCache("writeBehindCache"); net.sf.ehcache.Cache nativeCache = (net.sf.ehcache.Cache) cache.getNativeCache(); System.out.println("cache put:" + "test"); nativeCache.putWithWriter(new Element(1, "test")); System.out.println("cache get:" + cache.get(1).get()); System.out.println("cache evict:" + 1); nativeCache.removeWithWriter(1); System.out.println("sleep:" + 2 + "s"); Thread.sleep(2000); } }
40.70339
120
0.669373
c68ad57819d5a4f62d5430e3d67041b910c7de50
6,476
/* * Copyright 2012-2013 Hippo B.V. (http://www.onehippo.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onehippo.repository.mock; import java.io.InputStream; import java.math.BigDecimal; import java.util.Calendar; import javax.jcr.Binary; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Value; import javax.jcr.ValueFormatException; import org.apache.jackrabbit.util.ISO8601; /** * Mock version of a {@link Value}. */ public class MockValue implements Value { private int type; private String stringifiedValue; private Binary binary; @SuppressWarnings("unused") public MockValue() { // used by JAXB } public MockValue(String stringifiedValue) { this(PropertyType.STRING, stringifiedValue); } public MockValue(Binary binaryValue) { this.type = PropertyType.BINARY; this.binary = binaryValue; } public MockValue(int type, String stringifiedValue) { this.type = type; this.stringifiedValue = stringifiedValue; } public MockValue(Value value) throws RepositoryException { this.type = value.getType(); switch (type) { case PropertyType.STRING: { this.stringifiedValue = value.getString(); break; } case PropertyType.DATE: { this.stringifiedValue = ISO8601.format(value.getDate()); break; } case PropertyType.BOOLEAN: { this.stringifiedValue = Boolean.toString(value.getBoolean()); break; } case PropertyType.LONG: { this.stringifiedValue = Long.toString(value.getLong()); break; } case PropertyType.DOUBLE: { this.stringifiedValue = Double.toString(value.getDouble()); break; } case PropertyType.DECIMAL: { this.stringifiedValue = value.getDecimal().toString(); break; } case PropertyType.BINARY: { this.binary = value.getBinary(); break; } case PropertyType.NAME: { this.stringifiedValue = value.getString(); break; } case PropertyType.URI: { this.stringifiedValue = value.getString(); break; } default: { throw new UnsupportedOperationException("Unsupported type, " + type + ". Only primitive number/string values are currently supported."); } } } @Override public int getType() { return type; } @Override public String getString() throws ValueFormatException { checkNotBinary(); return stringifiedValue; } private void checkNotBinary() throws ValueFormatException { if (binary != null) { throw new ValueFormatException("Binary value cannot be converted to a string"); } } @Override public Calendar getDate() throws ValueFormatException { checkNotBinary(); try { Calendar date = ISO8601.parse(stringifiedValue); if (date == null) { throw new ValueFormatException("Invalid date format (ISO8601). " + stringifiedValue); } return date; } catch (Exception e) { throw new ValueFormatException(e); } } @Override public boolean getBoolean() throws ValueFormatException { checkNotBinary(); try { return Boolean.parseBoolean(stringifiedValue); } catch (Exception e) { throw new ValueFormatException(e); } } @Override public long getLong() throws ValueFormatException { checkNotBinary(); try { return Long.parseLong(stringifiedValue); } catch (Exception e) { throw new ValueFormatException(e); } } @Override public double getDouble() throws ValueFormatException { checkNotBinary(); try { return Double.parseDouble(stringifiedValue); } catch (Exception e) { throw new ValueFormatException(e); } } @Override public BigDecimal getDecimal() throws ValueFormatException { checkNotBinary(); try { return new BigDecimal(stringifiedValue); } catch (Exception e) { throw new ValueFormatException(e); } } @Override public InputStream getStream() throws RepositoryException { throw new UnsupportedOperationException("Use #getBinary instead"); } @Override public Binary getBinary() throws RepositoryException { if (binary != null) { return binary; } throw new RepositoryException("Value is not binary"); } @Override public boolean equals(final Object o) { if (this == o) { return true; } else if (o instanceof MockValue) { MockValue other = (MockValue) o; if (stringifiedValue != null) { return stringifiedValue.equals(other.stringifiedValue); } else { return binary.equals(other.binary); } } return false; } @Override public int hashCode() { if (stringifiedValue != null) { return stringifiedValue.hashCode(); } return binary.hashCode(); } @Override public String toString() { StringBuffer result = new StringBuffer(super.toString()); result.append(";{type: ").append(type); if (stringifiedValue != null) { result.append(", '").append(stringifiedValue).append("'"); } result.append("}"); return result.toString(); } }
28.910714
152
0.585083
7c4f8f81f76395b6fa2e2601ea4aa92830e6aacb
5,804
package controllers; import play.*; import play.mvc.*; import play.data.*; import play.data.Form.*; import play.mvc.Http.Context; import java.util.*; import views.html.*; // Import models import models.*; import models.users.*; import models.products.*; import models.shopping.*; // Import security controllers import controllers.security.*; public class Application extends Controller { public Result index() { //List<Product> products = new ArrayList<Product>(); //products = Product.findAll(); return ok(index.render(Form.form(Login.class), User.getLoggedIn(session().get("email")))); } public Result about() { return ok(about.render(User.getLoggedIn(session().get("email")))); } public Result contact() { return ok(contact.render(User.getLoggedIn(session().get("email")))); } public Result product(Long id) { try { List<Product> products = new ArrayList<Product>(); products = Product.findAll(); Product p = Product.find.byId(id); return ok(product.render(p, User.getLoggedIn(session().get("email")), products)); } catch(Exception e) { return ok(error.render("This product may not exist", User.getLoggedIn(session().get("email")))); } } public Result listOrders() { try{ List<ShopOrder> orders = new ArrayList<ShopOrder>(); List<ShopOrder> ordersCust = new ArrayList<ShopOrder>(); Customer customer = Customer.getLoggedIn(session().get("email")); orders = ShopOrder.findAll(); for(ShopOrder o : orders){ if(o.customer.email.equals(customer.email)){ ordersCust.add(o); } } return ok(listOrders.render(ordersCust,customer, User.getLoggedIn(session().get("email")))); }catch(Exception e){ return redirect(controllers.security.routes.LoginCtrl.login()); } } public Result register() { // Instantiate a form object based on the Product class Form<Customer> addUserForm = Form.form(Customer.class); // passing the form object return ok(register.render(addUserForm, User.getLoggedIn(session().get("email")))); } // Handle the form data when a new product is submitted public Result addUserSubmit() { Form<Customer> newUserForm = Form.form(Customer.class).bindFromRequest(); try{ // Create a product form object (to hold submitted data) // 'Bind' the object to the submitted form (this copies the filled form) // Check for errors (based on Product class annotations) if(newUserForm.hasErrors()) { // Display the form again return badRequest(register.render(newUserForm, User.getLoggedIn(session().get("email")))); } Customer newCustomer = newUserForm.get(); // Save product now to set id (needed to update manytomany) newCustomer.save(); // Set a sucess message in temporary flash flash("success", "User registered!"); // Redirect to the admin home return redirect(controllers.security.routes.LoginCtrl.login()); }catch(Exception e){ flash("success", "This email is already in use!"); return badRequest(register.render(newUserForm, User.getLoggedIn(session().get("email")))); } } public Result editProfile(String email) { // Instantiate a form object based on the Product class Customer c = Customer.find.ref(email); Form<Customer> editProfileForm = Form.form(Customer.class).fill(c); // Render the Add Product View, passing the form object return ok(editProfile.render(email, editProfileForm, User.getLoggedIn(session().get("email")))); } // Handle the form data when a new product is submitted public Result editProfileSubmit(String email) { // Create a product form object (to hold submitted data) // 'Bind' the object to the submitted form (this copies the filled form) Form<Customer> updateProfileForm = Form.form(Customer.class).bindFromRequest(); // Check for errors (based on Product class annotations) if(updateProfileForm.hasErrors()) { // Display the form again return badRequest(editProfile.render(email, updateProfileForm, User.getLoggedIn(session().get("email")))); } Customer c = updateProfileForm.get(); c.email = email; // Save product now to set id (needed to update manytomany) c.update(); // Set a sucess message in temporary flash flash("success"); // Redirect to the admin home return redirect(routes.Application.index()); } public Result resultPage(String arg){ List<Product> products = new ArrayList<Product>(); List<Product> resultList = new ArrayList<Product>(); products = Product.findAll(); //search through all products for(Product p : products) { if(p.name.toLowerCase().contains(arg.toLowerCase()) || p.description.toLowerCase().contains(arg.toLowerCase())){ resultList.add(p); } } return ok(resultPage.render(arg, resultList, User.getLoggedIn(session().get("email")))); } public Result error(String e){ return ok(error.render(e, User.getLoggedIn(session().get("email")))); } public Result deleteAccount(String email) { // Call delete method try{ Customer.find.ref(email).delete(); // Add message to flash session flash("success", "Account has been deleted"); // Redirect home return redirect(routes.Application.index()); }catch(Exception e){ return ok(error.render("Be sure to clear your cart first!", User.getLoggedIn(session().get("email")))); } } }
30.387435
118
0.64266
3d4ccbc94726b56e9a60ac368a63f9a31834ead6
439
package _12InfernoInfinityCompareTo; import _12InfernoInfinityCompareTo.enums.Gem; import _12InfernoInfinityCompareTo.enums.WeaponType; public class Axe extends WeaponImpl { public Axe(String name) { super.setName(name); super.setDefaultMinDamage(WeaponType.AXE.getMinDamage()); super.setDefaultMaxDamage(WeaponType.AXE.getMaxDamage()); super.setSockets(new Gem[WeaponType.AXE.getSockets()]); } }
31.357143
65
0.753986
7cd790b5effb8579cda5bae942020e231b8b962a
733
package de.yard.threed.graph; import java.util.ArrayList; import java.util.List; /** * Difference to GraphPath? A transition isType a "short path" used for connecting edges. * * Created by thomass on 24.05.17. */ public class GraphTransition { public List<GraphPathSegment> seg = new ArrayList<GraphPathSegment>(); public GraphTransition() { } public GraphTransition(GraphPathSegment s) { this.seg.add(s); } public GraphTransition(GraphPathSegment s0, GraphPathSegment s1, GraphPathSegment s2) { this.seg.add(s0); this.seg.add(s1); this.seg.add(s2); } public void add(GraphPathSegment graphPathSegement) { seg.add(graphPathSegement); } }
23.645161
91
0.671214
84ee14441c5646a886d17d30705e428bb3bf42e7
941
package com.example.chardsoftcryptowallet.core.database.models; import java.time.LocalDateTime; public class Transaction { private final String Id; private final String From; private final String To; private final float Value; private final LocalDateTime Datetime; private final boolean Success; public String getId() { return Id; } public String getFrom() { return From; } public String getTo() { return To; } public float getValue() { return Value; } public LocalDateTime getDatetime() { return Datetime; } public boolean isSuccess() { return Success; } public Transaction(String id, String from, String to, float value, LocalDateTime datetime, boolean success) { Id = id; From = from; To = to; Value = value; Datetime = datetime; Success = success; } }
20.456522
113
0.616366
bfb15e92c1a737a68b7bef48f14693ee0019a5da
5,029
// Needs 2.0.1 update before finishing port /* package org.jbox2d.testbed.tests; import org.jbox2d.collision.PolygonDef; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.joints.RevoluteJoint; import org.jbox2d.testbed.AbstractExample; import org.jbox2d.testbed.TestbedMain; */ /** * Inspired by a contribution by roman_m * Dimensions scooped from APE (http://www.cove.org/ape/index.htm) */ /* public class TheoJansen extends AbstractExample { Vec2 m_offset; Body m_chassis; Body m_wheel; RevoluteJoint m_motorJoint; boolean m_motorOn; float m_motorSpeed; public TheoJansen(TestbedMain p) { super(p); } public String getName() { return "Theo Jansen Walker"; } void createLeg(float s, Vec2 wheelAnchor) { Vec2 p1 = new Vec2(5.4f * s, -6.1f); Vec2 p2 = new Vec2(7.2f * s, -1.2f); Vec2 p3 = new Vec2(4.3f * s, -1.9f); Vec2 p4 = new Vec2(3.1f * s, 0.8f); Vec2 p5 = new Vec2(6.0f * s, 1.5f); Vec2 p6 = new Vec2(2.5f * s, 3.7f); PolygonDef sd1 = new PolygonDef(); PolygonDef sd2 = new PolygonDef(); sd1.filter.groupIndex = -1; sd2.filter.groupIndex = -1; sd1.density = 1.0f; sd2.density = 1.0f; if (s > 0.0f) { sd1.vertices[0] = p1; sd1.vertices[1] = p2; sd1.vertices[2] = p3; sd2.vertices[0] = Vec2_zero; sd2.vertices[1] = p5 - p4; sd2.vertices[2] = p6 - p4; } else { sd1.vertices[0] = p1; sd1.vertices[1] = p3; sd1.vertices[2] = p2; sd2.vertices[0] = Vec2_zero; sd2.vertices[1] = p6 - p4; sd2.vertices[2] = p5 - p4; } b2BodyDef bd1, bd2; bd1.position = m_offset; bd2.position = p4 + m_offset; bd1.angularDamping = 10.0f; bd2.angularDamping = 10.0f; b2Body* body1 = m_world.createBody(&bd1); b2Body* body2 = m_world.createBody(&bd2); body1.createShape(&sd1); body2.createShape(&sd2); body1.setMassFromShapes(); body2.setMassFromShapes(); b2DistanceJointDef djd; djd.Initialize(body1, body2, p2 + m_offset, p5 + m_offset); m_world.createJoint(&djd); djd.Initialize(body1, body2, p3 + m_offset, p4 + m_offset); m_world.createJoint(&djd); djd.Initialize(body1, m_wheel, p3 + m_offset, wheelAnchor + m_offset); m_world.createJoint(&djd); djd.Initialize(body2, m_wheel, p6 + m_offset, wheelAnchor + m_offset); m_world.createJoint(&djd); b2RevoluteJointDef rjd; rjd.Initialize(body2, m_chassis, p4 + m_offset); m_world.createJoint(&rjd); } void TheoJansen(){ m_offset.set(0.0f, 8.0f); m_motorSpeed = 2.0f; m_motorOn = true; Vec2 pivot = new Vec2(0.0f, 0.8f); { b2PolygonDef sd; sd.SetAsBox(50.0f, 10.0f); b2BodyDef bd; bd.position.Set(0.0f, -10.0f); b2Body* ground = m_world.createBody(&bd); ground.createShape(&sd); sd.SetAsBox(0.5f, 5.0f, Vec2(-50.0f, 15.0f), 0.0f); ground.createShape(&sd); sd.SetAsBox(0.5f, 5.0f, Vec2(50.0f, 15.0f), 0.0f); ground.createShape(&sd); } for (int32 i = 0; i < 40; ++i) { b2CircleDef sd; sd.density = 1.0f; sd.radius = 0.25f; b2BodyDef bd; bd.position.Set(-40.0f + 2.0f * i, 0.5f); b2Body* body = m_world.createBody(&bd); body.createShape(&sd); body.setMassFromShapes(); } { b2PolygonDef sd; sd.density = 1.0f; sd.SetAsBox(2.5f, 1.0f); sd.filter.groupIndex = -1; b2BodyDef bd; bd.position = pivot + m_offset; m_chassis = m_world.createBody(&bd); m_chassis.createShape(&sd); m_chassis.setMassFromShapes(); } { b2CircleDef sd; sd.density = 1.0f; sd.radius = 1.6f; sd.filter.groupIndex = -1; b2BodyDef bd; bd.position = pivot + m_offset; m_wheel = m_world.createBody(&bd); m_wheel.createShape(&sd); m_wheel.setMassFromShapes(); } { b2RevoluteJointDef jd; jd.Initialize(m_wheel, m_chassis, pivot + m_offset); jd.collideConnected = false; jd.motorSpeed = m_motorSpeed; jd.maxMotorTorque = 400.0f; jd.enableMotor = m_motorOn; m_motorJoint = (b2RevoluteJoint*)m_world.createJoint(&jd); } Vec2 wheelAnchor; wheelAnchor = pivot + Vec2(0.0f, -0.8f); CreateLeg(-1.0f, wheelAnchor); CreateLeg(1.0f, wheelAnchor); m_wheel.setXForm(m_wheel.getPosition(), 120.0f * b2_pi / 180.0f); CreateLeg(-1.0f, wheelAnchor); CreateLeg(1.0f, wheelAnchor); m_wheel.setXForm(m_wheel.getPosition(), -120.0f * b2_pi / 180.0f); CreateLeg(-1.0f, wheelAnchor); CreateLeg(1.0f, wheelAnchor); } void Step(Settings* settings) { DrawString(5, m_textLine, "Keys: left = a, brake = s, right = d, toggle motor = m"); m_textLine += 15; Test::Step(settings); } void Keyboard(unsigned char key) { switch (key) { case 'a': m_chassis->WakeUp(); m_motorJoint->SetMotorSpeed(-m_motorSpeed); break; case 's': m_chassis->WakeUp(); m_motorJoint->SetMotorSpeed(0.0f); break; case 'd': m_chassis->WakeUp(); m_motorJoint->SetMotorSpeed(m_motorSpeed); break; case 'm': m_chassis->WakeUp(); m_motorJoint->EnableMotor(!m_motorJoint->IsMotorEnabled()); break; } } }*/
22.252212
86
0.65341
48d6750df4f18455532931730d70c737e2305ddc
115
/** * aliyun sms. * * @author shishuihao * @version 1.0.0 */ package cn.shishuihao.thirdparty.api.sms.aliyun;
14.375
48
0.66087
572e2b1d5affcedd912b2c0478f706312ec40aa0
1,151
package org.wwr.frc2013.pneumatics; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.command.Subsystem; import org.wwr.frc2013.RMap; /** * * @author Austin Reuland */ public class SS_LiftHooks extends Subsystem { // Put methods for controlling this subsystem // here. Call these from Commands. private static final Solenoid hooks = new Solenoid(RMap.MODULE_SOLENOID_MAIN, RMap.SOLENOID_LIFT_VALVE); private static final SS_LiftHooks instance = new SS_LiftHooks(); public static SS_LiftHooks getInstance(){ return instance; } static{ } private SS_LiftHooks(){ super("SS_LiftHooks"); } public static boolean get(){ return hooks.get(); } public static void set(boolean var){ hooks.set(var); } public static void up(){ hooks.set(true); } public static void down(){ hooks.set(false); } public static boolean isUp(){ return hooks.get() == true; } public static boolean isDown(){ return hooks.get() == false; } public void initDefaultCommand() { // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } }
19.183333
105
0.697654
0e65e1bb4667fccfdc437f4ed01baff940d57a38
5,191
package site.bigdataresource.hbase; import org.apache.commons.collections.IteratorUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.mapred.TableOutputFormat; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.mapreduce.Job; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.function.Function; import org.apache.spark.api.java.function.VoidFunction; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import site.bigdataresource.spark.JavaSparkSessionSingleton; import site.bigdataresource.utils.PropertiesUtils; import java.util.Iterator; import java.util.List; import java.util.Properties; /**site.bigdataresource.hbase.Hdfs2HBase * Created by [email protected] on 10/10/17. */ public class Hdfs2HBase { public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("Must Set Hbase Table"); System.exit(1); } String hbaseTableName = args[0]; String columnFamily = "A"; final byte[] cf = Bytes.toBytes(columnFamily); Configuration hbaseConf = HBaseConfiguration.create(); //通过读取本地配置文件的方式读取基本配置 //TODO:配置文件的读取单独提炼出来 Properties props = PropertiesUtils.load("hbase.properties"); //zk的端口 hbaseConf.set("hbase.zookeeper.property.clientPort", props.getProperty("hbase.zookeeper.property.clientPort", "2181")); //zk集群的地址 hbaseConf.set("hbase.zookeeper.quorum", props.getProperty("hbase.zookeeper.quorum")); hbaseConf.set("hbase.defaults.for.version.skip", "true"); hbaseConf.set(TableOutputFormat.OUTPUT_TABLE, hbaseTableName); Connection connection = ConnectionFactory.createConnection(); final Table table = connection.getTable(TableName.valueOf(hbaseTableName)); Job job = Job.getInstance(hbaseConf); job.setMapOutputKeyClass(ImmutableBytesWritable.class); job.setMapOutputValueClass(Result.class); // JavaSparkSessionSingleton SparkSession spark = JavaSparkSessionSingleton.getInstance("site.bigdataresource.hbase.Hdfs2HBase", "n"); String path = "hdfs://10.28.52.43:8020/user/hive/warehouse/dw.db/qyxx_gdxx/dt=20171009"; Dataset<Row> ds = spark.read().orc(path); JavaRDD<Row> rowJavaRDD = ds.toJavaRDD(); JavaRDD<Put> putJavaRDD = rowJavaRDD.map(new Function<Row, Put>() { @Override public Put call(Row row) throws Exception { Put put = new Put(Bytes.toBytes(row.getString(3) + row.getString(12) + row.get(11))); put.addColumn(cf, Bytes.toBytes("id"), Bytes.toBytes(row.getString(0))); put.addColumn(cf, Bytes.toBytes("idno"), Bytes.toBytes(row.getString(1))); put.addColumn(cf, Bytes.toBytes("idtype"), Bytes.toBytes(row.getString(2))); put.addColumn(cf, Bytes.toBytes("bbd_qyxx_id"), Bytes.toBytes(row.getString(3))); put.addColumn(cf, Bytes.toBytes("invest_amount"), Bytes.toBytes(row.getString(4))); put.addColumn(cf, Bytes.toBytes("invest_name"), Bytes.toBytes(row.getString(5))); put.addColumn(cf, Bytes.toBytes("invest_ratio"), Bytes.toBytes(row.getString(6))); put.addColumn(cf, Bytes.toBytes("name_compid"), Bytes.toBytes(row.getString(7))); put.addColumn(cf, Bytes.toBytes("no"), Bytes.toBytes(row.getString(8))); put.addColumn(cf, Bytes.toBytes("paid_contribution"), Bytes.toBytes(row.getString(9))); put.addColumn(cf, Bytes.toBytes("shareholder_detail"), Bytes.toBytes(row.getString(10))); put.addColumn(cf, Bytes.toBytes("shareholder_id"), Bytes.toBytes(row.getString(11))); put.addColumn(cf, Bytes.toBytes("shareholder_name"), Bytes.toBytes(row.getString(12))); put.addColumn(cf, Bytes.toBytes("shareholder_type"), Bytes.toBytes(row.getString(13))); put.addColumn(cf, Bytes.toBytes("subscribed_capital"), Bytes.toBytes(row.getString(14))); put.addColumn(cf, Bytes.toBytes("bbd_dotime"), Bytes.toBytes(row.getString(15))); put.addColumn(cf, Bytes.toBytes("company_name"), Bytes.toBytes(row.getString(16))); put.addColumn(cf, Bytes.toBytes("bbd_uptime"), Bytes.toBytes(row.getString(17))); put.addColumn(cf, Bytes.toBytes("create_time"), Bytes.toBytes(row.getString(18))); put.addColumn(cf, Bytes.toBytes("sumconam"), Bytes.toBytes(row.getString(19))); return put; } }); putJavaRDD.foreachPartition(new VoidFunction<Iterator<Put>>() { @Override public void call(Iterator<Put> iterator) throws Exception { List puts = IteratorUtils.toList(iterator); table.put(puts); } }); } }
49.438095
127
0.671162
de7c04f7aaed54147c38585d1963f7188a69ae0f
466
package framework; import java.io.IOException; /** * Defines operations for any class that wishes to be notified when an {@link IAgent} hits a goal. * * @author Zachary Paul Faltersack * @version 0.95 */ public interface IGoalListener { //region Methods /** * Callback for receiving a goal {@link GoalEvent}. * * @param event The event to receive. */ void goalReceived(GoalEvent event) throws IOException; //endregion }
19.416667
98
0.671674
38e6bced7ca8d377edaf04a8ce60b5519e01bc2d
14,401
/* * Copyright 2015 The Energy Detective. All Rights Reserved. */ package com.ted.commander.server.dao; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.ted.commander.common.model.VirtualECC; import com.ted.commander.common.model.history.HistoryKey; import com.ted.commander.common.model.history.HistoryMTUBillingCycle; import com.ted.commander.common.model.history.HistoryMTUBillingCycleKey; import com.ted.commander.server.services.HazelcastService; import com.ted.commander.server.services.PollingService; import com.ted.commander.server.services.ServerService; import com.ted.commander.server.util.CalendarUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DuplicateKeyException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import java.util.concurrent.TimeUnit; /** * DAO for accessing the EnergyData object */ @Repository public class HistoryMTUBillingCycleDAO extends SimpleAbstractDAO { private static final String INSERT = "INSERT INTO history_mtu_billingCycle " + "(virtualECC_id, " + "mtu_id, " + "billingCycleMonth, " + "billingCycleYear, " + "startEpoch, " + "endEpoch, " + "energy, " + "cost, " + "demandPeak, " + "demandPeakTime, " + "peakVoltage, " + "peakVoltageTime, " + "minVoltage, " + "minVoltageTime, " + "pfSampleCount, " + "pfTotal, " + "touOffPeak, " + "touPeak, " + "touMidPeak, " + "touSuperPeak) " + "VALUES " + "(:virtualECC_id, " + ":mtu_id, " + ":billingCycleMonth, " + ":billingCycleYear, " + ":startEpoch, " + ":endEpoch, " + ":energy, " + ":cost, " + ":demandPeak, " + ":demandPeakTime, " + ":peakVoltage, " + ":peakVoltageTime, " + ":minVoltage, " + ":minVoltageTime, " + ":pfSampleCount, " + ":pfTotal, " + ":touOffPeak, " + ":touPeak, " + ":touMidPeak, " + ":touSuperPeak)"; private static final String SAVE = "UPDATE history_mtu_billingCycle" + " SET " + " energy = :energy, " + " cost = :cost, " + " demandPeak = :demandPeak, " + " demandPeakTime = :demandPeakTime, " + " peakVoltage = :peakVoltage, " + " peakVoltageTime = :peakVoltageTime, " + " minVoltage = :minVoltage, " + " minVoltageTime = :minVoltageTime, " + " pfSampleCount = :pfSampleCount, " + " pfTotal = :pfTotal, " + " touOffPeak = :touOffPeak, " + " touPeak = :touPeak, " + " touMidPeak = :touMidPeak, " + " touSuperPeak = :touSuperPeak " + " WHERE virtualECC_id = :virtualECC_id " + " AND mtu_id = :mtu_id " + " AND billingCycleYear = :billingCycleYear " + " AND billingCycleMonth = :billingCycleMonth "; private static final String FIND_BY_DATE_RANGE_QUERY = "select * from history_mtu_billingCycle where virtualECC_id=:virtualECCId and mtu_id = :mtuId and ((startEpoch >= :startEpoch and startEpoch < :endEpoch) or (:startEpoch >= startEpoch and :startEpoch < endEpoch) or (:endEpoch >= startEpoch and :endEpoch < endEpoch)) order by startEpoch"; @Autowired HazelcastService hazelcastService; @Autowired VirtualECCDAO virtualECCDAO; private RowMapper<HistoryMTUBillingCycle> rowMapper = new RowMapper<HistoryMTUBillingCycle>() { public HistoryMTUBillingCycle mapRow(ResultSet rs, int rowNum) throws SQLException { HistoryMTUBillingCycle dto = new HistoryMTUBillingCycle(); HistoryMTUBillingCycleKey key = new HistoryMTUBillingCycleKey(); key.setVirtualECCId(rs.getLong("virtualECC_id")); key.setMtuId(rs.getLong("mtu_id")); key.setBillingCycleYear(rs.getInt("billingCycleYear")); key.setBillingCycleMonth(rs.getInt("billingCycleMonth")); dto.setKey(key); dto.setStartEpoch(rs.getLong("startEpoch")); dto.setEndEpoch(rs.getLong("endEpoch")); dto.setEnergy(rs.getDouble("energy")); dto.setCost(rs.getDouble("cost")); dto.setDemandPeak(rs.getDouble("demandPeak")); dto.setDemandPeakTime(rs.getLong("demandPeakTime")); dto.setTouOffPeak(rs.getDouble("touOffPeak")); dto.setTouPeak(rs.getDouble("touPeak")); dto.setTouMidPeak(rs.getDouble("touMidPeak")); dto.setTouSuperPeak(rs.getDouble("touSuperPeak")); dto.setPeakVoltage(rs.getDouble("peakVoltage")); dto.setPeakVoltageTime(rs.getLong("peakVoltageTime")); dto.setMinVoltage(rs.getDouble("minVoltage")); dto.setMinVoltageTime(rs.getLong("minVoltageTime")); dto.setPfSampleCount(rs.getLong("pfSampleCount")); dto.setPfTotal(rs.getDouble("pfTotal")); updateCalendarKeys(dto); return dto; } }; private Map getNamedParameters(HistoryMTUBillingCycle dto) { Map<String, Object> namedParameters = new HashMap(64); namedParameters.put("virtualECC_id", dto.getKey().getVirtualECCId()); namedParameters.put("mtu_id", dto.getKey().getMtuId()); namedParameters.put("billingCycleMonth", dto.getKey().getBillingCycleMonth()); namedParameters.put("billingCycleYear", dto.getKey().getBillingCycleYear()); namedParameters.put("startEpoch", dto.getStartEpoch()); namedParameters.put("endEpoch", dto.getEndEpoch()); namedParameters.put("energy", dto.getEnergy()); namedParameters.put("cost", dto.getCost()); namedParameters.put("demandPeak", dto.getDemandPeak()); namedParameters.put("demandPeakTime", dto.getDemandPeakTime()); namedParameters.put("touOffPeak", dto.getTouOffPeak()); namedParameters.put("touPeak", dto.getTouPeak()); namedParameters.put("touMidPeak", dto.getTouMidPeak()); namedParameters.put("touSuperPeak", dto.getTouSuperPeak()); // namedParameters.put("peakVoltage", dto.getPeakVoltage()); if (dto.getPeakVoltage() < 0) namedParameters.put("peakVoltage", 120.0); else if (dto.getPeakVoltage() > 999.0) namedParameters.put("peakVoltage", 999.0); else namedParameters.put("peakVoltage", dto.getPeakVoltage()); namedParameters.put("peakVoltageTime", dto.getPeakVoltageTime()); if (dto.getMinVoltage() < 0) namedParameters.put("minVoltage", 0.0); else if (dto.getMinVoltage() > 999.0) namedParameters.put("minVoltage", 999.0); else namedParameters.put("minVoltage", dto.getMinVoltage()); namedParameters.put("minVoltageTime", dto.getMinVoltageTime()); namedParameters.put("pfSampleCount", dto.getPfSampleCount()); namedParameters.put("pfTotal", dto.getPfTotal()); for (String s : namedParameters.keySet()) { Object o = namedParameters.get(s); if (o instanceof Double) namedParameters.put(s, forceZero((double) o)); } return namedParameters; } private void updateCalendarKeys(HistoryMTUBillingCycle dto) { VirtualECC virtualECC = virtualECCDAO.findOneFromCache(dto.getKey().getVirtualECCId()); TimeZone timeZone = TimeZone.getTimeZone(virtualECC.getTimezone()); dto.setCalendarKey(CalendarUtils.keyFromMillis(dto.getStartEpoch() * 1000, timeZone)); dto.setDemandPeakCalendarKey(CalendarUtils.keyFromMillis(dto.getDemandPeakTime() * 1000, timeZone)); dto.setPeakVoltageCalendarKey(CalendarUtils.keyFromMillis(dto.getPeakVoltageTime() * 1000, timeZone)); dto.setMinVoltageCalendarKey(CalendarUtils.keyFromMillis(dto.getMinVoltageTime() * 1000, timeZone)); } public HistoryMTUBillingCycle findOne(HistoryMTUBillingCycleKey key) { try { HistoryMTUBillingCycle historyDay = hazelcastService.getHistoryMTUBillingCycleMap().get(key); if (historyDay == null) { LOGGER.debug("DATABASE HIT<<<<<<<<<<<<<<<<<<<<<<<<<<<"); String query = "select * from history_mtu_billingCycle where virtualECC_id=? and mtu_id=? " + " and billingCycleYear=? " + " and billingCycleMonth = ? "; historyDay = getJdbcTemplate().queryForObject(query, new Object[]{ key.getVirtualECCId(), key.getMtuId(), key.getBillingCycleYear(), key.getBillingCycleMonth() }, rowMapper); if (!PollingService.skipCache && PollingService.NUMBER_ENERGYPOST_THREADS != 0) hazelcastService.getHistoryMTUBillingCycleMap().put(key, historyDay); } return historyDay; } catch (EmptyResultDataAccessException ex) { LOGGER.debug("No Results returned"); return null; } } public void insert(HistoryMTUBillingCycle dto) { processBatch(); try { LOGGER.debug("RUNNING INSERT QUERY: {}", dto); if (!PollingService.skipCache) { updateCalendarKeys(dto); hazelcastService.getHistoryMTUBillingCycleMap().put(dto.getKey(), dto); } //getNamedParameterJdbcTemplate().update(INSERT, getNamedParameters(dto)); queueForBatch(dto.getKey(), HistoryKey.BatchState.INSERT, dto); } catch (Exception ex) { LOGGER.error("Error inserting record: {}", dto, ex); } } public void save(HistoryMTUBillingCycle dto) { processBatch(); try { LOGGER.debug("RUNNING SAVE QUERY: {}", dto); if (!PollingService.skipCache && PollingService.NUMBER_ENERGYPOST_THREADS != 0) { updateCalendarKeys(dto); hazelcastService.getHistoryMTUBillingCycleMap().put(dto.getKey(), dto); } //getNamedParameterJdbcTemplate().update(SAVE, getNamedParameters(dto)); queueForBatch(dto.getKey(), HistoryKey.BatchState.UPDATE, dto); } catch (Exception ex) { LOGGER.error("Error updating record: {}", dto, ex); } } public List<HistoryMTUBillingCycle> findByDateRange(long virtualECCId, long mtu_id, long startEpoch, long endEpoch) { Map<String, Object> namedParameters = new HashMap(24); namedParameters.put("virtualECCId", virtualECCId); namedParameters.put("mtuId", mtu_id); namedParameters.put("startEpoch", startEpoch); namedParameters.put("endEpoch", endEpoch); return getNamedParameterJdbcTemplate().query(FIND_BY_DATE_RANGE_QUERY, namedParameters, rowMapper); } static final int BATCH_SIZE = 20000; Cache<HistoryMTUBillingCycleKey,HistoryKey.BatchState> batchStateCache = CacheBuilder.newBuilder().concurrencyLevel(1).expireAfterAccess(30, TimeUnit.MINUTES).maximumSize(BATCH_SIZE).initialCapacity(BATCH_SIZE).build(); Cache<HistoryMTUBillingCycleKey, HistoryMTUBillingCycle> batch = CacheBuilder.newBuilder().concurrencyLevel(1).expireAfterAccess(30, TimeUnit.MINUTES).maximumSize(BATCH_SIZE).initialCapacity(BATCH_SIZE).build(); synchronized void queueForBatch(HistoryMTUBillingCycleKey key, HistoryKey.BatchState batchState, HistoryMTUBillingCycle dto){ if (batchStateCache.getIfPresent(key) == null){ batchStateCache.put(key, batchState); batch.put(key, dto); } else { batch.put(key, dto); } } long lastBatchPost = System.currentTimeMillis()/1000L; @Autowired ServerService serverService; public synchronized void processBatch(){ long secondsSinceLastPost = (System.currentTimeMillis()/1000L) - lastBatchPost; if (batch.size() != BATCH_SIZE && secondsSinceLastPost < (60*15) && serverService.isKeepRunning()) return; //Hold off o lastBatchPost = System.currentTimeMillis()/1000L; List<HistoryMTUBillingCycle> insertRecords = new ArrayList<>(BATCH_SIZE); List<HistoryMTUBillingCycle> updateRecords = new ArrayList<>(BATCH_SIZE); for (HistoryMTUBillingCycleKey key: batch.asMap().keySet()){ HistoryKey.BatchState state = batchStateCache.getIfPresent(key); if (state != null){ if (state == HistoryKey.BatchState.INSERT){ insertRecords.add(batch.getIfPresent(key)); } else { updateRecords.add(batch.getIfPresent(key)); } } else { LOGGER.warn("KEY NOT FOUND: {}", key); } } //Batch Insert LOGGER.info("BULK INSERT:{}", insertRecords.size()); batchUpdate(INSERT, insertRecords); //Batch Update LOGGER.info("BULK UPDATE:{}", updateRecords.size()); batchUpdate(SAVE,updateRecords); batchStateCache.invalidateAll(); batch.invalidateAll(); } private void batchUpdate(String query, List<HistoryMTUBillingCycle> batchList) { Map<String, ?>[] maps = new Map[batchList.size()]; for (int i=0; i < batchList.size(); i++){ maps[i] = getNamedParameters(batchList.get(i)); } try { getNamedParameterJdbcTemplate().batchUpdate(query, maps); } catch(DuplicateKeyException dex){ LOGGER.error("Duplicate Key on insert: {}", dex.getMessage()); } } public void deleteByVirtualEcc(Long virtualECCId, Long mtuId) { getJdbcTemplate().update("DELETE FROM history_mtu_billingCycle where virtualECC_id=? and mtu_id=? ", new Object[]{virtualECCId, mtuId}); } }
42.98806
347
0.624193
2d337272f072bb103fce7e28362bb61c7ef63127
202
package ru.otus.l0111.cache; public interface CacheEngine<K, V> { void put(CacheElement<K, V> element); V get(K key); int getHintCount(); int getMissCount(); void dispose(); }
13.466667
41
0.633663
6ec67e7da298fb76b5a6490540a8a38b8354d1ba
3,133
package gui; import java.awt.Color; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JTextArea; import javax.swing.SwingConstants; public class ResultPane { private JPanel resultPanel = null; private JLabel typeLabel = null; private JLabel definitionsLabel = null; private JLabel exampleLable = null; private JTextArea typeData = null; private JTextArea definitionData = null; private JTextArea exampleData = null; public ResultPane() { resultPanel = new JPanel(); typeLabel = new JLabel("Type"); definitionsLabel = new JLabel("Definition"); exampleLable = new JLabel("Example"); typeData = new JTextArea(2,25); definitionData = new JTextArea(2,25); exampleData = new JTextArea(2,25); } public JPanel getResultPane(String type,String definition,String example) { typeData.setText(type); typeData.setEditable(false); definitionData.setText(definition); definitionData.setEditable(false); exampleData.setText(example); exampleData.setEditable(false); Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 15); resultPanel.setLayout(new GridBagLayout()); GridBagConstraints gbcResult = new GridBagConstraints(); gbcResult.weighty=1; gbcResult.gridx=0; gbcResult.gridy=0; gbcResult.weightx=0.5; gbcResult.gridheight=2; typeLabel.setFont(font); resultPanel.add(typeLabel,gbcResult); definitionsLabel.setFont(font); gbcResult.gridy=3; resultPanel.add(definitionsLabel,gbcResult); exampleLable.setFont(font); gbcResult.gridy=6; resultPanel.add(exampleLable,gbcResult); gbcResult.gridx=1; gbcResult.gridy=0; gbcResult.fill=GridBagConstraints.VERTICAL; gbcResult.gridheight=8; resultPanel.add(new JSeparator(SwingConstants.VERTICAL),gbcResult); gbcResult.gridx=2; gbcResult.gridy=0; gbcResult.weightx=1; gbcResult.gridheight=2; typeData.setLineWrap(true); typeData.setWrapStyleWord(true); resultPanel.add(typeData,gbcResult); gbcResult.gridy=3; definitionData.setLineWrap(true); definitionData.setWrapStyleWord(true); resultPanel.add(definitionData,gbcResult); gbcResult.gridy=6; exampleData.setLineWrap(true); exampleData.setWrapStyleWord(true); GridBagConstraints spaceGbc = new GridBagConstraints(); spaceGbc.gridy=2; spaceGbc.gridx=0; spaceGbc.gridwidth=3; spaceGbc.fill=GridBagConstraints.HORIZONTAL; resultPanel.add(new JSeparator(SwingConstants.HORIZONTAL),spaceGbc); spaceGbc.gridy=5; resultPanel.add(new JSeparator(SwingConstants.HORIZONTAL),spaceGbc); resultPanel.add(exampleData,gbcResult); resultPanel.setBorder(BorderFactory.createLineBorder(Color.gray)); return resultPanel; } public void setType(String type) { typeData.setText(type); } public void setDefinition(String definition) { definitionData.setText(definition); } public void setExample(String example) { exampleData.setText(example); } }
30.715686
77
0.750399
53c9989e5fe3106fe93d669133367b8482be3ff2
3,149
package ai.pathfinding; import java.awt.Point; /** * An attempt at vectors in Java * Tailored a bit for what I actually need * Really more of a line with a single point * * @author Oliver Gratton * */ public class Vector { private double dx, dy; private Point centre; /** * Make a vector from two points * * @param source * @param dest */ public Vector(Point source, Point dest) { this.dx = dest.x - source.x; this.dy = dest.y - source.y; // normalise double sum = Math.abs(dx) + Math.abs(dy); dx = dx / sum; dy = dy / sum; this.centre = dest; } /** * Make a new vector directly * Automatically normalises * * @param x * @param y */ public Vector(double x, double y, Point centre) { double sum = Math.abs(x) + Math.abs(y); this.dx = x / sum; this.dy = y / sum; this.centre = centre; } public Point getCentre() { return centre; } public double getX() { return dx; } public double getY() { return dy; } /** * @param centre the point the new vector should be centred on * @return the normal of this vector */ public Vector normal(Point centre) { return new Vector(dy, -dx, centre); } /** * Is point p inside (i.e. to the left of) the vector? * This is used on normals by AIs following waypoints. * Being inside means that the waypoint is in the same * direction as the goal, but being outside means that * it should skip to the next waypoint as it has overshot * * @param p * @return */ public boolean pointInside(Point p) { boolean bool = true; // TODO I don't think we care if this.x or this.y are 0 but check if (this.dx < 0) { bool &= p.y >= getYfromX(p.x); } if (this.dx > 0) { bool &= p.y <= getYfromX(p.x); } if (this.dy < 0) { bool &= p.x <= getXfromY(p.y); } if (this.dy > 0) { bool &= p.x >= getXfromY(p.y); } return bool; } /** * Work out the y coord on the vector from the centre given x * * @param x * @return */ private double getYfromX(double x) { double xFromCentre = x - centre.getX(); double times = xFromCentre / this.dx; double y = centre.getY() + (this.dy * times); return y; } /** * Work out the x coord on the vector from the centre given y * * @param y * @return */ private double getXfromY(double y) { double yFromCentre = y - centre.getY(); double times = yFromCentre / this.dy; double x = centre.getX() + (this.dx * times); return x; } /** * Test if another vector is pointing in the same direction as this * * @param v another vector * @return true if yes */ public boolean equalDirection(Vector v) { // XXX check this value is sensible (i've no idea) double fuzziness = 0.4; return fuzzyEqual(v.dx,this.dx, fuzziness) && fuzzyEqual(v.dy, this.dy, fuzziness); } /** * Are two doubles almost equal * @param a * @param b * @return */ private boolean fuzzyEqual(double a, double b, double fuzziness) { return (Math.abs(a - b) <= fuzziness); } /** * Overwrites the Object toString method */ public String toString() { return "[ " + dx + " " + dy + " ]"; } }
18.202312
85
0.614481
d53917b1a3597c97da32748fca3a02a5f6c9a88a
5,379
package org.embulk.parser.poi_excel.visitor; import java.text.MessageFormat; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.util.CellReference; import org.embulk.parser.poi_excel.PoiExcelColumnValueType; import org.embulk.parser.poi_excel.bean.PoiExcelColumnBean; import org.embulk.parser.poi_excel.visitor.embulk.CellVisitor; import org.embulk.spi.Column; import org.embulk.spi.ColumnVisitor; import org.embulk.spi.Exec; import org.embulk.spi.PageBuilder; import org.slf4j.Logger; public class PoiExcelColumnVisitor implements ColumnVisitor { private final Logger log = Exec.getLogger(getClass()); protected final PoiExcelVisitorValue visitorValue; protected final PageBuilder pageBuilder; protected final PoiExcelVisitorFactory factory; protected Row currentRow; public PoiExcelColumnVisitor(PoiExcelVisitorValue visitorValue) { this.visitorValue = visitorValue; this.pageBuilder = visitorValue.getPageBuilder(); this.factory = visitorValue.getVisitorFactory(); } public void setRow(Row row) { this.currentRow = row; } @Override public final void booleanColumn(Column column) { visitCell0(column, factory.getBooleanCellVisitor()); } @Override public final void longColumn(Column column) { visitCell0(column, factory.getLongCellVisitor()); } @Override public final void doubleColumn(Column column) { visitCell0(column, factory.getDoubleCellVisitor()); } @Override public final void stringColumn(Column column) { visitCell0(column, factory.getStringCellVisitor()); } @Override public final void timestampColumn(Column column) { visitCell0(column, factory.getTimestampCellVisitor()); } protected final void visitCell0(Column column, CellVisitor visitor) { if (log.isTraceEnabled()) { log.trace("{} start", column); } try { visitCell(column, visitor); } catch (Exception e) { String sheetName = visitorValue.getSheet().getSheetName(); String ref = new CellReference(currentRow.getRowNum(), visitorValue.getColumnBean(column).getColumnIndex()) .formatAsString(); throw new RuntimeException(MessageFormat.format("error at {0} cell={1}!{2}. {3}", column, sheetName, ref, e.getMessage()), e); } if (log.isTraceEnabled()) { log.trace("{} end", column); } } protected void visitCell(Column column, CellVisitor visitor) { PoiExcelColumnBean bean = visitorValue.getColumnBean(column); PoiExcelColumnValueType valueType = bean.getValueType(); switch (valueType) { case SHEET_NAME: visitor.visitSheetName(column); return; case ROW_NUMBER: visitor.visitRowNumber(column, currentRow.getRowNum() + 1); return; case COLUMN_NUMBER: visitor.visitColumnNumber(column, bean.getColumnIndex() + 1); return; case CONSTANT: visitCellConstant(column, bean.getValueTypeSuffix(), visitor); return; default: break; } assert valueType.useCell(); Cell cell = currentRow.getCell(bean.getColumnIndex()); if (cell == null) { visitCellNull(column); return; } switch (valueType) { case CELL_VALUE: case CELL_FORMULA: visitCellValue(bean, cell, visitor); return; case CELL_STYLE: visitCellStyle(bean, cell, visitor); return; case CELL_FONT: visitCellFont(bean, cell, visitor); return; case CELL_COMMENT: visitCellComment(bean, cell, visitor); return; case CELL_TYPE: visitCellType(bean, cell, cell.getCellType(), visitor); return; case CELL_CACHED_TYPE: if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { visitCellType(bean, cell, cell.getCachedFormulaResultType(), visitor); } else { visitCellType(bean, cell, cell.getCellType(), visitor); } return; default: throw new UnsupportedOperationException(MessageFormat.format("unsupported value_type={0}", valueType)); } } protected void visitCellConstant(Column column, String value, CellVisitor visitor) { if (value == null) { pageBuilder.setNull(column); return; } visitor.visitCellValueString(column, null, value); } protected void visitCellNull(Column column) { pageBuilder.setNull(column); } private void visitCellValue(PoiExcelColumnBean bean, Cell cell, CellVisitor visitor) { PoiExcelCellValueVisitor delegator = factory.getPoiExcelCellValueVisitor(); delegator.visitCellValue(bean, cell, visitor); } private void visitCellStyle(PoiExcelColumnBean bean, Cell cell, CellVisitor visitor) { PoiExcelCellStyleVisitor delegator = factory.getPoiExcelCellStyleVisitor(); delegator.visit(bean, cell, visitor); } private void visitCellFont(PoiExcelColumnBean bean, Cell cell, CellVisitor visitor) { PoiExcelCellFontVisitor delegator = factory.getPoiExcelCellFontVisitor(); delegator.visit(bean, cell, visitor); } private void visitCellComment(PoiExcelColumnBean bean, Cell cell, CellVisitor visitor) { PoiExcelCellCommentVisitor delegator = factory.getPoiExcelCellCommentVisitor(); delegator.visit(bean, cell, visitor); } private void visitCellType(PoiExcelColumnBean bean, Cell cell, int cellType, CellVisitor visitor) { PoiExcelCellTypeVisitor delegator = factory.getPoiExcelCellTypeVisitor(); delegator.visit(bean, cell, cellType, visitor); } }
31.273256
111
0.733594
3920e272e8363d4d1134edbbd76e6982bf984c08
2,306
/* * Tencent is pleased to support the open source community by making QMUI_Android available. * * Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT 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://opensource.org/licenses/MIT * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.qmuiteam.qmui.type.parser; import com.qmuiteam.qmui.type.TypeModel; import com.qmuiteam.qmui.type.element.CharOrPhraseElement; import com.qmuiteam.qmui.type.element.Element; import com.qmuiteam.qmui.type.element.NextParagraphElement; import java.util.HashMap; public class PlainTextParser implements TextParser { @Override public TypeModel parse(CharSequence text) { if (text.length() == 0) { return null; } HashMap<Integer, Element> map = new HashMap<>(text.length()); Element first = null, last = null, tmp; int index = 0; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (c == '\n') { tmp = new NextParagraphElement(c, null, index, i); } else if (c == '\r') { if (i + 1 < text.length() && text.charAt(i + 1) == '\n') { tmp = new NextParagraphElement('\u0000', "\r\n", index, i); i++; } else { tmp = new NextParagraphElement(c, null, index, i); } } else { tmp = new CharOrPhraseElement(c, index, i); } ParserHelper.handleWordPart(c, last, tmp); index++; if (first == null) { first = tmp; last = tmp; } else { last.setNext(tmp); last = tmp; } map.put(tmp.getIndex(), tmp); } return new TypeModel(text, map, first, last, null); } }
35.476923
103
0.579792
f42c042196defab9e3234270dcabd1967d7655a0
22,568
/* * Copyright 2004-2019 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.gridgain.internal.h2.test.jdbc; import java.io.ByteArrayInputStream; import java.io.Reader; import java.io.StringReader; import java.math.BigDecimal; import java.net.URL; import java.nio.charset.StandardCharsets; import java.sql.Array; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.Ref; import java.sql.ResultSet; import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLXML; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import java.util.Collections; import org.gridgain.internal.h2.api.ErrorCode; import org.gridgain.internal.h2.test.TestBase; import org.gridgain.internal.h2.test.TestDb; import org.gridgain.internal.h2.tools.SimpleResultSet; import org.gridgain.internal.h2.util.IOUtils; import org.gridgain.internal.h2.util.JdbcUtils; import org.gridgain.internal.h2.util.LocalDateTimeUtils; import org.gridgain.internal.h2.util.Utils; /** * Tests for the CallableStatement class. */ public class TestCallableStatement extends TestDb { /** * Run just this test. * * @param a ignored */ public static void main(String... a) throws Exception { TestBase.createCaller().init().test(); } @Override public void test() throws Exception { deleteDb("callableStatement"); Connection conn = getConnection("callableStatement"); testOutParameter(conn); testUnsupportedOperations(conn); testGetters(conn); testCallWithResultSet(conn); testPreparedStatement(conn); testCallWithResult(conn); testPrepare(conn); testClassLoader(conn); testArrayArgument(conn); testArrayReturnValue(conn); conn.close(); deleteDb("callableStatement"); } private void testOutParameter(Connection conn) throws SQLException { conn.createStatement().execute( "create table test(id identity) as select null"); for (int i = 1; i < 20; i++) { CallableStatement cs = conn.prepareCall("{ ? = call IDENTITY()}"); cs.registerOutParameter(1, Types.BIGINT); cs.execute(); long id = cs.getLong(1); assertEquals(1, id); cs.close(); } conn.createStatement().execute( "drop table test"); } private void testUnsupportedOperations(Connection conn) throws SQLException { CallableStatement call; call = conn.prepareCall("select 10 as a"); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, call). getURL(1); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, call). getObject(1, Collections.<String, Class<?>>emptyMap()); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, call). getRef(1); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, call). getRowId(1); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, call). getURL("a"); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, call). getObject("a", Collections.<String, Class<?>>emptyMap()); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, call). getRef("a"); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, call). getRowId("a"); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, call). setURL(1, (URL) null); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, call). setRef(1, (Ref) null); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, call). setRowId(1, (RowId) null); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, call). setURL("a", (URL) null); assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, call). setRowId("a", (RowId) null); } private void testCallWithResultSet(Connection conn) throws SQLException { CallableStatement call; ResultSet rs; call = conn.prepareCall("select 10 as a"); call.execute(); rs = call.getResultSet(); rs.next(); assertEquals(10, rs.getInt(1)); } private void testPreparedStatement(Connection conn) throws SQLException { // using a callable statement like a prepared statement CallableStatement call; call = conn.prepareCall("create table test(id int)"); call.executeUpdate(); call = conn.prepareCall("insert into test values(1), (2)"); assertEquals(2, call.executeUpdate()); call = conn.prepareCall("drop table test"); call.executeUpdate(); } private void testGetters(Connection conn) throws SQLException { CallableStatement call; call = conn.prepareCall("{?=call ?}"); call.setLong(2, 1); call.registerOutParameter(1, Types.BIGINT); call.execute(); assertEquals(1, call.getLong(1)); assertEquals(1, call.getByte(1)); assertEquals(1, ((Long) call.getObject(1)).longValue()); assertEquals(1, call.getObject(1, Long.class).longValue()); assertFalse(call.wasNull()); call.setFloat(2, 1.1f); call.registerOutParameter(1, Types.REAL); call.execute(); assertEquals(1.1f, call.getFloat(1)); call.setDouble(2, Math.PI); call.registerOutParameter(1, Types.DOUBLE); call.execute(); assertEquals(Math.PI, call.getDouble(1)); call.setBytes(2, new byte[11]); call.registerOutParameter(1, Types.BINARY); call.execute(); assertEquals(11, call.getBytes(1).length); assertEquals(11, call.getBlob(1).length()); call.setDate(2, java.sql.Date.valueOf("2000-01-01")); call.registerOutParameter(1, Types.DATE); call.execute(); assertEquals("2000-01-01", call.getDate(1).toString()); if (LocalDateTimeUtils.isJava8DateApiPresent()) { assertEquals("2000-01-01", call.getObject(1, LocalDateTimeUtils.LOCAL_DATE).toString()); } call.setTime(2, java.sql.Time.valueOf("01:02:03")); call.registerOutParameter(1, Types.TIME); call.execute(); assertEquals("01:02:03", call.getTime(1).toString()); if (LocalDateTimeUtils.isJava8DateApiPresent()) { assertEquals("01:02:03", call.getObject(1, LocalDateTimeUtils.LOCAL_TIME).toString()); } call.setTimestamp(2, java.sql.Timestamp.valueOf( "2001-02-03 04:05:06.789")); call.registerOutParameter(1, Types.TIMESTAMP); call.execute(); assertEquals("2001-02-03 04:05:06.789", call.getTimestamp(1).toString()); if (LocalDateTimeUtils.isJava8DateApiPresent()) { assertEquals("2001-02-03T04:05:06.789", call.getObject(1, LocalDateTimeUtils.LOCAL_DATE_TIME).toString()); } call.setBoolean(2, true); call.registerOutParameter(1, Types.BIT); call.execute(); assertEquals(true, call.getBoolean(1)); call.setShort(2, (short) 123); call.registerOutParameter(1, Types.SMALLINT); call.execute(); assertEquals(123, call.getShort(1)); call.setBigDecimal(2, BigDecimal.TEN); call.registerOutParameter(1, Types.DECIMAL); call.execute(); assertEquals("10", call.getBigDecimal(1).toString()); } private void testCallWithResult(Connection conn) throws SQLException { CallableStatement call; for (String s : new String[]{"{?= call abs(?)}", " { ? = call abs(?)}", " {? = call abs(?)}"}) { call = conn.prepareCall(s); call.setInt(2, -3); call.registerOutParameter(1, Types.INTEGER); call.execute(); assertEquals(3, call.getInt(1)); call.executeUpdate(); assertEquals(3, call.getInt(1)); } } private void testPrepare(Connection conn) throws Exception { Statement stat = conn.createStatement(); CallableStatement call; ResultSet rs; stat.execute("CREATE TABLE TEST(ID INT, NAME VARCHAR)"); call = conn.prepareCall("INSERT INTO TEST VALUES(?, ?)"); call.setInt(1, 1); call.setString(2, "Hello"); call.execute(); call = conn.prepareCall("SELECT * FROM TEST", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); rs = call.executeQuery(); rs.next(); assertEquals(1, rs.getInt(1)); assertEquals("Hello", rs.getString(2)); assertFalse(rs.next()); call = conn.prepareCall("SELECT * FROM TEST", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); rs = call.executeQuery(); rs.next(); assertEquals(1, rs.getInt(1)); assertEquals("Hello", rs.getString(2)); assertFalse(rs.next()); stat.execute("CREATE ALIAS testCall FOR \"" + getClass().getName() + ".testCall\""); call = conn.prepareCall("{CALL testCall(?, ?, ?, ?)}"); call.setInt("A", 50); call.setString("B", "abc"); long t = System.currentTimeMillis(); call.setTimestamp("C", new Timestamp(t)); call.setTimestamp("D", Timestamp.valueOf("2001-02-03 10:20:30.0")); call.registerOutParameter(1, Types.INTEGER); call.registerOutParameter("B", Types.VARCHAR); call.executeUpdate(); try { call.getTimestamp("C"); fail("not registered out parameter accessible"); } catch (SQLException e) { // expected exception } call.registerOutParameter(3, Types.TIMESTAMP); call.registerOutParameter(4, Types.TIMESTAMP); call.executeUpdate(); assertEquals(t + 1, call.getTimestamp(3).getTime()); assertEquals(t + 1, call.getTimestamp("C").getTime()); assertEquals("2001-02-03 10:20:30.0", call.getTimestamp(4).toString()); assertEquals("2001-02-03 10:20:30.0", call.getTimestamp("D").toString()); if (LocalDateTimeUtils.isJava8DateApiPresent()) { assertEquals("2001-02-03T10:20:30", call.getObject(4, LocalDateTimeUtils.LOCAL_DATE_TIME).toString()); assertEquals("2001-02-03T10:20:30", call.getObject("D", LocalDateTimeUtils.LOCAL_DATE_TIME).toString()); } assertEquals("10:20:30", call.getTime(4).toString()); assertEquals("10:20:30", call.getTime("D").toString()); if (LocalDateTimeUtils.isJava8DateApiPresent()) { assertEquals("10:20:30", call.getObject(4, LocalDateTimeUtils.LOCAL_TIME).toString()); assertEquals("10:20:30", call.getObject("D", LocalDateTimeUtils.LOCAL_TIME).toString()); } assertEquals("2001-02-03", call.getDate(4).toString()); assertEquals("2001-02-03", call.getDate("D").toString()); if (LocalDateTimeUtils.isJava8DateApiPresent()) { assertEquals("2001-02-03", call.getObject(4, LocalDateTimeUtils.LOCAL_DATE).toString()); assertEquals("2001-02-03", call.getObject("D", LocalDateTimeUtils.LOCAL_DATE).toString()); } assertEquals(100, call.getInt(1)); assertEquals(100, call.getInt("A")); assertEquals(100, call.getLong(1)); assertEquals(100, call.getLong("A")); assertEquals("100", call.getBigDecimal(1).toString()); assertEquals("100", call.getBigDecimal("A").toString()); assertEquals(100, call.getFloat(1)); assertEquals(100, call.getFloat("A")); assertEquals(100, call.getDouble(1)); assertEquals(100, call.getDouble("A")); assertEquals(100, call.getByte(1)); assertEquals(100, call.getByte("A")); assertEquals(100, call.getShort(1)); assertEquals(100, call.getShort("A")); assertTrue(call.getBoolean(1)); assertTrue(call.getBoolean("A")); assertEquals("ABC", call.getString(2)); Reader r = call.getCharacterStream(2); assertEquals("ABC", IOUtils.readStringAndClose(r, -1)); r = call.getNCharacterStream(2); assertEquals("ABC", IOUtils.readStringAndClose(r, -1)); assertEquals("ABC", call.getString("B")); assertEquals("ABC", call.getNString(2)); assertEquals("ABC", call.getNString("B")); assertEquals("ABC", call.getClob(2).getSubString(1, 3)); assertEquals("ABC", call.getClob("B").getSubString(1, 3)); assertEquals("ABC", call.getNClob(2).getSubString(1, 3)); assertEquals("ABC", call.getNClob("B").getSubString(1, 3)); assertEquals("ABC", call.getSQLXML(2).getString()); assertEquals("ABC", call.getSQLXML("B").getString()); try { call.getString(100); fail("incorrect parameter index value"); } catch (SQLException e) { // expected exception } try { call.getString(0); fail("incorrect parameter index value"); } catch (SQLException e) { // expected exception } try { call.getBoolean("X"); fail("incorrect parameter name value"); } catch (SQLException e) { // expected exception } call.setCharacterStream("B", new StringReader("xyz")); call.executeUpdate(); assertEquals("XYZ", call.getString("B")); call.setCharacterStream("B", new StringReader("xyz-"), 3); call.executeUpdate(); assertEquals("XYZ", call.getString("B")); call.setCharacterStream("B", new StringReader("xyz-"), 3L); call.executeUpdate(); assertEquals("XYZ", call.getString("B")); call.setAsciiStream("B", new ByteArrayInputStream("xyz".getBytes(StandardCharsets.UTF_8))); call.executeUpdate(); assertEquals("XYZ", call.getString("B")); call.setAsciiStream("B", new ByteArrayInputStream("xyz-".getBytes(StandardCharsets.UTF_8)), 3); call.executeUpdate(); assertEquals("XYZ", call.getString("B")); call.setAsciiStream("B", new ByteArrayInputStream("xyz-".getBytes(StandardCharsets.UTF_8)), 3L); call.executeUpdate(); assertEquals("XYZ", call.getString("B")); call.setClob("B", new StringReader("xyz")); call.executeUpdate(); assertEquals("XYZ", call.getString("B")); call.setClob("B", new StringReader("xyz-"), 3); call.executeUpdate(); assertEquals("XYZ", call.getString("B")); call.setNClob("B", new StringReader("xyz")); call.executeUpdate(); assertEquals("XYZ", call.getString("B")); call.setNClob("B", new StringReader("xyz-"), 3); call.executeUpdate(); assertEquals("XYZ", call.getString("B")); call.setString("B", "xyz"); call.executeUpdate(); assertEquals("XYZ", call.getString("B")); call.setNString("B", "xyz"); call.executeUpdate(); assertEquals("XYZ", call.getString("B")); SQLXML xml = conn.createSQLXML(); xml.setString("<x>xyz</x>"); call.setSQLXML("B", xml); call.executeUpdate(); assertEquals("<X>XYZ</X>", call.getString("B")); // test for exceptions after closing call.close(); assertThrows(ErrorCode.OBJECT_CLOSED, call). executeUpdate(); assertThrows(ErrorCode.OBJECT_CLOSED, call). registerOutParameter(1, Types.INTEGER); assertThrows(ErrorCode.OBJECT_CLOSED, call). getString("X"); } private void testClassLoader(Connection conn) throws SQLException { Utils.ClassFactory myFactory = new TestClassFactory(); JdbcUtils.addClassFactory(myFactory); try { Statement stat = conn.createStatement(); stat.execute("CREATE ALIAS T_CLASSLOADER FOR \"TestClassFactory.testClassF\""); ResultSet rs = stat.executeQuery("SELECT T_CLASSLOADER(true)"); assertTrue(rs.next()); assertEquals(false, rs.getBoolean(1)); } finally { JdbcUtils.removeClassFactory(myFactory); } } private void testArrayArgument(Connection connection) throws SQLException { Array array = connection.createArrayOf("Int", new Object[] {0, 1, 2}); try (Statement statement = connection.createStatement()) { statement.execute("CREATE ALIAS getArrayLength FOR \"" + getClass().getName() + ".getArrayLength\""); // test setArray try (CallableStatement callableStatement = connection .prepareCall("{call getArrayLength(?)}")) { callableStatement.setArray(1, array); assertTrue(callableStatement.execute()); try (ResultSet resultSet = callableStatement.getResultSet()) { assertTrue(resultSet.next()); assertEquals(3, resultSet.getInt(1)); assertFalse(resultSet.next()); } } // test setObject try (CallableStatement callableStatement = connection .prepareCall("{call getArrayLength(?)}")) { callableStatement.setObject(1, array); assertTrue(callableStatement.execute()); try (ResultSet resultSet = callableStatement.getResultSet()) { assertTrue(resultSet.next()); assertEquals(3, resultSet.getInt(1)); assertFalse(resultSet.next()); } } } finally { array.free(); } } private void testArrayReturnValue(Connection connection) throws SQLException { Object[][] arraysToTest = new Object[][] { new Object[] {0, 1, 2}, new Object[] {0, "1", 2}, new Object[] {0, null, 2}, new Object[] {0, new Object[] {"s", 1}, new Object[] {null, 1L}}, }; try (Statement statement = connection.createStatement()) { statement.execute("CREATE ALIAS arrayIdentiy FOR \"" + getClass().getName() + ".arrayIdentiy\""); for (Object[] arrayToTest : arraysToTest) { Array sqlInputArray = connection.createArrayOf("ignored", arrayToTest); try { try (CallableStatement callableStatement = connection .prepareCall("{call arrayIdentiy(?)}")) { callableStatement.setArray(1, sqlInputArray); assertTrue(callableStatement.execute()); try (ResultSet resultSet = callableStatement.getResultSet()) { assertTrue(resultSet.next()); // test getArray() Array sqlReturnArray = resultSet.getArray(1); try { assertEquals( (Object[]) sqlInputArray.getArray(), (Object[]) sqlReturnArray.getArray()); } finally { sqlReturnArray.free(); } // test getObject(Array.class) sqlReturnArray = resultSet.getObject(1, Array.class); try { assertEquals( (Object[]) sqlInputArray.getArray(), (Object[]) sqlReturnArray.getArray()); } finally { sqlReturnArray.free(); } assertFalse(resultSet.next()); } } } finally { sqlInputArray.free(); } } } } /** * Class factory unit test * @param b boolean value * @return !b */ public static Boolean testClassF(Boolean b) { return !b; } /** * This method is called via reflection from the database. * * @param array the array * @return the length of the array */ public static int getArrayLength(Object[] array) { return array == null ? 0 : array.length; } /** * This method is called via reflection from the database. * * @param array the array * @return the array */ public static Object[] arrayIdentiy(Object[] array) { return array; } /** * This method is called via reflection from the database. * * @param conn the connection * @param a the value a * @param b the value b * @param c the value c * @param d the value d * @return a result set */ public static ResultSet testCall(Connection conn, int a, String b, Timestamp c, Timestamp d) throws SQLException { SimpleResultSet rs = new SimpleResultSet(); rs.addColumn("A", Types.INTEGER, 0, 0); rs.addColumn("B", Types.VARCHAR, 0, 0); rs.addColumn("C", Types.TIMESTAMP, 0, 0); rs.addColumn("D", Types.TIMESTAMP, 0, 0); if ("jdbc:columnlist:connection".equals(conn.getMetaData().getURL())) { return rs; } rs.addRow(a * 2, b.toUpperCase(), new Timestamp(c.getTime() + 1), d); return rs; } /** * A class factory used for testing. */ static class TestClassFactory implements Utils.ClassFactory { @Override public boolean match(String name) { return name.equals("TestClassFactory"); } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return TestCallableStatement.class; } } }
38.643836
91
0.575461
de85af5a2b9696e358000385a29eb9469287b7d8
1,941
package me.mmarz11.aod.handlers; import me.mmarz11.aod.handlers.map.BuildBreakHandler; import me.mmarz11.aod.handlers.map.MapHandler; import me.mmarz11.aod.handlers.player.ArrowHandler; import me.mmarz11.aod.handlers.player.BrainHandler; import me.mmarz11.aod.handlers.player.HungerHandler; import me.mmarz11.aod.handlers.player.LoginHandler; import me.mmarz11.aod.handlers.player.PermissionHandler; import me.mmarz11.aod.handlers.player.PlayerTypeHandler; import me.mmarz11.aod.handlers.player.PortalHandler; import me.mmarz11.aod.handlers.player.RespawnHandler; import me.mmarz11.aod.handlers.player.StatHandler; import me.mmarz11.aod.handlers.player.TeamkillHandler; import me.mmarz11.aod.handlers.round.KitHandler; import me.mmarz11.aod.handlers.round.ScoreboardHandler; import me.mmarz11.aod.handlers.round.TimerHandler; public class Handlers { public ScoreboardHandler scoreboardHandler = new ScoreboardHandler(); public TimerHandler timerHandler = new TimerHandler(); public PlayerTypeHandler playerTypeHandler = new PlayerTypeHandler(); public ConfigHandler configHandler = new ConfigHandler(); public MapHandler mapHandler = new MapHandler(); public TeamkillHandler teamkillHandler = new TeamkillHandler(); public LoginHandler loginHandler = new LoginHandler(); public PortalHandler portalHandler = new PortalHandler(); public KitHandler kitHandler = new KitHandler(); public HungerHandler hungerHandler = new HungerHandler(); public BuildBreakHandler buildBreakHandler = new BuildBreakHandler(); public RespawnHandler respawnHandler = new RespawnHandler(); public StatHandler statHandler = new StatHandler(); public PermissionHandler permissionHandler = new PermissionHandler(); public ArrowHandler arrowHandler = new ArrowHandler(); public BrainHandler brainHandler = new BrainHandler(); public void init() { configHandler.init(); brainHandler.init(); mapHandler.init(); scoreboardHandler.init(); } }
44.113636
70
0.819165
781f3a9781a699a829d6a77924aaf6de2e85e6ba
1,015
package Hexel.generation.heightMap; import Hexel.generation.plate.PlateSumChunks; import Hexel.generation.plate.PlateSum; public class HeightMap { private PlateSumChunks smallPSCs; private PlateSumChunks bigPSCs; private static final int SCALE = 2; public HeightMap(){ smallPSCs = new PlateSumChunks(); bigPSCs = new PlateSumChunks(); } public int getHeight(int px, int py){ PlateSum small = smallPSCs.getPlateSum(px, py); PlateSum big = bigPSCs.getPlateSum(px/SCALE, py/SCALE); double h = 0; if (big.baseHeight < 0){ h = big.baseHeight; if (h + big.heightVar < 0) h += big.heightVar; } else { h = small.additions + Math.max(small.baseHeight, 0) + small.heightVar; } return (int)h; } public double getResistanceToChange(int px, int py){ PlateSum small = smallPSCs.getPlateSum(px, py); return small.resistanceToChange; } }
26.025641
82
0.615764
72ef945d0ea155e78862d5576633b56adf35811e
13,971
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.streaming.api.datastream; import org.apache.flink.api.common.functions.FoldFunction; import org.apache.flink.api.common.functions.ReduceFunction; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.java.Utils; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.api.java.typeutils.TypeExtractor; import org.apache.flink.streaming.api.functions.aggregation.AggregationFunction; import org.apache.flink.streaming.api.functions.aggregation.AggregationFunction.AggregationType; import org.apache.flink.streaming.api.functions.aggregation.ComparableAggregator; import org.apache.flink.streaming.api.functions.aggregation.SumAggregator; import org.apache.flink.streaming.api.operators.StreamGroupedFold; import org.apache.flink.streaming.api.operators.StreamGroupedReduce; /** * A GroupedDataStream represents a {@link DataStream} which has been * partitioned by the given {@link KeySelector}. Operators like {@link #reduce}, * {@link #fold} etc. can be applied on the {@link GroupedDataStream} to * get additional functionality by the grouping. * * @param <OUT> * The output type of the {@link GroupedDataStream}. */ public class GroupedDataStream<OUT> extends KeyedDataStream<OUT> { /** * Creates a new {@link GroupedDataStream}, group inclusion is determined using * a {@link KeySelector} on the elements of the {@link DataStream}. * * @param dataStream Base stream of data * @param keySelector Function for determining group inclusion */ public GroupedDataStream(DataStream<OUT> dataStream, KeySelector<OUT, ?> keySelector) { super(dataStream, keySelector); } /** * Applies a reduce transformation on the grouped data stream grouped on by * the given key position. The {@link ReduceFunction} will receive input * values based on the key value. Only input values with the same key will * go to the same reducer. * * @param reducer * The {@link ReduceFunction} that will be called for every * element of the input values with the same key. * @return The transformed DataStream. */ public SingleOutputStreamOperator<OUT, ?> reduce(ReduceFunction<OUT> reducer) { return transform("Grouped Reduce", getType(), new StreamGroupedReduce<OUT>( clean(reducer), keySelector)); } /** * Applies a fold transformation on the grouped data stream grouped on by * the given key position. The {@link FoldFunction} will receive input * values based on the key value. Only input values with the same key will * go to the same folder. * * @param folder * The {@link FoldFunction} that will be called for every element * of the input values with the same key. * @param initialValue * The initialValue passed to the folders for each key. * @return The transformed DataStream. */ public <R> SingleOutputStreamOperator<R, ?> fold(R initialValue, FoldFunction<OUT, R> folder) { TypeInformation<R> outType = TypeExtractor.getFoldReturnTypes(clean(folder), getType(), Utils.getCallLocationName(), true); return transform("Grouped Fold", outType, new StreamGroupedFold<OUT, R>(clean(folder), keySelector, initialValue, outType)); } /** * Applies an aggregation that gives a rolling sum of the data stream at the * given position grouped by the given key. An independent aggregate is kept * per key. * * @param positionToSum * The position in the data point to sum * @return The transformed DataStream. */ public SingleOutputStreamOperator<OUT, ?> sum(int positionToSum) { return aggregate(new SumAggregator<OUT>(positionToSum, getType(), getExecutionConfig())); } /** * Applies an aggregation that that gives the current sum of the pojo data * stream at the given field expressionby the given key. An independent * aggregate is kept per key. A field expression is either the name of a * public field or a getter method with parentheses of the * {@link DataStream}S underlying type. A dot can be used to drill down into * objects, as in {@code "field1.getInnerField2()" }. * * @param field * The field expression based on which the aggregation will be * applied. * @return The transformed DataStream. */ public SingleOutputStreamOperator<OUT, ?> sum(String field) { return aggregate(new SumAggregator<OUT>(field, getType(), getExecutionConfig())); } /** * Applies an aggregation that that gives the current minimum of the data * stream at the given position by the given key. An independent aggregate * is kept per key. * * @param positionToMin * The position in the data point to minimize * @return The transformed DataStream. */ public SingleOutputStreamOperator<OUT, ?> min(int positionToMin) { return aggregate(new ComparableAggregator<OUT>(positionToMin, getType(), AggregationType.MIN, getExecutionConfig())); } /** * Applies an aggregation that that gives the current minimum of the pojo * data stream at the given field expression by the given key. An * independent aggregate is kept per key. A field expression is either the * name of a public field or a getter method with parentheses of the * {@link DataStream}S underlying type. A dot can be used to drill down into * objects, as in {@code "field1.getInnerField2()" }. * * @param field * The field expression based on which the aggregation will be * applied. * @return The transformed DataStream. */ public SingleOutputStreamOperator<OUT, ?> min(String field) { return aggregate(new ComparableAggregator<OUT>(field, getType(), AggregationType.MIN, false, getExecutionConfig())); } /** * Applies an aggregation that gives the current maximum of the data stream * at the given position by the given key. An independent aggregate is kept * per key. * * @param positionToMax * The position in the data point to maximize * @return The transformed DataStream. */ public SingleOutputStreamOperator<OUT, ?> max(int positionToMax) { return aggregate(new ComparableAggregator<OUT>(positionToMax, getType(), AggregationType.MAX, getExecutionConfig())); } /** * Applies an aggregation that that gives the current maximum of the pojo * data stream at the given field expression by the given key. An * independent aggregate is kept per key. A field expression is either the * name of a public field or a getter method with parentheses of the * {@link DataStream}S underlying type. A dot can be used to drill down into * objects, as in {@code "field1.getInnerField2()" }. * * @param field * The field expression based on which the aggregation will be * applied. * @return The transformed DataStream. */ public SingleOutputStreamOperator<OUT, ?> max(String field) { return aggregate(new ComparableAggregator<OUT>(field, getType(), AggregationType.MAX, false, getExecutionConfig())); } /** * Applies an aggregation that that gives the current minimum element of the * pojo data stream by the given field expression by the given key. An * independent aggregate is kept per key. A field expression is either the * name of a public field or a getter method with parentheses of the * {@link DataStream}S underlying type. A dot can be used to drill down into * objects, as in {@code "field1.getInnerField2()" }. * * @param field * The field expression based on which the aggregation will be * applied. * @param first * If True then in case of field equality the first object will * be returned * @return The transformed DataStream. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public SingleOutputStreamOperator<OUT, ?> minBy(String field, boolean first) { return aggregate(new ComparableAggregator(field, getType(), AggregationType.MINBY, first, getExecutionConfig())); } /** * Applies an aggregation that that gives the current maximum element of the * pojo data stream by the given field expression by the given key. An * independent aggregate is kept per key. A field expression is either the * name of a public field or a getter method with parentheses of the * {@link DataStream}S underlying type. A dot can be used to drill down into * objects, as in {@code "field1.getInnerField2()" }. * * @param field * The field expression based on which the aggregation will be * applied. * @param first * If True then in case of field equality the first object will * be returned * @return The transformed DataStream. */ public SingleOutputStreamOperator<OUT, ?> maxBy(String field, boolean first) { return aggregate(new ComparableAggregator<OUT>(field, getType(), AggregationType.MAXBY, first, getExecutionConfig())); } /** * Applies an aggregation that that gives the current element with the * minimum value at the given position by the given key. An independent * aggregate is kept per key. If more elements have the minimum value at the * given position, the operator returns the first one by default. * * @param positionToMinBy * The position in the data point to minimize * @return The transformed DataStream. */ public SingleOutputStreamOperator<OUT, ?> minBy(int positionToMinBy) { return this.minBy(positionToMinBy, true); } /** * Applies an aggregation that that gives the current element with the * minimum value at the given position by the given key. An independent * aggregate is kept per key. If more elements have the minimum value at the * given position, the operator returns the first one by default. * * @param positionToMinBy * The position in the data point to minimize * @return The transformed DataStream. */ public SingleOutputStreamOperator<OUT, ?> minBy(String positionToMinBy) { return this.minBy(positionToMinBy, true); } /** * Applies an aggregation that that gives the current element with the * minimum value at the given position by the given key. An independent * aggregate is kept per key. If more elements have the minimum value at the * given position, the operator returns either the first or last one, * depending on the parameter set. * * @param positionToMinBy * The position in the data point to minimize * @param first * If true, then the operator return the first element with the * minimal value, otherwise returns the last * @return The transformed DataStream. */ public SingleOutputStreamOperator<OUT, ?> minBy(int positionToMinBy, boolean first) { return aggregate(new ComparableAggregator<OUT>(positionToMinBy, getType(), AggregationType.MINBY, first, getExecutionConfig())); } /** * Applies an aggregation that that gives the current element with the * maximum value at the given position by the given key. An independent * aggregate is kept per key. If more elements have the maximum value at the * given position, the operator returns the first one by default. * * @param positionToMaxBy * The position in the data point to maximize * @return The transformed DataStream. */ public SingleOutputStreamOperator<OUT, ?> maxBy(int positionToMaxBy) { return this.maxBy(positionToMaxBy, true); } /** * Applies an aggregation that that gives the current element with the * maximum value at the given position by the given key. An independent * aggregate is kept per key. If more elements have the maximum value at the * given position, the operator returns the first one by default. * * @param positionToMaxBy * The position in the data point to maximize * @return The transformed DataStream. */ public SingleOutputStreamOperator<OUT, ?> maxBy(String positionToMaxBy) { return this.maxBy(positionToMaxBy, true); } /** * Applies an aggregation that that gives the current element with the * maximum value at the given position by the given key. An independent * aggregate is kept per key. If more elements have the maximum value at the * given position, the operator returns either the first or last one, * depending on the parameter set. * * @param positionToMaxBy * The position in the data point to maximize. * @param first * If true, then the operator return the first element with the * maximum value, otherwise returns the last * @return The transformed DataStream. */ public SingleOutputStreamOperator<OUT, ?> maxBy(int positionToMaxBy, boolean first) { return aggregate(new ComparableAggregator<OUT>(positionToMaxBy, getType(), AggregationType.MAXBY, first, getExecutionConfig())); } protected SingleOutputStreamOperator<OUT, ?> aggregate(AggregationFunction<OUT> aggregate) { StreamGroupedReduce<OUT> operator = new StreamGroupedReduce<OUT>(clean(aggregate), keySelector); SingleOutputStreamOperator<OUT, ?> returnStream = transform("Grouped Aggregation", getType(), operator); return returnStream; } }
42.081325
106
0.724644
b0b82bfb320b57a81c543591c4db40518fd49410
7,814
package org.sakaiproject.site.tool.helper.participant.rsf; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.entitybroker.DeveloperHelperService; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SiteService; import org.sakaiproject.site.tool.helper.participant.impl.SiteAddParticipantHandler; import org.sakaiproject.tool.api.SessionManager; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.user.api.UserDirectoryService; import uk.ac.cam.caret.sakai.rsf.producers.FrameAdjustingProducer; import uk.ac.cam.caret.sakai.rsf.util.SakaiURLUtil; import uk.org.ponder.messageutil.MessageLocator; import uk.org.ponder.messageutil.TargettedMessage; import uk.org.ponder.messageutil.TargettedMessageList; import uk.org.ponder.rsf.components.UIBranchContainer; import uk.org.ponder.rsf.components.UICommand; import uk.org.ponder.rsf.components.UIContainer; import uk.org.ponder.rsf.components.UIForm; import uk.org.ponder.rsf.components.UIMessage; import uk.org.ponder.rsf.components.UIInput; import uk.org.ponder.rsf.components.UIOutputMany; import uk.org.ponder.rsf.components.UISelect; import uk.org.ponder.rsf.components.UISelectChoice; import uk.org.ponder.rsf.components.UISelectLabel; import uk.org.ponder.rsf.components.decorators.UILabelTargetDecorator; import uk.org.ponder.rsf.flow.ARIResult; import uk.org.ponder.rsf.flow.ActionResultInterceptor; import uk.org.ponder.rsf.flow.jsfnav.NavigationCase; import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter; import uk.org.ponder.rsf.view.ComponentChecker; import uk.org.ponder.rsf.view.ViewComponentProducer; import uk.org.ponder.rsf.viewstate.RawViewParameters; import uk.org.ponder.rsf.viewstate.SimpleViewParameters; import uk.org.ponder.rsf.viewstate.ViewParameters; import uk.org.ponder.stringutil.StringList; /** * Assign same role while adding participant * @author * */ public class EmailNotiProducer implements ViewComponentProducer, NavigationCaseReporter, ActionResultInterceptor { /** Our log (commons). */ private static Log M_log = LogFactory.getLog(EmailNotiProducer.class); public SiteAddParticipantHandler handler; public static final String VIEW_ID = "EmailNoti"; public MessageLocator messageLocator; public FrameAdjustingProducer frameAdjustingProducer; public SessionManager sessionManager; private SiteService siteService = null; public void setSiteService(SiteService siteService) { this.siteService = siteService; } public String getViewID() { return VIEW_ID; } private TargettedMessageList targettedMessageList; public void setTargettedMessageList(TargettedMessageList targettedMessageList) { this.targettedMessageList = targettedMessageList; } public UserDirectoryService userDirectoryService; public void setUserDirectoryService(UserDirectoryService userDirectoryService) { this.userDirectoryService = userDirectoryService; } private DeveloperHelperService developerHelperService; public void setDeveloperHelperService( DeveloperHelperService developerHelperService) { this.developerHelperService = developerHelperService; } public void fillComponents(UIContainer tofill, ViewParameters arg1, ComponentChecker arg2) { String locationId = developerHelperService.getCurrentLocationId(); String siteTitle = ""; try { Site s = siteService.getSite(locationId); siteTitle = s.getTitle(); } catch (IdUnusedException e) { // TODO Auto-generated catch block e.printStackTrace(); } UIMessage.make(tofill, "add.addpart", "add.addpart", new Object[]{siteTitle}); UIBranchContainer content = UIBranchContainer.make(tofill, "content:"); UIForm emailNotiForm = UIForm.make(content, "emailNoti-form"); // csrf token UIInput.make(emailNotiForm, "csrfToken", "#{siteAddParticipantHandler.csrfToken}", handler.csrfToken); // role choice String[] values = new String[] { Boolean.TRUE.toString(), Boolean.FALSE.toString()}; String[] labels = new String[] { messageLocator.getMessage("addnoti.sendnow"), messageLocator.getMessage("addnoti.dontsend") }; StringList notiItems = new StringList(); UISelect notiSelect = UISelect.make(emailNotiForm, "select-noti", null, "#{siteAddParticipantHandler.emailNotiChoice}", handler.emailNotiChoice); String selectID = notiSelect.getFullID(); notiSelect.optionnames = UIOutputMany.make(labels); for (int i = 0; i < values.length; i++) { UIBranchContainer notiRow = UIBranchContainer.make(emailNotiForm, "noti-row:", Integer.toString(i)); UISelectLabel lb = UISelectLabel.make(notiRow, "noti-label", selectID, i); UISelectChoice choice = UISelectChoice.make(notiRow, "noti-select", selectID, i); UILabelTargetDecorator.targetLabel(lb, choice); notiItems.add(values[i]); } notiSelect.optionlist.setValue(notiItems.toStringArray()); // buttons UICommand.make(emailNotiForm, "continue", messageLocator.getMessage("gen.continue"), "#{siteAddParticipantHandler.processEmailNotiContinue}"); UICommand.make(emailNotiForm, "back", messageLocator.getMessage("gen.back"), "#{siteAddParticipantHandler.processEmailNotiBack}"); UICommand.make(emailNotiForm, "cancel", messageLocator.getMessage("gen.cancel"), "#{siteAddParticipantHandler.processCancel}"); //process any messages targettedMessageList = handler.targettedMessageList; if (targettedMessageList != null && targettedMessageList.size() > 0) { for (int i = 0; i < targettedMessageList.size(); i++ ) { TargettedMessage msg = targettedMessageList.messageAt(i); if (msg.severity == TargettedMessage.SEVERITY_ERROR) { UIBranchContainer errorRow = UIBranchContainer.make(tofill,"error-row:", Integer.valueOf(i).toString()); if (msg.args != null ) { UIMessage.make(errorRow,"error", msg.acquireMessageCode(), (Object[]) msg.args); } else { UIMessage.make(errorRow,"error", msg.acquireMessageCode()); } } else if (msg.severity == TargettedMessage.SEVERITY_INFO) { UIBranchContainer errorRow = UIBranchContainer.make(tofill,"info-row:", Integer.valueOf(i).toString()); if (msg.args != null ) { UIMessage.make(errorRow,"info", msg.acquireMessageCode(), (Object[]) msg.args); } else { UIMessage.make(errorRow,"info", msg.acquireMessageCode()); } } } } } public ViewParameters getViewParameters() { AddViewParameters params = new AddViewParameters(); params.id = null; return params; } public List<NavigationCase> reportNavigationCases() { List<NavigationCase> togo = new ArrayList<NavigationCase>(); togo.add(new NavigationCase("continue", new SimpleViewParameters(ConfirmProducer.VIEW_ID))); togo.add(new NavigationCase("backSameRole", new SimpleViewParameters(SameRoleProducer.VIEW_ID))); togo.add(new NavigationCase("backDifferentRole", new SimpleViewParameters(DifferentRoleProducer.VIEW_ID))); return togo; } public void interceptActionResult(ARIResult result, ViewParameters incoming, Object actionReturn) { if ("done".equals(actionReturn)) { Tool tool = handler.getCurrentTool(); result.resultingView = new RawViewParameters(SakaiURLUtil.getHelperDoneURL(tool, sessionManager)); } } }
40.071795
147
0.729204
eff204acf5d5575d933b89fcfe6254f2bf2e601f
3,611
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.xml.text.syntax; import org.netbeans.editor.TokenContext; import org.netbeans.editor.TokenContextPath; import org.netbeans.modules.xml.text.syntax.javacc.lib.*; /** * Token-ids and token-categories for XML * * @author Miloslav Metelka * @author Petr Kuzel * @version 1.0 */ public class XMLTokenContext extends TokenContext { public static final int ATT_ID = 1; public static final int CDATA_ID = 2; public static final int COMMENT_ID = 3; public static final int EOL_ID = 4; public static final int ERROR_ID = 5; public static final int KW_ID = 6; public static final int PLAIN_ID = 7; public static final int REF_ID = 8; public static final int STRING_ID = 9; public static final int SYMBOL_ID = 10; public static final int TAG_ID = 11; public static final int TARGET_ID = 12; public static final int CDATA_MARKUP_ID = 13; // <home attname="..."> // NOI18N public static final JJTokenID ATT = new JJTokenID("attribute", ATT_ID); // NOI18N // <![CDATA[ dtatasection ]]> public static final JJTokenID CDATA = new JJTokenID("cdata", CDATA_ID); // NOI18N public static final JJTokenID COMMENT = new JJTokenID("comment", COMMENT_ID); // NOI18N public static final JJTokenID EOL = new JJTokenID("EOL", EOL_ID); // NOI18N public static final JJTokenID ERROR = new JJTokenID("error", ERROR_ID, true); // NOI18N // <!declatarion + "SYSTEM"/"PUBLIC" // NOI18N public static final JJTokenID KW = new JJTokenID("keyword", KW_ID); // NOI18N public static final JJTokenID PLAIN = new JJTokenID("plain", PLAIN_ID); // NOI18N // &aref; &#x000; public static final JJTokenID REF = new JJTokenID("ref", REF_ID); // NOI18N // <home id="attrvalue" > // NOI18N public static final JJTokenID STRING = new JJTokenID("string", STRING_ID); // NOI18N // <>! public static final JJTokenID SYMBOL = new JJTokenID("symbol", SYMBOL_ID); // NOI18N // <atagname ....> public static final JJTokenID TAG = new JJTokenID("tag", TAG_ID); // NOI18N // <? target ...> public static final JJTokenID TARGET = new JJTokenID("target", TARGET_ID); // NOI18N public static final JJTokenID CDATA_MARKUP = new JJTokenID("markup-in-CDATA", CDATA_MARKUP_ID); // NOI18N // Context instance declaration public static final XMLTokenContext context = new XMLTokenContext(); public static final TokenContextPath contextPath = context.getContextPath(); protected XMLTokenContext() { super("xml-"); // NOI18N try { addDeclaredTokenIDs(); } catch (Exception e) { if (Boolean.getBoolean("netbeans.debug.exceptions")) { // NOI18N e.printStackTrace(); } } } }
37.226804
109
0.688729
343520c0a102e67d34cbc8faf9cf00a270392436
33,401
/* * Copyright 2016 Richard Cartwright * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tv.amwa.maj.industry; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import lombok.extern.slf4j.Slf4j; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; import org.w3c.dom.Node; import tv.amwa.maj.constant.CommonConstants; import tv.amwa.maj.extensions.avid.AvidFactory; import tv.amwa.maj.io.xml.XMLBuilder; import tv.amwa.maj.meta.ClassDefinition; import tv.amwa.maj.meta.PropertyDefinition; import tv.amwa.maj.meta.TypeDefinition; import tv.amwa.maj.meta.TypeDefinitionFixedArray; import tv.amwa.maj.meta.TypeDefinitionRecord; import tv.amwa.maj.meta.TypeDefinitionSet; import tv.amwa.maj.meta.TypeDefinitionStrongObjectReference; import tv.amwa.maj.meta.TypeDefinitionVariableArray; import tv.amwa.maj.model.InterchangeObject; import tv.amwa.maj.model.impl.AAFFileDescriptorImpl; import tv.amwa.maj.model.impl.AES3PCMDescriptorImpl; import tv.amwa.maj.model.impl.AIFCDescriptorImpl; import tv.amwa.maj.model.impl.AuxiliaryDescriptorImpl; import tv.amwa.maj.model.impl.BWFImportDescriptorImpl; import tv.amwa.maj.model.impl.CDCIDescriptorImpl; import tv.amwa.maj.model.impl.CodecDefinitionImpl; import tv.amwa.maj.model.impl.CommentMarkerImpl; import tv.amwa.maj.model.impl.ComponentImpl; import tv.amwa.maj.model.impl.CompositionPackageImpl; import tv.amwa.maj.model.impl.ConstantValueImpl; import tv.amwa.maj.model.impl.ContainerDefinitionImpl; import tv.amwa.maj.model.impl.ControlPointImpl; import tv.amwa.maj.model.impl.DataDefinitionImpl; import tv.amwa.maj.model.impl.DataEssenceDescriptorImpl; import tv.amwa.maj.model.impl.DefinitionObjectImpl; import tv.amwa.maj.model.impl.DescriptiveClipImpl; import tv.amwa.maj.model.impl.DescriptiveFrameworkImpl; import tv.amwa.maj.model.impl.DescriptiveMarkerImpl; import tv.amwa.maj.model.impl.DescriptiveObjectImpl; import tv.amwa.maj.model.impl.DictionaryImpl; import tv.amwa.maj.model.impl.EdgeCodeSegmentImpl; import tv.amwa.maj.model.impl.EssenceDataImpl; import tv.amwa.maj.model.impl.EssenceDescriptorImpl; import tv.amwa.maj.model.impl.EventImpl; import tv.amwa.maj.model.impl.EventTrackImpl; import tv.amwa.maj.model.impl.FillerImpl; import tv.amwa.maj.model.impl.FilmDescriptorImpl; import tv.amwa.maj.model.impl.GPITriggerImpl; import tv.amwa.maj.model.impl.HTMLClipImpl; import tv.amwa.maj.model.impl.HTMLDescriptorImpl; import tv.amwa.maj.model.impl.IdentificationImpl; import tv.amwa.maj.model.impl.ImportDescriptorImpl; import tv.amwa.maj.model.impl.InterchangeObjectImpl; import tv.amwa.maj.model.impl.InterpolationDefinitionImpl; import tv.amwa.maj.model.impl.KLVDataDefinitionImpl; import tv.amwa.maj.model.impl.KLVDataImpl; import tv.amwa.maj.model.impl.LocatorImpl; import tv.amwa.maj.model.impl.MPEGVideoDescriptorImpl; import tv.amwa.maj.model.impl.MaterialPackageImpl; import tv.amwa.maj.model.impl.NetworkLocatorImpl; import tv.amwa.maj.model.impl.OperationDefinitionImpl; import tv.amwa.maj.model.impl.PackageImpl; import tv.amwa.maj.model.impl.ParameterDefinitionImpl; import tv.amwa.maj.model.impl.ParameterImpl; import tv.amwa.maj.model.impl.PhysicalDescriptorImpl; import tv.amwa.maj.model.impl.PictureDescriptorImpl; import tv.amwa.maj.model.impl.PluginDefinitionImpl; import tv.amwa.maj.model.impl.PrefaceImpl; import tv.amwa.maj.model.impl.PulldownImpl; import tv.amwa.maj.model.impl.RGBADescriptorImpl; import tv.amwa.maj.model.impl.RIFFChunkImpl; import tv.amwa.maj.model.impl.RecordingDescriptorImpl; import tv.amwa.maj.model.impl.ScopeReferenceImpl; import tv.amwa.maj.model.impl.SegmentImpl; import tv.amwa.maj.model.impl.SoundDescriptorImpl; import tv.amwa.maj.model.impl.SourceClipImpl; import tv.amwa.maj.model.impl.SourcePackageImpl; import tv.amwa.maj.model.impl.SourceReferenceSegmentImpl; import tv.amwa.maj.model.impl.StaticTrackImpl; import tv.amwa.maj.model.impl.SubDescriptorImpl; import tv.amwa.maj.model.impl.TIFFDescriptorImpl; import tv.amwa.maj.model.impl.TaggedValueDefinitionImpl; import tv.amwa.maj.model.impl.TaggedValueImpl; import tv.amwa.maj.model.impl.TapeDescriptorImpl; import tv.amwa.maj.model.impl.TextClipImpl; import tv.amwa.maj.model.impl.TextLocatorImpl; import tv.amwa.maj.model.impl.TimecodeSegmentImpl; import tv.amwa.maj.model.impl.TimecodeStream12MImpl; import tv.amwa.maj.model.impl.TimecodeStreamImpl; import tv.amwa.maj.model.impl.TimelineTrackImpl; import tv.amwa.maj.model.impl.TrackImpl; import tv.amwa.maj.model.impl.VaryingValueImpl; import tv.amwa.maj.model.impl.WAVEDescriptorImpl; import tv.amwa.maj.model.impl.WAVEPCMDescriptorImpl; import tv.amwa.maj.record.impl.AUIDImpl; // TODO add support for streams // TODO investigate why multiple descriptors don't work // TODO work out what to do about portable objects ... like implement a mix in equivalent @Slf4j public class JPAGenerator { private final static String ORM_NAMESPACE = "http://java.sun.com/xml/ns/persistence/orm"; // private final static String ORM_PREFIX = "orm"; /** * <p>Generate an object relational mapping * <a href="http://en.wikipedia.org/wiki/Java_Persistence_API">Java Persistence API 2.0</a> * configuration file (<code>orm.xml</code>) from the given collection of classes and store * it in the given file. Any embeddable objects or other utility class mappings will be * included in the mapping if they are required.</p> * * <p>The mapping file allows the given * {@linkplain MediaEntity media entities} to be persisted to a relational database * using a JPA implementation, such as <a href="http://openjpa.apache.org/">Open JPA</a> * or <a href="https://www.hibernate.org/">Hibernate</a>. By using this method, a developer * only needs to use one set of annotations to turn a class into both:</p> * * <ul> * <li>a media class that benefits from the facilities of this * media engine;</li> * <li>a JPA persistent entity, also known as an <em>EJB3 entity bean</em>.</li> * </ul> * * <p>Another benefit of using media annotations rather than JPA annotations is that * this code base can be compiled in Java SE without the need for JPA libraries to * be present.</p> * * @param mediaClassList Collection of classes to create object relational mappings for. * @param fileName Name and path of the object relational mapping file to create. * @return Was an object-relational mapping file generated successfully? * * @throws NullPointerException Cannot generate an object relational mapping if any * of the input values or classes is <code>null</code>. * @throws IllegalArgumentException One or more of the given classes is not * annotated as a media class. */ public final static boolean generateORM( Collection<Class<? extends MediaEntity>> mediaClassList, String fileName) throws NullPointerException, IllegalArgumentException { for ( Class<? extends MediaEntity> mediaEntity : mediaClassList ) if (mediaEntity == null) throw new NullPointerException("Cannot generate an object relational mapping when one or more of the classes is a null value."); if (fileName == null) throw new NullPointerException("The given output filename is null."); // Schema name moved to external ... this is part of the system properties and not coupled to the orm file DocumentFragment root = XMLBuilder.createDocumentFragment(); XMLBuilder.appendComment(root, " Automatically generated JPA 2.0 mapping using the MAJAPI JPA Generator - " + Forge.now().toString() + " "); Element entityMappings = child(root, "entity-mappings"); attr(entityMappings, "version", "2.0"); Element persistenceUnitMetadata = child(entityMappings, "persistence-unit-metadata"); child(persistenceUnitMetadata, "xml-mapping-metadata-complete"); Element persistenceUnitDefaults = child(persistenceUnitMetadata, "persistence-unit-defaults"); element(persistenceUnitDefaults, "access", "FIELD"); XMLBuilder.appendComment(entityMappings, " Generated mappings for all media entities. "); List<Class<?>> sortedClasses = new ArrayList<Class<?>>(); for ( Class<?> mediaClass : mediaClassList ) { if (Modifier.isAbstract(mediaClass.getModifiers())) sortedClasses.add(0, mediaClass); else sortedClasses.add(mediaClass); } for ( Class<?> mediaClass : sortedClasses) { ClassDefinition classDefinition = Warehouse.lookForClass(mediaClass); XMLBuilder.appendComment(entityMappings, " **************************************************** "); XMLBuilder.appendComment(entityMappings, " *** " + classDefinition.getName() + " "); XMLBuilder.appendComment(entityMappings, " **************************************************** "); Element entity = null; if (classDefinition.isConcrete()) { entity = child(entityMappings, "entity"); attr(entity, "name", classDefinition.getName()); attr(entity, "access", "FIELD"); attr(entity, "class", classDefinition.getJavaImplementation().getCanonicalName()); Element table = child(entity, "table"); attr(table, "name", classDefinition.getName()); Element inheritance = child(entity, "inheritance"); attr(inheritance, "strategy", "JOINED"); } else { entity = child(entityMappings, "mapped-superclass"); attr(entity, "access", "FIELD"); attr(entity, "class", classDefinition.getJavaImplementation().getCanonicalName()); } Element attributes = child(entity, "attributes"); Set<? extends PropertyDefinition> properties = classDefinition.getPropertyDefinitions(); // TODO consider whether this should be property access if (classDefinition.isRoot()) { Element id = child(attributes, "id"); attr(id, "name", "persistentID"); Element column = child(id, "column"); attr(column, "name", "PersistentID"); child(id, "generated-value"); } List<String> transientList = new ArrayList<String>(); List<PropertyDefinition> basicList = new ArrayList<PropertyDefinition>(); List<PropertyDefinition> oneToOneList = new ArrayList<PropertyDefinition>(); List<PropertyDefinition> oneToManyList = new ArrayList<PropertyDefinition>(); List<PropertyDefinition> elementCollectionList = new ArrayList<PropertyDefinition>(); TypeDefinition propertyType = null; for ( PropertyDefinition property : properties ) { if (property.getAUID().equals(CommonConstants.ObjectClassID)) continue; if ((mediaClass.equals(TaggedValueImpl.class)) && (property.getName().equals("PortableObject"))) continue; propertyType = property.getTypeDefinition(); TypeDefinition elementType = null; switch (propertyType.getTypeCategory()) { case FixedArray: elementType = ((TypeDefinitionFixedArray) propertyType).getType(); switch (elementType.getTypeCategory()) { case Record: elementCollectionList.add(property); break; default: basicList.add(property); } break; case Set: elementType = ((TypeDefinitionSet) propertyType).getElementType(); switch (elementType.getTypeCategory()) { case Record: elementCollectionList.add(property); break; case Int: basicList.add(property); break; case WeakObjRef: oneToOneList.add(property); break; case StrongObjRef: default: oneToManyList.add(property); break; } break; case VariableArray: elementType = ((TypeDefinitionVariableArray) propertyType).getType(); switch (elementType.getTypeCategory()) { case Int: basicList.add(property); break; case WeakObjRef: oneToOneList.add(property); break; case StrongObjRef: default: oneToManyList.add(property); break; } break; case WeakObjRef: case StrongObjRef: oneToOneList.add(property); break; case Opaque: case Indirect: case ExtEnum: case Record: basicList.add(property); transientList.add(lowerFirstLetter(property.getName())); break; case Stream: transientList.add(lowerFirstLetter(property.getName())); break; default: basicList.add(property); break; } } for ( PropertyDefinition property : basicList ) { propertyType = property.getTypeDefinition(); switch (propertyType.getTypeCategory()) { case String: { Element basic = child(attributes, "basic"); if ((mediaClass.equals(NetworkLocatorImpl.class)) || (mediaClass.equals(TextLocatorImpl.class))) { attr(basic, "name", lowerFirstLetter(property.getName()) + "Persist"); attr(basic, "access", "PROPERTY"); } else { attr(basic, "name", lowerFirstLetter(property.getName())); } Element column = child(basic, "column"); attr(column, "name", property.getName()); attr(column, "column-definition", "TEXT CHARACTER SET utf8 COLLATE utf8_general_ci"); child(basic, "lob"); break; } case Enum: { Element basic = child(attributes, "basic"); attr(basic, "name", lowerFirstLetter(property.getName())); Element column = child(basic, "column"); attr(column, "name", property.getName()); if (!propertyType.getName().equals("Boolean")) element(basic, "enumerated", "STRING"); break; } case ExtEnum: { Element basic = child(attributes, "basic"); attr(basic, "name", lowerFirstLetter(property.getName()) + "String"); attr(basic, "access", "PROPERTY"); Element column = child(basic, "column"); attr(column, "name", property.getName()); attr(column, "column-definition", AUIDImpl.MYSQL_COLUMN_DEFINITION); break; } case Record: { TypeDefinitionRecord recordType = (TypeDefinitionRecord) propertyType; Element basic = child(attributes, "basic"); if (( (mediaClass.equals(PluginDefinitionImpl.class)) && (property.getName().equals("PluginVersion"))) || ((mediaClass.equals(IdentificationImpl.class)) && (property.getName().equals("ApplicationVersion")) ) ) attr(basic, "name", lowerFirstLetter(property.getName()) + "Persist"); else attr(basic, "name", lowerFirstLetter(property.getName()) + "String"); attr(basic, "access", "PROPERTY"); Element column = child(basic, "column"); attr(column, "name", property.getName()); try { String columnDefinition = (String) recordType.getImplementation().getField("MYSQL_COLUMN_DEFINITION").get(null); if (columnDefinition != null) attr(column, "column-definition", columnDefinition); } catch (Exception e) { } break; } case Opaque: case Indirect: { Element basic = child(attributes, "basic"); attr(basic, "name", lowerFirstLetter(property.getName()) + "Persist"); attr(basic, "access", "PROPERTY"); Element column = child(basic, "column"); attr(column, "name", property.getName()); child(basic, "lob"); if (mediaClass.equals(TaggedValueImpl.class)) { transientList.remove("indirectValue"); transientList.add("value"); transientList.add("typeDefinition"); } if (mediaClass.equals(KLVDataImpl.class)) { transientList.remove("kLVDataValue"); transientList.add("klvDataValue"); } break; } default: { Element basic = child(attributes, "basic"); attr(basic, "name", lowerFirstLetter(property.getName())); Element column = child(basic, "column"); attr(column, "name", property.getName()); break; } } } if (mediaClass.equals(ComponentImpl.class)) { Element basic = child(attributes, "basic"); attr(basic, "name", "lengthPresent"); Element column = child(basic, "column"); attr(column, "name", "LengthPresent"); } if (mediaClass.equals(InterchangeObjectImpl.class)) { Element basic = child(attributes, "basic"); attr(basic, "name", "generationTracking"); Element column = child(basic, "column"); attr(column, "name", "GenerationTracking"); } for ( PropertyDefinition property : oneToManyList ) { propertyType = property.getTypeDefinition(); switch (propertyType.getTypeCategory()) { case VariableArray: { TypeDefinitionVariableArray arrayType = (TypeDefinitionVariableArray) propertyType; TypeDefinition elementType = arrayType.getType(); switch (elementType.getTypeCategory()) { case StrongObjRef: { Element oneToMany = child(attributes, "one-to-many"); attr(oneToMany, "name", lowerFirstLetter(property.getName())); attr(oneToMany, "target-entity", ((TypeDefinitionStrongObjectReference) elementType) .getObjectType().getJavaImplementation().getCanonicalName()); Element orderColumn = child(oneToMany, "order-column"); attr(orderColumn, "name", "PersistentIndex"); Element joinColumn = child(oneToMany, "join-column"); attr(joinColumn, "name", property.getName()); Element cascade = child(oneToMany, "cascade"); child(cascade, "cascade-all"); break; } default: log.warn("Not handling a variable array of type : " + propertyType.getName()); break; } break; } case Set: { TypeDefinitionSet setType = (TypeDefinitionSet) propertyType; TypeDefinition elementType = setType.getElementType(); switch (elementType.getTypeCategory()) { case StrongObjRef: { Element oneToMany = child(attributes, "one-to-many"); attr(oneToMany, "name", lowerFirstLetter(property.getName())); attr(oneToMany, "target-entity", ((TypeDefinitionStrongObjectReference) elementType) .getObjectType().getJavaImplementation().getCanonicalName()); Element joinColumn = child(oneToMany, "join-column"); attr(joinColumn, "name", property.getName()); Element cascade = child(oneToMany, "cascade"); child(cascade, "cascade-all"); break; } default: log.warn("Not handling a set of type : " + propertyType.getName()); break; } break; } case FixedArray: log.warn("Not handling a fixed array type : " + propertyType.getName()); break; default: log.warn("Not handling a one-to-many for type : " + propertyType.getName()); break; } } for ( PropertyDefinition property : oneToOneList ) { propertyType = property.getTypeDefinition(); switch (propertyType.getTypeCategory()) { case StrongObjRef: { Element oneToOne = child(attributes, "one-to-one"); attr(oneToOne, "name", lowerFirstLetter(property.getName())); attr(oneToOne, "target-entity", ((TypeDefinitionStrongObjectReference) propertyType) .getObjectType().getJavaImplementation().getCanonicalName()); Element joinColumn = child(oneToOne, "join-column"); attr(joinColumn, "name", property.getName()); Element cascade = child(oneToOne, "cascade"); child(cascade, "cascade-all"); break; } case WeakObjRef: { Element oneToOne = child(attributes, "one-to-one"); attr(oneToOne, "name", lowerFirstLetter(property.getName())); attr(oneToOne, "target-entity", WeakReference.class.getCanonicalName()); Element joinColumn = child(oneToOne, "join-column"); attr(joinColumn, "name", property.getName()); Element cascade = child(oneToOne, "cascade"); child(cascade, "cascade-all"); break; } case Set: { // Assume this must be a WeakReferenceSet Element oneToOne = child(attributes, "one-to-one"); attr(oneToOne, "name", lowerFirstLetter(property.getName())); attr(oneToOne, "target-entity", WeakReferenceSet.class.getCanonicalName()); Element joinColumn = child(oneToOne, "join-column"); attr(joinColumn, "name", property.getName()); Element cascade = child(oneToOne, "cascade"); child(cascade, "cascade-all"); break; } case VariableArray: { // Assume this must be a WeakReferenceVector Element oneToOne = child(attributes, "one-to-one"); attr(oneToOne, "name", lowerFirstLetter(property.getName())); attr(oneToOne, "target-entity", WeakReferenceVector.class.getCanonicalName()); Element joinColumn = child(oneToOne, "join-column"); attr(joinColumn, "name", property.getName()); Element cascade = child(oneToOne, "cascade"); child(cascade, "cascade-all"); break; } default: log.warn("Not handling a one-to-one for type " + propertyType.getName()); break; } } for ( PropertyDefinition property : elementCollectionList ) { propertyType = property.getTypeDefinition(); switch (propertyType.getTypeCategory()) { case FixedArray: { TypeDefinitionFixedArray fixedArrayType = (TypeDefinitionFixedArray) propertyType; TypeDefinition elementType = fixedArrayType.getType(); switch (elementType.getTypeCategory()) { case Record: { Element elementCollection = child(attributes, "element-collection"); attr(elementCollection, "access", "PROPERTY"); attr(elementCollection, "name", lowerFirstLetter(property.getName()) + "StringList"); //<order-column name="ArrayIndex"/> Element orderColumn = child(elementCollection, "order-column"); attr(orderColumn, "name", "ArrayIndex"); //<column name="PixelLayout"/> Element column = child(elementCollection, "column"); attr(column, "name", property.getName()); //<collection-table name="PixelLayout"/> Element collectionTable = child(elementCollection, "collection-table"); attr(collectionTable, "name", property.getName()); break; } default: log.warn("Not handling element collection fixed array for type : " + propertyType.getName()); break; } break; } case Set: { TypeDefinitionSet setType = (TypeDefinitionSet) propertyType; TypeDefinition elementType = setType.getElementType(); switch (elementType.getTypeCategory()) { case Record: { Element elementCollection = child(attributes, "element-collection"); attr(elementCollection, "access", "PROPERTY"); attr(elementCollection, "name", lowerFirstLetter(property.getName()) + "StringSet"); //<column name="PixelLayout"/> Element column = child(elementCollection, "column"); attr(column, "name", property.getName()); //<collection-table name="PixelLayout"/> Element collectionTable = child(elementCollection, "collection-table"); attr(collectionTable, "name", property.getName()); break; } } break; } default: log.warn("Not handling element collection for type : " + propertyType.getName()); break; } } if (mediaClass.equals(InterchangeObjectImpl.class)) { transientList.add("persistentIndex"); } for ( String transientItem : transientList) { Element transientElement = child(attributes, "transient"); attr(transientElement, "name", transientItem); } } // Add weak reference support XMLBuilder.appendComment(entityMappings, " Entities used internally by MAJ "); Element weakReference = child(entityMappings, "entity"); attr(weakReference, "name", "WeakReference"); attr(weakReference, "access", "FIELD"); attr(weakReference, "class", WeakReference.class.getCanonicalName()); Element weakReferenceTable = child(weakReference, "table"); attr(weakReferenceTable, "name", "WeakReference"); Element weakReferenceAttributes = child(weakReference, "attributes"); Element weakReferenceId = child(weakReferenceAttributes, "id"); attr(weakReferenceId, "name", "persistentID"); Element weakReferenceIdColumn = child(weakReferenceId, "column"); attr(weakReferenceIdColumn, "name", "PersistentID"); child(weakReferenceId, "generated-value"); Element weakReferenceTypeName = child(weakReferenceAttributes, "basic"); attr(weakReferenceTypeName, "name", "canonicalTypeName"); attr(weakReferenceTypeName, "fetch", "EAGER"); Element weakReferenceTypeNameColumn = child(weakReferenceTypeName, "column"); attr(weakReferenceTypeNameColumn, "name", "TypeName"); attr(weakReferenceTypeNameColumn, "nullable", "false"); Element weakReferenceIndex = child(weakReferenceAttributes, "basic"); attr(weakReferenceIndex, "name", "persistentIndex"); Element weakReferenceIndexColumn = child(weakReferenceIndex, "column"); attr(weakReferenceIndexColumn, "name", "PersistentIndex"); attr(weakReferenceIndexColumn, "nullable", "false"); Element weakReferenceIdent = child(weakReferenceAttributes, "basic"); attr(weakReferenceIdent, "name", "identifierString"); attr(weakReferenceIdent, "access", "PROPERTY"); attr(weakReferenceIdent, "fetch", "EAGER"); Element weakReferenceIdentColumn = child(weakReferenceIdent, "column"); attr(weakReferenceIdentColumn, "name", "Identifier"); attr(weakReferenceIdentColumn, "column-definition", "CHAR(36) CHARACTER SET ascii COLLATE ascii_general_ci"); Element weakReferenceCachedValue = child(weakReferenceAttributes, "transient"); attr(weakReferenceCachedValue, "name", "cachedValue"); Element weakReferenceIdentifier = child(weakReferenceAttributes, "transient"); attr(weakReferenceIdentifier, "name", "identifier"); // WeakReferenceVector Element weakReferenceVector = child(entityMappings, "entity"); attr(weakReferenceVector, "access", "FIELD"); attr(weakReferenceVector, "class", WeakReferenceVector.class.getCanonicalName()); attr(weakReferenceVector, "name", "WeakReferenceVector"); Element weakReferenceVectorTable = child(weakReferenceVector, "table"); attr(weakReferenceVectorTable, "name", "WeakReferenceVector"); Element weakReferenceVectorAttributes = child(weakReferenceVector, "attributes"); Element weakReferenceVectorID = child(weakReferenceVectorAttributes, "id"); attr(weakReferenceVectorID, "name", "persistentID"); Element weakReferenceVectorIDColumn = child(weakReferenceVectorID, "column"); attr(weakReferenceVectorIDColumn, "name", "PersistentID"); child(weakReferenceVectorID, "generated-value"); Element weakReferenceVectorVector = child(weakReferenceVectorAttributes, "one-to-many"); attr(weakReferenceVectorVector, "name", "vector"); attr(weakReferenceVectorVector, "target-entity", WeakReference.class.getCanonicalName()); Element weakReferenceVectorOrder = child(weakReferenceVectorVector, "order-column"); attr(weakReferenceVectorOrder, "name", "PersistentIndex"); Element weakReferenceVectorJoin = child(weakReferenceVectorVector, "join-column"); attr(weakReferenceVectorJoin, "name", "VectorElements"); Element weakReferenceVectorCascade = child(weakReferenceVectorVector, "cascade"); child(weakReferenceVectorCascade, "cascade-all"); // WeakReferenceSet Element weakReferenceSet = child(entityMappings, "entity"); attr(weakReferenceSet, "access", "FIELD"); attr(weakReferenceSet, "class", WeakReferenceSet.class.getCanonicalName()); attr(weakReferenceSet, "name", "WeakReferenceSet"); Element weakReferenceSetTable = child(weakReferenceSet, "table"); attr(weakReferenceSetTable, "name", "WeakReferenceSet"); Element weakReferenceSetAttributes = child(weakReferenceSet, "attributes"); Element weakReferenceSetID = child(weakReferenceSetAttributes, "id"); attr(weakReferenceSetID, "name", "persistentID"); Element weakReferenceSetIDColumn = child(weakReferenceSetID, "column"); attr(weakReferenceSetIDColumn, "name", "PersistentID"); child(weakReferenceSetID, "generated-value"); Element weakReferenceSetSet = child(weakReferenceSetAttributes, "one-to-many"); attr(weakReferenceSetSet, "name", "set"); attr(weakReferenceSetSet, "target-entity", WeakReference.class.getCanonicalName()); Element weakReferenceSetJoin = child(weakReferenceSetSet, "join-column"); attr(weakReferenceSetJoin, "name", "SetElements"); Element weakReferenceSetCascade = child(weakReferenceSetSet, "cascade"); child(weakReferenceSetCascade, "cascade-all"); FileWriter writer = null; try{ writer = new FileWriter(fileName); writer.append(XMLBuilder.transformNodeToString(root)); writer.flush(); } catch (IOException ioe) { return false; } finally { try { writer.close(); } catch (Exception e) { } } return true; } private final static Element child( Node element, String name) { return XMLBuilder.createChild(element, ORM_NAMESPACE, null, name); } private final static void attr( Element element, String attributeName, String attributeValue) { XMLBuilder.setAttribute(element, ORM_NAMESPACE, null, attributeName, attributeValue); } private final static void element( Element parent, String elementName, String elementValue) { XMLBuilder.appendElement(parent, ORM_NAMESPACE, null, elementName, elementValue); } protected static final String lowerFirstLetter( String changeMe) { if (Character.isUpperCase(changeMe.charAt(0))) { StringBuffer replacement = new StringBuffer(changeMe); replacement.setCharAt(0, Character.toLowerCase(changeMe.charAt(0))); return replacement.toString(); } return changeMe; } /** <p>List of concrete AAF classes that are interchangeable as they extend * {@link InterchangeObject}.</p> */ public final static Class<?>[] interchangeable = new Class<?>[] { // TransitionImpl.class, EdgeCodeSegmentImpl.class, // EssenceGroupImpl.class, CommentMarkerImpl.class, GPITriggerImpl.class, DescriptiveMarkerImpl.class, FillerImpl.class, // NestedScopeImpl.class, // OperationGroupImpl.class, PulldownImpl.class, ScopeReferenceImpl.class, // SelectorImpl.class, // SequenceImpl.class, SourceClipImpl.class, DescriptiveClipImpl.class, HTMLClipImpl.class, TimecodeSegmentImpl.class, TimecodeStream12MImpl.class, // ContentStorageImpl.class, ControlPointImpl.class, CodecDefinitionImpl.class, ContainerDefinitionImpl.class, DataDefinitionImpl.class, InterpolationDefinitionImpl.class, KLVDataDefinitionImpl.class, OperationDefinitionImpl.class, ParameterDefinitionImpl.class, PluginDefinitionImpl.class, TaggedValueDefinitionImpl.class, DictionaryImpl.class, EssenceDataImpl.class, AIFCDescriptorImpl.class, DataEssenceDescriptorImpl.class, CDCIDescriptorImpl.class, MPEGVideoDescriptorImpl.class, RGBADescriptorImpl.class, HTMLDescriptorImpl.class, // MultipleDescriptorImpl.class, SoundDescriptorImpl.class, WAVEPCMDescriptorImpl.class, AES3PCMDescriptorImpl.class, TIFFDescriptorImpl.class, WAVEDescriptorImpl.class, FilmDescriptorImpl.class, AuxiliaryDescriptorImpl.class, ImportDescriptorImpl.class, BWFImportDescriptorImpl.class, RecordingDescriptorImpl.class, TapeDescriptorImpl.class, PrefaceImpl.class, IdentificationImpl.class, KLVDataImpl.class, NetworkLocatorImpl.class, TextLocatorImpl.class, CompositionPackageImpl.class, MaterialPackageImpl.class, SourcePackageImpl.class, EventTrackImpl.class, StaticTrackImpl.class, TimelineTrackImpl.class, ConstantValueImpl.class, VaryingValueImpl.class, RIFFChunkImpl.class, TaggedValueImpl.class }; /** * <p>List of abstract AAF classes that are part of the interchangeable * object hierarchy, i.e. abstract and extending {@link InterchangeObject}.</p> */ public final static Class<?>[] abstractInterchangeable = new Class<?>[] { InterchangeObjectImpl.class, ComponentImpl.class, SegmentImpl.class, EventImpl.class, SourceReferenceSegmentImpl.class, TextClipImpl.class, TimecodeStreamImpl.class, DefinitionObjectImpl.class, DescriptiveFrameworkImpl.class, DescriptiveObjectImpl.class, EssenceDescriptorImpl.class, AAFFileDescriptorImpl.class, PictureDescriptorImpl.class, PhysicalDescriptorImpl.class, LocatorImpl.class, PackageImpl.class, TrackImpl.class, ParameterImpl.class, SubDescriptorImpl.class }; @SuppressWarnings("unchecked") public final static void main( String args[]) throws Exception { MediaEngine.initializeAAF(); AvidFactory.registerAvidExtensions(); List<Class<? extends MediaEntity>> mediaClassList = new ArrayList<Class<? extends MediaEntity>>(); for (Class<?> interchange : interchangeable ) mediaClassList.add((Class<? extends MediaEntity>) interchange); for (Class<?> abstractInterchange : abstractInterchangeable ) mediaClassList.add((Class<? extends MediaEntity>) abstractInterchange); long startTime = System.currentTimeMillis(); generateORM(mediaClassList, "/Users/vizigoth2/tools/apache-openjpa-2.0.1/examples/META-INF/orm.xml"); long endTime = System.currentTimeMillis(); log.info("JPA mapping file generated in " + (endTime - startTime) + "."); } }
37.529213
132
0.723092
88f25cf4034225d003b87c40105062102642f443
1,917
package com.revature.controllers; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.revature.models.Flashcard; import com.revature.repositories.FlashcardRepository; @RestController @RequestMapping("flashcard") public class FlashcardController { @Autowired private FlashcardRepository flashcardDao; @GetMapping public ResponseEntity<List<Flashcard>> findAll() { List<Flashcard> all = flashcardDao.findAll(); return ResponseEntity.ok(all); } @GetMapping("/{id}") public ResponseEntity<Flashcard> findById(@PathVariable("id") int id) { Optional<Flashcard> optional = flashcardDao.findById(id); if(optional.isPresent()) { return ResponseEntity.ok(optional.get()); } return ResponseEntity.noContent().build(); } @PostMapping public ResponseEntity<Flashcard> insert(@RequestBody Flashcard flashcard) { int id = flashcard.getId(); if(id != 0) { return ResponseEntity.badRequest().build(); } flashcardDao.save(flashcard); return ResponseEntity.status(201).body(flashcard); } @DeleteMapping("/{id}") public ResponseEntity<Flashcard> delete(@PathVariable("id") int id) { Optional<Flashcard> option = flashcardDao.findById(id); if(option.isPresent()) { flashcardDao.delete(option.get()); return ResponseEntity.accepted().body(option.get()); } return ResponseEntity.notFound().build(); } }
27.782609
76
0.769953
a698717993fa8b9ea120ac33118c17bc5da0da7c
2,338
package com.daylight.devleague.services.stats.fetch; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import com.daylight.devleague.daos.jira.issues.JiraUserStoryDao; import com.daylight.devleague.domain.jira.issues.JiraUserStory; @ExtendWith(MockitoExtension.class) public class JiraStatsUserStoriesFetchServiceTest { @Mock private JiraUserStoryDao userStoriesDao; @InjectMocks private JiraStatsUserStoriesFetchService service; @BeforeEach() public void before() { service = new JiraStatsUserStoriesFetchService(userStoriesDao); } @Test public void should_call_last_update_after_function_when_startdate_is_not_null() { List<JiraUserStory> stories = new ArrayList<>(); Page<JiraUserStory> storiesPaginated = new PageImpl<>(stories); LocalDateTime localDateTime = LocalDateTime.now(); when(userStoriesDao.findByLastUpdateAfter(eq(localDateTime), any())).thenReturn(storiesPaginated); service.fetch(localDateTime, 0); verify(userStoriesDao, times(1)).findByLastUpdateAfter(eq(localDateTime), any()); verify(userStoriesDao, never()).findAll((Pageable) any()); } @Test public void should_call_find_all_function_when_startdate_is_null() { List<JiraUserStory> stories = new ArrayList<>(); Page<JiraUserStory> storiesPaginated = new PageImpl<>(stories); LocalDateTime localDateTime = null; when(userStoriesDao.findAll((Pageable) any())).thenReturn(storiesPaginated); service.fetch(localDateTime, 0); verify(userStoriesDao, never()).findByLastUpdateAfter(any(), any()); verify(userStoriesDao, times(1)).findAll((Pageable) any()); } }
34.382353
101
0.773738
ba1bb6f6f9a689e4a1a63b19ec99a36da288def0
920
/** * Copyright 2016-2018 Iulian Popa ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package net.whais.Client; interface Cipher { abstract byte type(); abstract int metadataSize(); abstract void encodeFrame( CommunicationFrame frame, Object key); abstract void decodeFrame( CommunicationFrame frame, Object key); abstract Object prepareKey (byte[] key); }
28.75
75
0.73587
7d9eaaf97345e781792ead229b123fcd00fbd21e
4,901
package io.github.cjybyjk.systemupdater; import android.content.SharedPreferences; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.preference.MultiSelectListPreference; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import androidx.preference.PreferenceManager; import java.util.Set; import io.github.cjybyjk.systemupdater.R; public class SettingsActivity extends AppCompatActivity { private final static String TAG = "SettingsActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings_activity); getSupportFragmentManager() .beginTransaction() .replace(R.id.action_settings, new SettingsFragment()) .commit(); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } } public static class SettingsFragment extends PreferenceFragmentCompat { private SharedPreferences mSharedPreferences; private MultiSelectListPreference mPrefAutoDownload; private MultiSelectListPreference mPrefUpdateType; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext()); mPrefAutoDownload = findPreference("auto_download"); mPrefUpdateType = findPreference("update_type"); OnPreferenceChange(mPrefAutoDownload, null); OnPreferenceChange(mPrefUpdateType, null); mPrefAutoDownload.setOnPreferenceChangeListener(new MultiSelectListPreference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { return OnPreferenceChange(preference, newValue); } }); mPrefUpdateType.setOnPreferenceChangeListener(new MultiSelectListPreference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { return OnPreferenceChange(preference, newValue); } }); } @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.root_preferences, rootKey); } private boolean OnPreferenceChange(Preference preference, @Nullable Object newValue) { try { if (preference == mPrefAutoDownload) { Set<String> prefsValue = (Set) newValue; if (prefsValue == null) { prefsValue = mSharedPreferences.getStringSet(preference.getKey(), prefsValue); } if (prefsValue.contains("wifi") && prefsValue.contains("data")) { preference.setSummary(R.string.setting_auto_updates_download_wifi_and_data); } else if (prefsValue.contains("wifi")) { preference.setSummary(R.string.setting_auto_updates_download_wifi); } else if (prefsValue.contains("data")) { preference.setSummary(R.string.setting_auto_updates_download_data); } else { preference.setSummary(R.string.setting_auto_updates_download_never); } } else if (preference == mPrefUpdateType) { Set<String> prefsValue = (Set) newValue; if (prefsValue == null) { prefsValue = mSharedPreferences.getStringSet(preference.getKey(), prefsValue); } if (prefsValue.contains("full") && prefsValue.contains("incremental")) { preference.setSummary(R.string.setting_update_type_all); } else if (prefsValue.contains("full")) { preference.setSummary(R.string.text_update_type_full); } else if (prefsValue.contains("incremental")) { preference.setSummary(R.string.text_update_type_incremental); } else { preference.setSummary(""); } } } catch (NullPointerException e) { e.printStackTrace(); } finally { return true; } } } }
44.153153
121
0.605387
3facba39ae7d61cbf5aa9b1df700f2b01eebd286
20,388
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package open.dolphin.delegater; import java.awt.Dimension; import java.awt.Image; import java.io.StringWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.naming.NamingException; import javax.persistence.PersistenceException; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import open.dolphin.client.ImageEntry; import open.dolphin.project.GlobalSettings; import open.dolphin.dto.DiagnosisSearchSpec; import open.dolphin.dto.DocumentSearchSpec; import open.dolphin.dto.ImageSearchSpec; import open.dolphin.dto.ModuleSearchSpec; import open.dolphin.dto.ObservationSearchSpec; import open.dolphin.infomodel.DocInfoModel; import open.dolphin.infomodel.DocumentModel; import open.dolphin.infomodel.IInfoModel; import open.dolphin.infomodel.KarteBean; import open.dolphin.infomodel.LetterModel; import open.dolphin.infomodel.ModelUtils; import open.dolphin.infomodel.ModuleModel; import open.dolphin.infomodel.ObservationModel; import open.dolphin.infomodel.PatientMemoModel; import open.dolphin.infomodel.RegisteredDiagnosisModel; import open.dolphin.infomodel.SchemaModel; import open.dolphin.infomodel.TouTouLetter; import open.dolphin.infomodel.TouTouReply; import open.dolphin.service.IKarteService; import open.dolphin.utils.DebugDump; /** * * @author tomohiro */ public abstract class DocumentDelegater extends DelegaterErrorHandler { /** * * @return * @throws NamingException */ protected abstract IKarteService getService() throws NamingException; /** * ドキュメントを論理削除する。 * @param pk 論理削除するドキュメントの prmary key * @return 削除件数 */ public int deleteDocument(long pk) { try { return getService().deleteDocument(pk); } catch (Exception e) { dispatchError(getClass(), e, ""); } return 0; } /** * * @param templateName * @return */ public DocumentModel getDocument(final String templateName) { final List<String> templateNames = getDocumentList(null); List<Long> ids = new ArrayList<Long>() { { super.add(new Long(templateNames.indexOf(templateName))); } }; DocumentModel document = null; try { List<DocumentModel> documents = getDocuments(ids); if (!documents.isEmpty()) { document = documents.get(0); } } catch (Exception e) { dispatchError(getClass(), e, ""); } return document; } /** * * @param spec * @return */ public List getDocumentList(DocumentSearchSpec spec) { try { return getService().getDocumentList(spec); } catch (Exception e) { dispatchError(getClass(), e, ""); } return null; } /** * 複数のIDから、それに相当するドキュメントモデル(カルテ)を返す。 * * @param ids IDのリスト * @return ドキュメントモデルのリスト。例外発生時はNULL */ public List<DocumentModel> getDocuments(List<Long> ids) { try { List<DocumentModel> result = getService().getDocuments(ids); for (DocumentModel doc : result) { // Module byte をオブジェクトへ戻す Set<ModuleModel> mc = doc.getModules(); for (ModuleModel module : mc) { module.setModel(module.toInfoModel()); } // JPEG byte をアイコンへ戻す Set<SchemaModel> sc = doc.getSchemas(); if (sc != null) { for (SchemaModel schema : sc) { ImageIcon icon = new ImageIcon(schema.getJpegBytes()); schema.setIcon(icon); } } } return result; } catch (Exception e) { dispatchError(getClass(), e, ""); } return null; } /** * 確定日、適合開始日、記録日、ステータスを DocInfo から DocumentModel(KarteEntry) に移す<br> * カルテコンテンツを lastkarte.log に書き出す * @param docModel カルテコンテンツ * @return 保存したカルテコンテンツの数 */ public long putDocument(DocumentModel docModel) { try { // try { // 確定日、適合開始日、記録日、ステータスを // DocInfo から DocumentModel(KarteEntry) に移す docModel.toPersist(); if (GlobalSettings.isKarteDataDump()) { debugDump(docModel); //カルテコンテンツを lastkarte.log に書き出す } try { return getService().putDocument(docModel); } catch (PersistenceException e) { showErrorMessage("他のマシンで同じカルテを編集している可能性があります。" + System.getProperty("line.separator") + e.getMessage()); dispatchError(getClass(), e, ""); } // } catch (javax.transaction.RollbackException e) { // } } catch (Exception e) { showErrorMessage("サーバ保存時のエラー。" + System.getProperty("line.separator") + e.getMessage()); dispatchError(getClass(), e, ""); } return -1; } /** * 患者のカルテを取得する。 * @param patientPk 患者PK * @param fromDate 履歴の検索開始日 * @return カルテ */ public KarteBean getKarte(long patientPk, Date fromDate) { try { return getService().getKarte(patientPk, fromDate); } catch (Exception e) { showErrorMessage(e.toString()); dispatchError(getClass(), e, ""); } return null; } /** * 文書履歴を検索して返す。 * @param spec DocumentSearchSpec 検索仕様 * @return DocInfoModel の Collection */ public List getDocumentHistory(DocumentSearchSpec spec) { if (spec.getDocType().equals(IInfoModel.DOCTYPE_KARTE)) { return getDocumentList(spec); } else if (spec.getDocType().equals(IInfoModel.DOCTYPE_LETTER)) { return getLetterList(spec); } else if (spec.getDocType().equals(IInfoModel.DOCTYPE_LETTER_REPLY)) { return getLetterReplyList(spec); } return null; } /** * * @param models * @return * @throws SQLException */ private List<LetterModel> getLetterModelsFromModels(List<LetterModel> models) throws SQLException { List<LetterModel> result = new ArrayList<LetterModel>(); LetterModel temp = null; for (LetterModel model : models) { temp = model.toInfoModel(); temp.setId(model.getId()); temp.setBeanBytes(null); result.add(temp); } return result; } /** * * @return */ public List<LetterModel> getRecentLetterModels() { try { List<LetterModel> models = getService().getRecentLetterModels("TOUTOU"); return getLetterModelsFromModels(models); } catch (Exception ex) { dispatchError(getClass(), ex, ""); } return null; } /** * * @param letterPkL * @return */ public List<LetterModel> getRecentLetterModels(final long letterPkL) { try { List<LetterModel> models = getService().getRecentLetterModels(letterPkL, "TOUTOU"); return getLetterModelsFromModels(models); } catch (Exception ex) { dispatchError(getClass(), ex, ""); } return null; } /** * * @param spec * @return */ private List<DocInfoModel> getLetterList(DocumentSearchSpec spec) { List result = new ArrayList<DocInfoModel>(); try { List<LetterModel> models = (List<LetterModel>) getService().getLetterList(spec.getKarteId(), "TOUTOU"); for (LetterModel model : models) { TouTouLetter letter = (TouTouLetter) model; DocInfoModel docInfo = new DocInfoModel(); docInfo.setDocPk(letter.getId()); docInfo.setDocType(IInfoModel.DOCTYPE_LETTER); docInfo.setDocId(String.valueOf(letter.getId())); docInfo.setConfirmDate(letter.getConfirmed()); docInfo.setFirstConfirmDate(letter.getConfirmed()); docInfo.setTitle(letter.getConsultantHospital()); result.add(docInfo); } } catch (Exception e) { dispatchError(getClass(), e, ""); } return result; } /** * * @return */ public List<LetterModel> getRecentLetterReplyModels() { try { List<LetterModel> models = getService().getRecentLetterModels("TOUTOU_REPLY"); return getLetterModelsFromModels(models); } catch (Exception ex) { dispatchError(getClass(), ex, ""); } return null; } /** * * @param letterPkL * @return */ public List<LetterModel> getRecentLetterReplyModels(final long letterPkL) { try { List<LetterModel> models = getService().getRecentLetterModels(letterPkL, "TOUTOU_REPLY"); return getLetterModelsFromModels(models); } catch (Exception ex) { dispatchError(getClass(), ex, ""); } return null; } /** * * @param spec * @return */ private List<DocInfoModel> getLetterReplyList(DocumentSearchSpec spec) { List result = new ArrayList<DocInfoModel>(); try { List<LetterModel> models = (List<LetterModel>) getService().getLetterList(spec.getKarteId(), "TOUTOU_REPLY"); for (LetterModel model : models) { TouTouReply letter = (TouTouReply) model; DocInfoModel docInfo = new DocInfoModel(); docInfo.setDocPk(letter.getId()); docInfo.setDocType(IInfoModel.DOCTYPE_LETTER_REPLY); docInfo.setDocId(String.valueOf(letter.getId())); docInfo.setConfirmDate(letter.getConfirmed()); docInfo.setFirstConfirmDate(letter.getConfirmed()); docInfo.setTitle(letter.getClientHospital()); result.add(docInfo); } } catch (Exception e) { showErrorMessage(e.toString()); dispatchError(getClass(), e, ""); } return result; } /** * * @param letterPk * @return */ public LetterModel getLetter(long letterPk) { LetterModel result = null; try { LetterModel model = getService().getLetter(letterPk); result = model.toInfoModel(); result.setId(model.getId()); result.setBeanBytes(null); } catch (Exception e) { dispatchError(getClass(), e, ""); } return result; } /** * * @param letterPk * @return */ public LetterModel getLetterReply(long letterPk) { LetterModel result = null; try { LetterModel model = getService().getLetterReply(letterPk); result = model.toInfoModel(); result.setId(model.getId()); result.setBeanBytes(null); } catch (Exception e) { dispatchError(getClass(), e, ""); } return result; } /** * 文書履歴のタイトルを変更する。 * @param docInfo * @return 変更した件数 */ public int updateTitle(DocInfoModel docInfo) { try { return getService().updateTitle(docInfo.getDocPk(), docInfo.getTitle()); } catch (Exception e) { dispatchError(getClass(), e, ""); } return 0; } /** * Moduleを検索して返す。 * @param spec ModuleSearchSpec 検索仕様 * @return Module の Collection */ public List getModuleList(ModuleSearchSpec spec) { List<List> result = null; try { result = getService().getModules(spec); for (List list : result) { for (Iterator iter = list.iterator(); iter.hasNext();) { ModuleModel module = (ModuleModel) iter.next(); module.setModel(module.toInfoModel()); } } } catch (Exception e) { dispatchError(getClass(), e, ""); } return result; } /** * 全期間の Module を返します * @param spec ModuleSearchSpec 検索仕様 * @return Module の Collection */ public List getAllModuleList(ModuleSearchSpec spec) { List<ModuleModel> result = null; try { result = getService().getAllModule(spec); for (ModuleModel module : result) { module.setModel(module.toInfoModel()); } } catch (Exception e) { dispatchError(getClass(), e, ""); } return result; } /** * イメージを取得する。 * @param id 画像のId * @return SchemaModel */ public SchemaModel getImage(long id) { SchemaModel result = null; try { result = getService().getImage(id); if (result != null) { byte[] bytes = result.getJpegBytes(); ImageIcon icon = new ImageIcon(bytes); if (icon != null) { result.setIcon(icon); } } } catch (Exception e) { dispatchError(getClass(), e, ""); } return result; } /** * Imageを検索して返す。 * @param spec ImageSearchSpec 検索仕様 * @return Imageリストのリスト */ public List getImageList(ImageSearchSpec spec) { List<List> result = new ArrayList<List>(3); try { List images = getService().getImages(spec); // 検索結果 for (Iterator iter = images.iterator(); iter.hasNext();) { // 抽出期間毎のリスト List periodList = (List) iter.next(); // 抽出期間毎のリスト List<ImageEntry> el = new ArrayList<ImageEntry>(); // ImageEntry 用のリスト for (Iterator iter2 = periodList.iterator(); iter2.hasNext();) { // 抽出期間をイテレートする // シェーマモデルをエントリに変換しリストに加える SchemaModel model = (SchemaModel) iter2.next(); ImageEntry entry = getImageEntry(model, spec.getIconSize()); el.add(entry); } // リターンリストへ追加する result.add(el); } } catch (Exception e) { dispatchError(getClass(), e, ""); } return result; } /** * シェーマモデルをエントリに変換する。 * @param schema シェーマモデル * @param iconSize アイコンのサイズ * @return ImageEntry */ private ImageEntry getImageEntry(SchemaModel schema, Dimension iconSize) { ImageEntry result = new ImageEntry(); result.setId(schema.getId()); //model.setConfirmDate(ModelUtils.getDateTimeAsString(schema.getConfirmDate())); // First? result.setConfirmDate(ModelUtils.getDateTimeAsString(schema.getConfirmed())); // First? result.setContentType(schema.getExtRef().getContentType()); result.setTitle(schema.getExtRef().getTitle()); result.setMedicalRole(schema.getExtRef().getMedicalRole()); byte[] bytes = schema.getJpegBytes(); // Create ImageIcon ImageIcon icon = new ImageIcon(bytes); if (icon != null) { result.setImageIcon(adjustImageSize(icon, iconSize)); } return result; } /** * * @param beans * @return */ public List<Long> putDiagnosis(List<RegisteredDiagnosisModel> beans) { try { return getService().addDiagnosis(beans); } catch (Exception e) { dispatchError(getClass(), e, ""); } return null; } /** * * @param beans * @return */ public int updateDiagnosis(List<RegisteredDiagnosisModel> beans) { try { return getService().updateDiagnosis(beans); } catch (Exception e) { dispatchError(getClass(), e, ""); } return 0; } /** * * @param ids * @return */ public int removeDiagnosis(List<Long> ids) { try { return getService().removeDiagnosis(ids); } catch (Exception e) { dispatchError(getClass(), e, ""); } return 0; } /** * Diagnosisを検索して返す。 * @param spec DiagnosisSearchSpec 検索仕様 * @return DiagnosisModel の Collection */ public List<RegisteredDiagnosisModel> getDiagnosisList(DiagnosisSearchSpec spec) { try { return getService().getDiagnosis(spec); } catch (Exception e) { dispatchError(getClass(), e, ""); } return null; } /** * * @param observations * @return */ public List<Long> addObservations(List<ObservationModel> observations) { try { return getService().addObservations(observations); } catch (Exception e) { dispatchError(getClass(), e, ""); } return null; } /** * * @param spec * @return */ public List<ObservationModel> getObservations(ObservationSearchSpec spec) { try { return getService().getObservations(spec); } catch (Exception e) { dispatchError(getClass(), e, ""); } return null; } /** * * @param observations * @return */ public int updateObservations(List<ObservationModel> observations) { try { return getService().updateObservations(observations); } catch (Exception e) { dispatchError(getClass(), e, ""); } return 0; } /** * * @param ids * @return */ public int removeObservations(List<Long> ids) { try { return getService().removeObservations(ids); } catch (Exception e) { dispatchError(getClass(), e, ""); } return 0; } /** * * @param pm * @return */ public int updatePatientMemo(PatientMemoModel pm) { try { return getService().updatePatientMemo(pm); } catch (Exception e) { dispatchError(getClass(), e, ""); } return 0; } /** * * @param spec * @return */ public List getAppoinmentList(ModuleSearchSpec spec) { try { return getService().getAppointmentList(spec); } catch (Exception e) { dispatchError(getClass(), e, ""); } return null; } /** * * @param icon * @param dim * @return */ private ImageIcon adjustImageSize(ImageIcon icon, Dimension dim) { if ((icon.getIconHeight() > dim.height) || (icon.getIconWidth() > dim.width)) { Image img = icon.getImage(); float hRatio = (float) icon.getIconHeight() / dim.height; float wRatio = (float) icon.getIconWidth() / dim.width; int h, w; if (hRatio > wRatio) { h = dim.height; w = (int) (icon.getIconWidth() / hRatio); } else { w = dim.width; h = (int) (icon.getIconHeight() / wRatio); } img = img.getScaledInstance(w, h, Image.SCALE_SMOOTH); return new ImageIcon(img); } else { return icon; } } /** * * @param message */ private void showErrorMessage(String message) { JOptionPane.showMessageDialog(null, message, "エラー", JOptionPane.ERROR_MESSAGE); } /** * カルテコンテンツをlastkarte.log に書き出す * @param docModel カルテコンテンツ */ private void debugDump(DocumentModel docModel) { StringWriter writer = new StringWriter(); try { docModel.serialize(writer); DebugDump.dumpToFile("lastkarte.log", writer.toString()); } catch (Exception e) { dispatchError(getClass(), e, ""); } finally { try { writer.close(); } catch (Exception e) { dispatchError(getClass(), e, ""); } } } }
29.462428
121
0.552972
3d93bb37a2ee94815bd21c43f18d63a9e55d2c1a
5,132
package org.swaggertools.core.targets.server; import org.swaggertools.core.model.ApiDefinition; import org.swaggertools.core.model.Operation; import org.swaggertools.core.model.Parameter; import org.swaggertools.core.model.ParameterKind; import org.swaggertools.core.run.JavaFileWriter; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; public class JaxRsBuilder extends ServerBuilder { private static final String JAX_RS = "javax.ws.rs"; private static final String JAX_RS_CORE = "javax.ws.rs.core"; private static final String JAX_SSE = "javax.ws.rs.sse"; private static final ClassName PATH = ClassName.get(JAX_RS, "Path"); private static final ClassName CONSUMES = ClassName.get(JAX_RS, "Consumes"); private static final ClassName PRODUCES = ClassName.get(JAX_RS, "Produces"); private static final ClassName REQUEST_PARAM = ClassName.get(JAX_RS, "QueryParam"); private static final ClassName HEADER_PARAM = ClassName.get(JAX_RS, "HeaderParam"); private static final ClassName PATH_VARIABLE = ClassName.get(JAX_RS, "PathParam"); private static final ClassName CONTEXT = ClassName.get(JAX_RS_CORE, "Context"); private static final ClassName SSE_EVENT_SINK = ClassName.get(JAX_SSE, "SseEventSink"); private static final ClassName SSE = ClassName.get(JAX_SSE, "Sse"); public JaxRsBuilder(ApiDefinition apiDefinition, JavaFileWriter writer, ServerOptions options) { super(apiDefinition, writer, options); } @Override protected void annotateClass(TypeSpec.Builder builder) { if (apiDefinition.getBasePath() != null) { builder.addAnnotation(AnnotationSpec.builder(PATH) .addMember("value", "$S", apiDefinition.getBasePath()) .build() ); builder.addAnnotation(AnnotationSpec.builder(CONSUMES).addMember("value", "$S", "application/json").build()); builder.addAnnotation(AnnotationSpec.builder(PRODUCES).addMember("value", "$S", "application/json").build()); } } @Override protected void annotateMethod(MethodSpec.Builder builder, Operation operation) { builder.addAnnotation(AnnotationSpec.builder(ClassName.get(JAX_RS, operation.getMethod().name())).build()); builder.addAnnotation(AnnotationSpec.builder(PATH) .addMember("value", "$S", operation.getPath()) .build() ); if (operation.getResponseMediaType() != null) { builder.addAnnotation(AnnotationSpec.builder(PRODUCES) .addMember("value", "$S", operation.getResponseMediaType()) .build() ); } } @Override protected void annotateParameter(ParameterSpec.Builder paramBuilder, Parameter parameter) { super.annotateParameter(paramBuilder, parameter); if (parameter.getKind() != ParameterKind.BODY) { ClassName inType = getParameterAnnotationClass(parameter.getKind()); AnnotationSpec.Builder anno = AnnotationSpec.builder(inType) .addMember("value", "$S", parameter.getName()); paramBuilder.addAnnotation(anno.build()); } } private ClassName getParameterAnnotationClass(ParameterKind kind) { if (kind == ParameterKind.PATH) { return PATH_VARIABLE; } else if (kind == ParameterKind.QUERY) { return REQUEST_PARAM; } else if (kind == ParameterKind.HEADER) { return HEADER_PARAM; } else { throw new IllegalArgumentException("Unknown parameter kind: " + kind); } } @Override protected void addResponse(MethodSpec.Builder builder, Operation operationInfo) { if (options.reactive) { throw new IllegalArgumentException("JaxRS dialect does not support reactive API"); } else { if (EVENT_STREAM.equals(operationInfo.getResponseMediaType())) { builder.returns(TypeName.VOID.unbox()); } else { if (operationInfo.getResponseSchema() != null) { builder.returns(schemaMapper.getType(operationInfo.getResponseSchema(), false)); } } } } @Override protected void addParameters(MethodSpec.Builder builder, Operation operationInfo) { super.addParameters(builder, operationInfo); if (EVENT_STREAM.equals(operationInfo.getResponseMediaType())) { ParameterSpec.Builder paramBuilder = ParameterSpec.builder(SSE_EVENT_SINK, "sseEventSink"); paramBuilder.addAnnotation(AnnotationSpec.builder(CONTEXT).build()); builder.addParameter(paramBuilder.build()); paramBuilder = ParameterSpec.builder(SSE, "sse"); paramBuilder.addAnnotation(AnnotationSpec.builder(CONTEXT).build()); builder.addParameter(paramBuilder.build()); } } }
45.017544
121
0.674786
326b61dbac4dd0c0bbf63d77453f7b238de43e72
2,071
package org.lappsgrid.gate.cli.abner; import gate.util.Files; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import static org.junit.Assert.*; /** * */ @Ignore public class FileTests { @Test public void readString() throws IOException { File file = new File("/Users/suderman/Workspaces/IntelliJ/org.lappsgrid.pubannotation/pom.xml"); String text = Files.getString(file); System.out.println(text); } @Test public void streamTests() { assertTrue(System.out instanceof OutputStream); } @Test public void blockingTest() throws InterruptedException { System.out.println("FileTests.blockingTest"); BlockingQueue<Object> q = new ArrayBlockingQueue<>(10, false); CountDownLatch latch = new CountDownLatch(1); Blocking worker = new Blocking(q, latch); // Thread thread = new Thread(worker); worker.start(); System.out.println("Waiting for awhile."); Thread.sleep(5000); System.out.println("Attempting to halt the worker."); worker.halt(); System.out.println("Waiting for the latch"); latch.await(); System.out.println("Done."); } } class Blocking extends Thread { private BlockingQueue<Object> q; private CountDownLatch latch; private boolean running; public Blocking(BlockingQueue<Object> q, CountDownLatch latch) { this.q = q; this.latch = latch; this.running = false; } public void run() { System.out.println("Staring blocking thread."); running = true; while (running) { try { Object o = q.take(); } catch (InterruptedException e) { System.out.println("Thread was interrupted."); Thread.currentThread().interrupt(); running = false; } } latch.countDown(); System.out.println("Thread terminated."); } public void halt() { System.out.println("Halting thread."); running = false; System.out.println("Notifying the queue."); this.interrupt(); } }
23.534091
98
0.716079
1eee9eda2080fa834ba55afbfb72e680b029657e
1,236
package com.tentone.wallrunner.input; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.tentone.wallrunner.Global; public class Button { private Sprite sprite; public Button(int texture,float pos_x,float pos_y,float size_x,float size_y) { sprite = new Sprite(Global.texture[texture]); sprite.setPosition(pos_x, pos_y); sprite.setSize(size_x,size_y); } public Button(Sprite sprite,float pos_x,float pos_y,float size_x,float size_y) { this.sprite=sprite; this.sprite.setOrigin(0,0); this.sprite.setPosition(pos_x, pos_y); this.sprite.setSize(size_x, size_y); } public boolean isPressed() { float x=Global.camera.pos.x+(Global.touch_x-Global.camera.size_half.x),y=Global.camera.pos.y+(Global.touch_y-Global.camera.size_half.y); return (y>sprite.getY() && y<(sprite.getY()+sprite.getHeight())) && (x>sprite.getX() && x<(sprite.getX()+sprite.getWidth())); } public boolean isPressed(float x,float y) { return (y>sprite.getY() && y<(sprite.getY()+sprite.getHeight())) && (x>sprite.getX() && x<(sprite.getX()+sprite.getWidth())); } public void draw(SpriteBatch batch) { sprite.draw(batch); } }
29.428571
139
0.696602
9d34aeebd01efebb75acf03ce2ae67597fb945d2
1,148
import java.util.List; public interface CommandVisitors{ //Arithmetic Commands List<String> visit(Commands.AddCommand command); List<String> visit(Commands.SubCommand command); List<String> visit(Commands.NegCommand command); List<String> visit(Commands.EqualCommand command); List<String> visit(Commands.GreaterThanCommand command); List<String> visit(Commands.LessThanCommand command); List<String> visit(Commands.AndCommand command); List<String> visit(Commands.OrCommand command); List<String> visit(Commands.NotCommand command); //Memory Access Commands List<String> visit(Commands.PushCommand command); List<String> visit(Commands.PopCommand command); //Branch Commands List<String> visit(Commands.LabelCommand command); List<String> visit(Commands.GotoCommand command); List<String> visit(Commands.IfGotoCommand command); //Function Commands List<String> visit(Commands.FunctionCommand command); List<String> visit(Commands.CallCommand command); List<String> visit(Commands.ReturnCommand command); List<String> visit(Commands.InitCommand command); }
39.586207
60
0.755226
8fbd1148192949f7bff2921d0ff38d50a45d55b4
5,361
package com.shagaba.jacksync.diff.strategy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.shagaba.jacksync.exception.DiffProcessingException; import com.shagaba.jacksync.operation.MergeOperation; import com.shagaba.jacksync.operation.PatchOperation; import com.shagaba.jacksync.operation.RemoveOperation; import com.shagaba.jacksync.utils.JacksonUtils; public class MergeOperationDiffStrategy implements DiffStrategy { protected DiffStrategy diffStrategy; public MergeOperationDiffStrategy() { diffStrategy = new SimpleDiffStrategy(); } /** * * @param sourceJsonNode * @param targetJsonNode * @return * @throws DiffProcessingException */ @Override public List<PatchOperation> diff(JsonNode sourceJsonNode, JsonNode targetJsonNode) throws DiffProcessingException { List<PatchOperation> operations = diffStrategy.diff(sourceJsonNode, targetJsonNode); return optimize(targetJsonNode, operations); } protected class JsonPointerData { private List<String> fieldNames; private List<PatchOperation> operations; /** * */ public JsonPointerData() { fieldNames = new ArrayList<>(); operations = new ArrayList<>(); } /** * @return the fieldNames */ public List<String> getFieldNames() { return fieldNames; } /** * @return the operations */ public List<PatchOperation> getOperations() { return operations; } } /** * * @param targetJsonNode * @param operations * @return */ protected List<PatchOperation> optimize(JsonNode targetJsonNode, List<PatchOperation> operations) { List<PatchOperation> optimizedOperations = new ArrayList<>(); Map<JsonPointer, JsonPointerData> parentToJsonPointerDataMap = new HashMap<>(); for (PatchOperation operation: operations) { JsonNode pathJsonNode = JacksonUtils.locateHeadContainer(targetJsonNode, operation.getPath()); if (pathJsonNode.isObject()) { if (operation.getClass() == RemoveOperation.class) { optimizedOperations.add(operation); } else { JsonPointer parentPointer = operation.getPath().head(); if (!parentToJsonPointerDataMap.containsKey(parentPointer)) { parentToJsonPointerDataMap.put(parentPointer, new JsonPointerData()); } parentToJsonPointerDataMap.get(parentPointer).getOperations().add(operation); parentToJsonPointerDataMap.get(parentPointer).getFieldNames().add(JacksonUtils.lastFieldName(operation.getPath())); } } else if (pathJsonNode.isArray()) { optimizedOperations.add(operation); } } // merge process must start handling arrays optimizedOperations.addAll(optimize(targetJsonNode, parentToJsonPointerDataMap)); return optimizedOperations; } /** * * @param targetJsonNode * @param parentToJsonPointerDataMap * @return */ protected List<PatchOperation> optimize(JsonNode targetJsonNode, Map<JsonPointer, JsonPointerData> parentToJsonPointerDataMap) { List<PatchOperation> optimizedOperations = new ArrayList<>(); Map<JsonPointer, MergeOperation> parentToMergeOperation = new HashMap<>(); for (JsonPointer parentPath : parentToJsonPointerDataMap.keySet()) { JsonPointerData jsonPointerData = parentToJsonPointerDataMap.get(parentPath); JsonNode parentJsonNode = JacksonUtils.locateContainer(targetJsonNode, parentPath); ObjectNode parentObjectNode = (ObjectNode) parentJsonNode.deepCopy(); parentObjectNode.retain(jsonPointerData.getFieldNames()); MergeOperation mergeOperation = new MergeOperation(parentPath, parentObjectNode); mergeOperation = parentObjectMergeOperation(targetJsonNode, mergeOperation); MergeOperation parentMergeOperation = parentToMergeOperation.get(mergeOperation.getPath()); if (parentMergeOperation == null) { parentToMergeOperation.put(mergeOperation.getPath(), mergeOperation); } else { JsonNode mergedJsonNode = new MergeOperation(parentMergeOperation.getValue()).apply(mergeOperation.getValue()); parentMergeOperation.setValue(mergedJsonNode); } } if (!parentToMergeOperation.isEmpty()) { optimizedOperations.addAll(parentToMergeOperation.values()); } return optimizedOperations; } /** * * @param targetJsonNode * @param mergeOperation * @return */ protected MergeOperation parentObjectMergeOperation(JsonNode targetJsonNode, MergeOperation mergeOperation) { if (JacksonUtils.isRoot(mergeOperation.getPath())) { return mergeOperation; } JsonNode parentJsonNode = JacksonUtils.locateHeadContainer(targetJsonNode, mergeOperation.getPath()); if (parentJsonNode.isObject()) { ObjectNode parentObjectNode = (ObjectNode) parentJsonNode.deepCopy(); parentObjectNode.removeAll(); parentObjectNode.set(JacksonUtils.lastFieldName(mergeOperation.getPath()), mergeOperation.getValue()); MergeOperation parentMergeOperation = new MergeOperation(mergeOperation.getPath().head(), parentObjectNode); return parentObjectMergeOperation(targetJsonNode, parentMergeOperation); } else { return mergeOperation; } } }
35.269737
130
0.744637
59c26a1c3be1f3601c35547ad318c29331ce42be
595
package yuan.sim.vo.document; import lombok.Data; import java.util.List; /** * @QQ交流群: 648741281 * @Email: [email protected] * @微信: londu19930418 * @Author: Simon.Mr * @Created 2020/9/30 */ @Data public class DocumentField { /** * 字段名称 */ private String name; /** * 字段描述 */ private String desc; /** * 字段类型 */ private String type; /** * 对象类型的参数文档模型 */ private List<DocumentEntity> docs; /** * 是否必须 */ private boolean require; /** * 默认值 */ private String defaultValue; }
12.659574
38
0.539496
e4ff102cdc318e42cc077833cf2958430e02f9a2
2,719
package org.logstash.beats; import io.netty.buffer.ByteBuf; import io.netty.buffer.PooledByteBufAllocator; import java.util.Iterator; /** * Implementation of {@link Batch} for the v2 protocol backed by ByteBuf. *must* be released after use. */ public class V2Batch implements Batch { private ByteBuf internalBuffer = PooledByteBufAllocator.DEFAULT.buffer(); private int written = 0; private int read = 0; private static final int SIZE_OF_INT = 4; private int batchSize; private int highestSequence = -1; public void setProtocol(byte protocol){ if (protocol != Protocol.VERSION_2){ throw new IllegalArgumentException("Only version 2 protocol is supported"); } } @Override public byte getProtocol() { return Protocol.VERSION_2; } public Iterator<Message> iterator(){ internalBuffer.resetReaderIndex(); return new Iterator<Message>() { @Override public boolean hasNext() { return read < written; } @Override public Message next() { int sequenceNumber = internalBuffer.readInt(); int readableBytes = internalBuffer.readInt(); Message message = new Message(sequenceNumber, internalBuffer.slice(internalBuffer.readerIndex(), readableBytes)); internalBuffer.readerIndex(internalBuffer.readerIndex() + readableBytes); message.setBatch(V2Batch.this); read++; return message; } }; } @Override public int getBatchSize() { return batchSize; } @Override public void setBatchSize(final int batchSize) { this.batchSize = batchSize; } @Override public int size() { return written; } @Override public boolean isEmpty() { return written == 0; } @Override public boolean isComplete() { return written == batchSize; } @Override public int getHighestSequence(){ return highestSequence; } /** * Adds a message to the batch, which will be constructed into an actual {@link Message} lazily. * @param sequenceNumber sequence number of the message within the batch * @param buffer A ByteBuf pointing to serialized JSon * @param size size of the serialized Json */ void addMessage(int sequenceNumber, ByteBuf buffer, int size) { written++; if (internalBuffer.writableBytes() < size + (2 * SIZE_OF_INT)){ internalBuffer.capacity(internalBuffer.capacity() + size + (2 * SIZE_OF_INT)); } internalBuffer.writeInt(sequenceNumber); internalBuffer.writeInt(size); buffer.readBytes(internalBuffer, size); if (sequenceNumber > highestSequence){ highestSequence = sequenceNumber; } } @Override public void release() { internalBuffer.release(); } }
25.895238
121
0.687753
40a5db16cac7a00f57077671f105c1b65aa967ae
772
package com.github.nohum.localezenmode.util; import android.content.Context; import com.github.nohum.localezenmode.R; import com.github.nohum.localezenmode.ZenModeNotificationService; public class BlurbHelper { public static String modeToString(Context context, int mode) { switch (mode) { case ZenModeNotificationService.INTERRUPTION_FILTER_ALL: return context.getString(R.string.current_state_all); case ZenModeNotificationService.INTERRUPTION_FILTER_PRIORITY: return context.getString(R.string.current_state_priority); case ZenModeNotificationService.INTERRUPTION_FILTER_NONE: return context.getString(R.string.current_state_none); } return context.getString(R.string.current_state_unknown); } }
38.6
132
0.777202
90070e2ec8cd9749f46daf2655ac27591f723c44
5,224
package com.jlkj.project.ws.mapper; import com.jlkj.project.ws.dto.WsTowerCraneEquipmentWorkDetailsDTO; import com.jlkj.project.ws.dto.WsTowerCraneProjectMonitoringDetailsDTO; import com.jlkj.project.ws.dto.WsTowerCraneProjectRealTimeMonitoringDTO; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 塔机监测 Mapper接口 * * @author gaowei * @date 2020-07-2 */ public interface WsTowerCraneProjectRealTimeMonitoringMapper { WsTowerCraneProjectRealTimeMonitoringDTO selectTowerCraneOnSiteNumQuery(WsTowerCraneProjectRealTimeMonitoringDTO wsTowerCraneProjectRealTimeMonitoringDTO); List<WsTowerCraneProjectRealTimeMonitoringDTO> selectTowerCraneOnSiteNumQueryList(WsTowerCraneProjectRealTimeMonitoringDTO wsTowerCraneProjectRealTimeMonitoringDTO); WsTowerCraneProjectRealTimeMonitoringDTO selectMonitoringEquipmentNosOnlineRate(String[] monitoringEquipmentNos); WsTowerCraneProjectRealTimeMonitoringDTO selectMonitoringEquipmentNosViolationTodayNum(String[] monitoringEquipmentNos); List<WsTowerCraneProjectRealTimeMonitoringDTO> selectProjectTowerCraneList(WsTowerCraneProjectRealTimeMonitoringDTO wsTowerCraneProjectRealTimeMonitoringDTO); WsTowerCraneProjectRealTimeMonitoringDTO selectProjectfieldLayout(WsTowerCraneProjectRealTimeMonitoringDTO wsTowerCraneProjectRealTimeMonitoringDTO); WsTowerCraneProjectRealTimeMonitoringDTO selectTowerCraneEquipmentWorkDetailsQuery(String monitoringEquipmentNo); WsTowerCraneProjectRealTimeMonitoringDTO selectWarningStatusOrAlarmStatusQuery(String monitoringEquipmentNo); WsTowerCraneProjectRealTimeMonitoringDTO selectTowerCraneEquipmentFaceNoQuery(String faceId); WsTowerCraneProjectRealTimeMonitoringDTO selectTowerCraneEquipmentIdCardNoQuery(String faceNo); WsTowerCraneProjectRealTimeMonitoringDTO selectTowerCraneEquipmentPhotoAddressQuery(String idCardNo, Integer projectId); WsTowerCraneProjectMonitoringDetailsDTO selectProjectTowerCraneInformation(WsTowerCraneProjectMonitoringDetailsDTO wsTowerCraneProjectMonitoringDetailsDTO); WsTowerCraneProjectMonitoringDetailsDTO selectProjectMonitorrRealTimeData(@Param("monitoringEquipmentNo") String monitoringEquipmentNo); WsTowerCraneProjectMonitoringDetailsDTO selectProjectMonitorrRealTimeMaxMinData(String monitoringEquipmentNo); WsTowerCraneProjectMonitoringDetailsDTO selectTowerCraneDriverInformationQuery(String idCardNo, Integer projectId); WsTowerCraneProjectMonitoringDetailsDTO selectProjectMonitorrForewarningData(@Param("monitoringEquipmentNo") String monitoringEquipmentNo); WsTowerCraneProjectMonitoringDetailsDTO selectEquipmentOnlineStatusData(String monitoringEquipmentNo); List<WsTowerCraneProjectMonitoringDetailsDTO> selectEquipmentWorkCycleRecordOneList(String monitoringEquipmentNo); List<WsTowerCraneProjectMonitoringDetailsDTO> selectEquipmentWorkCycleRecordfifteenList(String monitoringEquipmentNo); List<WsTowerCraneProjectMonitoringDetailsDTO> selectEquipmentWorkCycleDetails(String monitoringEquipmentNo, String searchTime); List<WsTowerCraneProjectMonitoringDetailsDTO> selectEquipmentWorkDriverInformation(String faceNo, String searchTime, String driversName); List<WsTowerCraneProjectMonitoringDetailsDTO> selectProjectMonitorrRealTimeAlarmData(@Param("monitoringEquipmentNo") String monitoringEquipmentNo); WsTowerCraneProjectMonitoringDetailsDTO selectProjectMonitorrWarningTodayData(@Param("monitoringEquipmentNo") String monitoringEquipmentNo); WsTowerCraneProjectRealTimeMonitoringDTO selectTowerCraneEquipmentNameQuery(String faceNo); List<WsTowerCraneProjectRealTimeMonitoringDTO> selectDetailsProjectViolationQuerySeven(String monitoringEquipmentNo); List<WsTowerCraneProjectRealTimeMonitoringDTO> selectProjectTowerCraneDetailsList(WsTowerCraneProjectRealTimeMonitoringDTO wsTowerCraneProjectRealTimeMonitoringDTO); List<WsTowerCraneProjectRealTimeMonitoringDTO> selectDetailsProjectViolationQueryThirty(String monitoringEquipmentNo); List<WsTowerCraneProjectRealTimeMonitoringDTO> selectDetailsProjectViolationQuerySame(String monitoringEquipmentNo, String conditionsDate); WsTowerCraneProjectMonitoringDetailsDTO selectRecentViolationRateData(@Param("monitoringEquipmentNo") String monitoringEquipmentNo); WsTowerCraneProjectMonitoringDetailsDTO selectYesterdayHoistingData(@Param("monitoringEquipmentNo") String monitoringEquipmentNo); WsTowerCraneProjectMonitoringDetailsDTO selectTodayHoistingData(@Param("monitoringEquipmentNo") String monitoringEquipmentNo); List<WsTowerCraneProjectMonitoringDetailsDTO> selectEquipmentStatusAnalysis(WsTowerCraneProjectMonitoringDetailsDTO wsTowerCraneProjectMonitoringDetailsDTO); List<WsTowerCraneProjectMonitoringDetailsDTO> selectHoistingCycleSeven(WsTowerCraneProjectMonitoringDetailsDTO wsTowerCraneProjectMonitoringDetailsDTO); List<WsTowerCraneProjectMonitoringDetailsDTO> selectHoistingCycleFifteen(WsTowerCraneProjectMonitoringDetailsDTO wsTowerCraneProjectMonitoringDetailsDTO); List<WsTowerCraneProjectMonitoringDetailsDTO> selectHoistingCycleThirty(WsTowerCraneProjectMonitoringDetailsDTO wsTowerCraneProjectMonitoringDetailsDTO); }
58.696629
169
0.89242
82ea2381fa610b007d1e0ef6757a18d219f1b81a
24,784
package monet.decoder.gif; import android.annotation.SuppressLint; import java.io.IOException; import java.nio.charset.Charset; import javax.annotation.Nullable; import okio.Buffer; import okio.BufferedSource; import okio.ByteString; import okio.Source; import okio.Timeout; public final class GifSource implements Source { // Outer states for the GIF parser. private static final byte SECTION_HEADER = 0; private static final byte SECTION_BODY = 1; private static final byte SECTION_DONE = 2; // Inner states for each GIF frame. private static final byte FRAME_HEADER = 0; private static final byte FRAME_DATA = 1; private static final ByteString SIGNATURE = ByteString.encodeUtf8("GIF"); // Netscape extension private static final ByteString APPLICATION_NETSCAPE = ByteString.encodeString("NETSCAPE2.0", Charset.forName("US-ASCII")); // Frame disposal methods private static final int DISPOSAL_METHOD_UNKNOWN = 0; private static final int DISPOSAL_METHOD_LEAVE = 1; private static final int DISPOSAL_METHOD_BACKGROUND = 2; private static final int DISPOSAL_METHOD_RESTORE = 3; // Decoding parameters private static final int MAX_STACK_SIZE = 4096; // Work buffers private Buffer indexData; private short[] prefix; private byte[] suffix; private byte[] pixelStack; private final BufferedSource source; private int section = SECTION_HEADER; private int frameSection = FRAME_HEADER; private Header header; private Frame frame; private ByteString restoreCanvas; private int pos = 0; GifSource(BufferedSource source) { this.source = source; } @Override public long read(Buffer sink, long byteCount) throws IOException { if (byteCount < 0) throw new IllegalArgumentException("byteCount < 0 :" + byteCount); if (byteCount == 0) return 0; if (section == SECTION_HEADER) { header = readHeader(); section = SECTION_BODY; } if (section == SECTION_BODY) { if (frame == null || pos >= frame.pixelData.size()) { frameSection = FRAME_HEADER; frame = readFrame(); pos = 0; } if (frame == null) { section = SECTION_DONE; return -1; } int bytes = (int) Math.min(frame.pixelData.size() - pos, byteCount); sink.write(frame.pixelData.substring(pos, bytes)); pos = bytes; return bytes; } if (!source.exhausted()) { throw new IOException("gif read finished without exhausting source"); } section = SECTION_DONE; return -1; } public Header readHeader() throws IOException { // Signature // // 7 6 5 4 3 2 1 0 Field Name Type // +---------------+ // 0 | | Signature 3 Bytes // +- -+ // 1 | | // +- -+ // 2 | | // +---------------+ // 3 | | Version 3 Bytes // +- -+ // 4 | | // +- -+ // 5 | | // +---------------+ source.require(6); if (!source.rangeEquals(0, SIGNATURE)) { throw new UnsupportedFormatException("GIF signature not found"); } source.skip(6); // Logical Screen Descriptor // // 7 6 5 4 3 2 1 0 Field Name Type // +---------------+ // 0 | | Logical Screen Width Unsigned // +- -+ // 1 | | // +---------------+ // 2 | | Logical Screen Height Unsigned // +- -+ // 3 | | // +---------------+ // 4 | | | | | <Packed Fields> See below // +---------------+ // 5 | | Background Color Index Byte // +---------------+ // 6 | | Pixel Aspect Ratio Byte // +---------------+ // // <Packed Fields> = Global Color Table Flag 1 Bit // Color Resolution 3 Bits // Sort Flag 1 Bit // Size of Global Color Table 3 Bits final int width = readShort(); final int height = readShort(); final int packed = readByte(); final int globalColorTableSize = 2 << (packed & 0x07); final int backgroundIndex = readByte(); source.skip(1); // Ignore pixel aspect ratio. int[] globalColorTable = null; if ((packed & 0x80) != 0 && globalColorTableSize > 0) { globalColorTable = readColorTable(globalColorTableSize); } // Peek for netscape extension int loopCount = 0; if (source.request(19)) { ByteString extension = source.buffer().snapshot(13); if (extension.getByte(0) == 0x21 && extension.getByte(1) == 0xff && extension.rangeEquals(3, APPLICATION_NETSCAPE, 0, 11)) { source.skip(14); // extension header, app extension id loopCount = readShort(); source.skip(1); // block terminator } } final Header header = new Header(width, height, globalColorTable, globalColorTableSize, backgroundIndex, loopCount); section = SECTION_BODY; this.header = header; return header; } @Nullable public Frame readFrame() throws IOException { if (section == SECTION_HEADER) header = readHeader(); if (section == SECTION_DONE) return null; frame = readFrameInternal(frame); return frame; } @Nullable private Frame readFrameInternal(final Frame prev) throws IOException { frame = new Frame(); while (frameSection == FRAME_HEADER) { int code = readByte(); switch (code) { case 0x21: readFrameExtension(frame); break; case 0x2c: readImageDescriptor(frame); break; case 0x3b: section = SECTION_DONE; return null; // Trailer } } frame.dispose(header, prev, restoreCanvas); readFrameImageData(frame); return frame; } private void readFrameExtension(Frame frame) throws IOException { int code = readByte(); switch (code) { // Graphics control extension // 7 6 5 4 3 2 1 0 Field Name Type // +---------------+ // 0 | | Extension Introducer Byte // +---------------+ // 1 | | Graphic Control Label Byte // +---------------+ // // +---------------+ // 0 | | Block Size Byte // +---------------+ // 1 | | | | | <Packed Fields> See below // +---------------+ // 2 | | Delay Time Unsigned // +- -+ // 3 | | // +---------------+ // 4 | | Transparent Color Index Byte // +---------------+ // // +---------------+ // 0 | | Block Terminator Byte // +---------------+ // // <Packed Fields> = Reserved 3 Bits // Disposal Method 3 Bits // User Input Flag 1 Bit // Transparent Color Flag 1 Bit case 0xf9: source.skip(1); // fixed block size int packed = readByte(); frame.disposalMethod = (packed & 0x1c) >> 2; frame.transparentColorFlag = (packed & 1) != 0; frame.setDelayTime(readShort() * 10); if (frame.transparentColorFlag) { frame.transparentColorIndex = readByte(); } else { source.skip(1); frame.transparentColorIndex = -1; } source.skip(1); // block terminator break; // Application extension // 7 6 5 4 3 2 1 0 Field Name Type // +---------------+ // 0 | | Extension Introducer Byte // +---------------+ // 1 | | Extension Label Byte // +---------------+ // // +---------------+ // 0 | | Block Size Byte // +---------------+ // 1 | | // +- -+ // 2 | | // +- -+ // 3 | | Application Identifier 8 Bytes // +- -+ // 4 | | // +- -+ // 5 | | // +- -+ // 6 | | // +- -+ // 7 | | // +- -+ // 8 | | // +---------------+ // 9 | | // +- -+ //10 | | Appl. Authentication Code 3 Bytes // +- -+ //11 | | // +---------------+ // // +===============+ // | | // | | Application Data Data Sub-blocks // | | // | | // +===============+ // // +---------------+ // 0 | | Block Terminator Byte // +---------------+ case 0xff: // Ignore application extensions; we've already read the only one we care about (Netscape). source.skip(readByte() + 13); // app extension id, app data, block terminator } } private void readImageDescriptor(Frame frame) throws IOException { // Image Descriptor // // 7 6 5 4 3 2 1 0 Field Name Type // +---------------+ // 0 | | Image Separator Byte // +---------------+ // 1 | | Image Left Position Unsigned // +- -+ // 2 | | // +---------------+ // 3 | | Image Top Position Unsigned // +- -+ // 4 | | // +---------------+ // 5 | | Image Width Unsigned // +- -+ // 6 | | // +---------------+ // 7 | | Image Height Unsigned // +- -+ // 8 | | // +---------------+ // 9 | | | | | | <Packed Fields> See below // +---------------+ // // <Packed Fields> = Local Color Table Flag 1 Bit // Interlace Flag 1 Bit // Sort Flag 1 Bit // Reserved 2 Bits // Size of Local Color Table 3 Bits source.require(9); frame.imageLeftPosition = readShort(); frame.imageTopPosition = readShort(); frame.imageWidth = readShort(); frame.imageHeight = readShort(); int packed = readByte(); frame.localColorTableFlag = (packed & 0x80) != 0; frame.interlaceFlag = (packed & 0x40) != 0; frame.sortFlag = (packed & 0x20) != 0; frame.localColorTableSize = 2 << (packed & 0x07); if (frame.localColorTableFlag) { // Local color table // // 7 6 5 4 3 2 1 0 Field Name Type // +===============+ // 0 | | Red 0 Byte // +- -+ // 1 | | Green 0 Byte // +- -+ // 2 | | Blue 0 Byte // +- -+ // 3 | | Red 1 Byte // +- -+ // | | Green 1 Byte // +- -+ // up | | // +- . . . . -+ ... // to | | // +- -+ // | | Green 255 Byte // +- -+ // 767 | | Blue 255 Byte // +===============+ frame.localColorTable = readColorTable(frame.localColorTableSize); frame.activeColorTable = frame.localColorTable; } else { frame.activeColorTable = header.globalColorTable; } frameSection = FRAME_DATA; } private void readFrameImageData(Frame frame) throws IOException { frame.indexData = readFrameIndexData(frame.imageWidth * frame.imageHeight); frame.pixelData = readFramePixelData(frame); if (frame.disposalMethod == DISPOSAL_METHOD_UNKNOWN || frame.disposalMethod == DISPOSAL_METHOD_LEAVE) { restoreCanvas = frame.pixelData; } frameSection = FRAME_HEADER; } private ByteString readFrameIndexData(final int count) throws IOException { // Image data block // // 7 6 5 4 3 2 1 0 Field Name Type // +---------------+ // | | LZW Minimum Code Size Byte // +---------------+ // // +===============+ // | | // / / Image Data Data Sub-blocks // | | // +===============+ // LZW raster data // 7 6 5 4 3 2 1 0 // +---------------+ // | LZW code size | // +---------------+ // // +---------------+ ----+ // | block size | | // +---------------+ | // | | +-- Repeated as many // | data bytes | | times as necessary. // | | | // +---------------+ ----+ // // . . . . . . ------- The code that terminates the LZW // compressed data must appear before // Block Terminator. // +---------------+ // |0 0 0 0 0 0 0 0| Block Terminator // +---------------+ if (indexData == null) { indexData = new Buffer(); } else { indexData.clear(); } if (prefix == null) prefix = new short[MAX_STACK_SIZE]; if (suffix == null) suffix = new byte[MAX_STACK_SIZE]; if (pixelStack == null) pixelStack = new byte[MAX_STACK_SIZE + 1]; final int dataSize = readByte(); final int clearCode = 1 << dataSize; final int endCode = clearCode + 1; int available = clearCode + 2; int oldCode = -1; int codeSize = dataSize + 1; int codeMask = (1 << codeSize) - 1; int datum = 0; int bits = 0; int first = 0; int top = 0; int remaining = 0; int code; int i; for (code = 0; code < clearCode; code++) { prefix[code] = 0; suffix[code] = (byte) code; } for (i = 0; i < count; ) { if (remaining == 0) { remaining = readByte(); if (remaining <= 0) break; } datum |= readByte() << bits; bits += 8; remaining--; while (bits >= codeSize) { // Get the next code. code = datum & codeMask; datum >>= codeSize; bits -= codeSize; // Interpret the code. if (code == clearCode) { // Reset decoder. codeSize = dataSize + 1; codeMask = (1 << codeSize) - 1; available = clearCode + 2; oldCode = -1; continue; } if (code == endCode || code > available) { break; } if (oldCode == -1) { indexData.writeByte(code); i++; oldCode = code; first = code; continue; } int inCode = code; if (code >= available) { pixelStack[top++] = (byte) first; code = oldCode; } while (code >= clearCode) { pixelStack[top++] = suffix[code]; code = prefix[code]; } first = suffix[code] & 0xff; pixelStack[top++] = (byte) first; if (available >= MAX_STACK_SIZE) break; prefix[available] = (short) oldCode; suffix[available] = (byte) first; available++; if (((available & codeMask) == 0) && (available < MAX_STACK_SIZE)) { codeSize++; codeMask += available; } oldCode = inCode; // Drain the pixel stack. while (top > 0) { indexData.writeByte(pixelStack[--top]); i++; pixelStack[top] = 0; } } } // Clear missing pixels. for (; i < count; i++) { indexData.writeByte(0); } source.skip(remaining + 1); // padding + block terminator return indexData.snapshot(); } private ByteString readFramePixelData(final Frame frame) throws IOException { Buffer pixelData = new Buffer(); ByteString indexData = frame.indexData; int[] colors = frame.activeColorTable; int transparentIndex = frame.transparentColorFlag ? frame.transparentColorIndex : -1; final int w = frame.imageWidth; final int h = frame.imageHeight; final int left = frame.imageLeftPosition; final int top = frame.imageTopPosition; final int right = left + w; final int bottom = top + h; final int stride = header.width * 4; final Buffer canvas = new Buffer(); canvas.write(frame.canvas); int dy, dx, sy; int n1 = 0, n2 = 0, n3 = 0; if (frame.interlaceFlag) { n1 = (h + 7) / 8; n2 = (h + 3) / 4; n3 = (h + 1) / 2; } // Top unpopulated region if (top > 0) { pixelData.write(canvas, top * stride); } for (dy = 0; dy < h; dy++) { // Left unpopulated region if (left > 0) { pixelData.write(canvas, left * 4); } if (frame.interlaceFlag) { sy = dy % 8 == 0 ? dy / 8 : dy % 4 == 0 ? n1 + (dy - 4) / 8 : dy % 2 == 0 ? n2 + (dy - 2) / 4 : n3 + (dy - 1) / 2; } else { sy = dy; } for (dx = 0; dx < w; dx++) { final int pos = sy * w + dx; final int index = indexData.getByte(pos) & 0xff; if (index == transparentIndex) { pixelData.write(canvas, 4); } else { pixelData.writeInt(colors[index]); canvas.skip(4); } } // Right unpopulated region if (right < header.width) { pixelData.write(canvas, (header.width - right) * 4); } } // Bottom unpopulated region if (bottom < header.height) { pixelData.write(canvas, (header.height - bottom) * stride); } return pixelData.snapshot(); } @Override public Timeout timeout() { return source.timeout(); } @Override public void close() throws IOException { source.close(); } private int readByte() throws IOException { return source.readByte() & 0xff; } private int readShort() throws IOException { return source.readShortLe() & 0xffff; } private int[] readColorTable(int count) throws IOException { // Global Color Table // // 7 6 5 4 3 2 1 0 Field Name Type // +===============+ // 0 | | Red 0 Byte // +- -+ // 1 | | Green 0 Byte // +- -+ // 2 | | Blue 0 Byte // +- -+ // 3 | | Red 1 Byte // +- -+ // | | Green 1 Byte // +- -+ // up | | // +- . . . . -+ ... // to | | // +- -+ // | | Green 255 Byte // +- -+ // 767 | | Blue 255 Byte // +===============+ source.require(count * 3); int[] table = new int[count]; for (int i = 0; i < count; i++) { table[i] = readByte() << 16 | readByte() << 8 | readByte() | 0xff000000; } return table; } public static class Header { final int width; final int height; final int globalColorTableSize; final int[] globalColorTable; final int backgroundIndex; final int loopCount; final ByteString background; Header(int width, int height, @Nullable int[] globalColorTable, int globalColorTableSize, int backgroundIndex, int loopCount) { this.width = width; this.height = height; this.globalColorTable = globalColorTable; this.globalColorTableSize = globalColorTableSize; this.backgroundIndex = backgroundIndex; this.loopCount = loopCount; Buffer canvas = new Buffer(); int count = width * height; if (globalColorTable != null) { int background = globalColorTable[backgroundIndex]; for (int i = 0; i < count; i++) { canvas.writeInt(background); } } else { for (int i = 0; i < count; i++) { canvas.writeInt(0); } } background = canvas.snapshot(); } public int width() { return width; } public int height() { return height; } public int loopCount() { return loopCount; } } public static class Frame { // Graphic control extension int delayTime; int disposalMethod; int transparentColorIndex; boolean transparentColorFlag; // Netscape extension int loopCount; // Image header int imageLeftPosition; int imageTopPosition; int imageWidth; int imageHeight; boolean localColorTableFlag; int localColorTableSize; int[] localColorTable; boolean interlaceFlag; boolean sortFlag; int[] activeColorTable; // Image data ByteString canvas; ByteString indexData; ByteString pixelData; Frame() { // Prevent instantiation outside this package. } public int delayTime() { return delayTime; } public int loopCount() { return loopCount; } public ByteString pixels() { return pixelData; } void setDelayTime(int delayTime) { this.delayTime = delayTime <= 10 ? 100 : delayTime; } void dispose(final Header header, @Nullable final Frame prev, @Nullable final ByteString restoreCanvas) throws IOException { switch (disposalMethod) { case DISPOSAL_METHOD_LEAVE: canvas = prev == null ? header.background : prev.pixelData; break; case DISPOSAL_METHOD_RESTORE: canvas = restoreCanvas == null ? header.background : restoreCanvas; break; case DISPOSAL_METHOD_UNKNOWN: case DISPOSAL_METHOD_BACKGROUND: default: canvas = header.background; } } @SuppressLint("DefaultLocale") @Override public String toString() { return String.format("Frame(\n" + " graphics control:\n" + " delayTime=%d\n" + " disposalMethod=%d\n" + " transparentColorIndex=%d\n" + " transparentColorFlag=%s\n" + " netscape:\n" + " loopCount=%d\n" + " header:\n" + " imageLeftPosition=%d\n" + " imageTopPosition=%d\n" + " imageWidth=%d\n" + " imageHeight=%d\n" + " localColorTableFlag=%s\n" + " interlaceFlag=%s\n" + " sortFlag=%s\n" + " localColorTableSize=%d\n" + ")\n", delayTime, disposalMethod, transparentColorIndex, transparentColorFlag, loopCount, imageLeftPosition, imageTopPosition, imageWidth, imageHeight, localColorTableFlag, interlaceFlag, sortFlag, localColorTableSize ); } } public static class UnsupportedFormatException extends IOException { UnsupportedFormatException(String message) { super(message); } } }
30.635352
99
0.447385
73ab6cc0f3c055e6a69f3ee8c1caa1ba5f046043
1,131
/* * Created on 07-Mar-2004 * Author is Michael Camacho */ package pipe.actions; import pipe.gui.imperial.pipe.models.petrinet.Annotation; import javax.swing.*; import java.awt.event.ActionEvent; /** * Action used to toggle the borderof an annotation */ public class EditAnnotationBorderAction extends AbstractAction { // private final Annotation annotation; /** * Constructor * @param annotation annotation to toggle border */ public EditAnnotationBorderAction(Annotation annotation) { //this.annotation = annotation; } /** * Action for editing the text in an AnnotationNote */ @Override public void actionPerformed(ActionEvent e) { // PipeApplicationController controller = ApplicationSettings.getApplicationController(); // PetriNetController petriNetController = controller.getActivePetriNetController(); // annotation.toggleBorder(); //TODO: UNDO ACTION! // petriNetController.getHistoryManager().addNewEdit(annotation.showBorder(!annotation.isShowingBorder())); } }
26.302326
115
0.682582
7c522f3d126bc570d241276c81682217cfe72a5c
1,589
package tw.com.tp6gl4cj86.java_tool.RecyclerView; import android.content.Context; import android.graphics.PointF; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearSmoothScroller; import androidx.recyclerview.widget.RecyclerView; /** * Created by tp6gl4cj86 on 15/4/30. */ public class OlisLayoutManager extends LinearLayoutManager { public OlisLayoutManager(Context context) { super(context); } public OlisLayoutManager(Context context, int orientation, boolean reverseLayout) { super(context, orientation, reverseLayout); } @Override protected int getExtraLayoutSpace(RecyclerView.State state) { return 300; } @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { final RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext()); smoothScroller.setTargetPosition(position); startSmoothScroll(smoothScroller); } private class TopSnappedSmoothScroller extends LinearSmoothScroller { TopSnappedSmoothScroller(Context context) { super(context); } @Override public PointF computeScrollVectorForPosition(int targetPosition) { return OlisLayoutManager.this.computeScrollVectorForPosition(targetPosition); } @Override protected int getVerticalSnapPreference() { return SNAP_TO_START; } } }
25.629032
115
0.708622
5e0081c9934b91e7392f9d2e27d812a1d0105bfb
6,566
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.metamodel.csv; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectInputStream.GetField; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import org.apache.metamodel.schema.AbstractTable; import org.apache.metamodel.schema.Column; import org.apache.metamodel.schema.ColumnType; import org.apache.metamodel.schema.MutableColumn; import org.apache.metamodel.schema.Relationship; import org.apache.metamodel.schema.Schema; import org.apache.metamodel.schema.TableType; import org.apache.metamodel.schema.naming.ColumnNamingContextImpl; import org.apache.metamodel.schema.naming.ColumnNamingSession; import org.apache.metamodel.schema.naming.ColumnNamingStrategy; import org.apache.metamodel.util.FileHelper; import org.apache.metamodel.util.LegacyDeserializationObjectInputStream; import com.opencsv.CSVReader; final class CsvTable extends AbstractTable { private static final long serialVersionUID = 1L; private final CsvSchema _schema; private final String _tableName; private List<Column> _columns; /** * Constructor for creating a new CSV table which has not yet been written. * * @param schema * @param columnNames */ public CsvTable(CsvSchema schema, String tableName, List<String> columnNames) { this(schema, tableName); _columns = buildColumns(columnNames); } /** * Constructor for reading an existing CSV table. * * @param schema */ public CsvTable(CsvSchema schema, String tableName) { _schema = schema; _tableName = tableName; } @Override public String getName() { if (_tableName == null) { // can only occur when deserializing legacy objects. Using the // legacy MetaModel code for creating table name here. String schemaName = _schema.getName(); return schemaName.substring(0, schemaName.length() - 4); } return _tableName; } @Override public List<Column> getColumns() { if (_columns == null) { synchronized (this) { if (_columns == null) { _columns = buildColumns(); } } } return _columns; } private List<Column> buildColumns() { CSVReader reader = null; try { reader = _schema.getDataContext().createCsvReader(0); final int columnNameLineNumber = _schema.getDataContext().getConfiguration().getColumnNameLineNumber(); for (int i = 1; i < columnNameLineNumber; i++) { reader.readNext(); } final List<String> columnHeaders = Arrays.asList(Optional.ofNullable(reader.readNext()).orElse(new String[0])); reader.close(); return buildColumns(columnHeaders); } catch (IOException e) { throw new IllegalStateException("Exception reading from resource: " + _schema.getDataContext().getResource().getName(), e); } finally { FileHelper.safeClose(reader); } } private List<Column> buildColumns(final List<String> columnNames) { if (columnNames == null) { return new ArrayList<>(); } final CsvConfiguration configuration = _schema.getDataContext().getConfiguration(); final int columnNameLineNumber = configuration.getColumnNameLineNumber(); final boolean nullable = !configuration.isFailOnInconsistentRowLength(); final ColumnNamingStrategy columnNamingStrategy = configuration.getColumnNamingStrategy(); List<Column> columns = new ArrayList<>(); try (final ColumnNamingSession namingSession = columnNamingStrategy.startColumnNamingSession()) { for (int i = 0; i < columnNames.size(); i++) { final String intrinsicColumnName = columnNameLineNumber == CsvConfiguration.NO_COLUMN_NAME_LINE ? null : columnNames.get(i); final String columnName = namingSession.getNextColumnName(new ColumnNamingContextImpl(this, intrinsicColumnName, i)); final Column column = new MutableColumn(columnName, ColumnType.STRING, this, i, null, null, nullable, null, false, null); columns.add(column); } } return columns; } @Override public Schema getSchema() { return _schema; } @Override public TableType getType() { return TableType.TABLE; } @Override public Collection<Relationship> getRelationships() { return Collections.emptyList(); } @Override public String getRemarks() { return null; } @Override public String getQuote() { return null; } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { final GetField getFields = stream.readFields(); Object columns = getFields.get("_columns", null); if (columns instanceof Column[]) { columns = Arrays.<Column> asList((Column[]) columns); } final Object schema = getFields.get("_schema", null); final Object tableName = getFields.get("_tableName", null); LegacyDeserializationObjectInputStream.setField(CsvTable.class, this, "_columns", columns); LegacyDeserializationObjectInputStream.setField(CsvTable.class, this, "_schema", schema); LegacyDeserializationObjectInputStream.setField(CsvTable.class, this, "_tableName", tableName); } }
35.879781
123
0.66753
7af8193f9b3ee6332c11476f30f0e5280011fd16
960
package com.vpaliy.melophile.ui.base.bus.event; import android.os.Bundle; import android.support.v4.util.Pair; import android.view.View; public class ExposeEvent { public static final int PLAYER=0; public static final int PLAYLIST=1; public static final int USER=2; public final int code; public final Bundle data; public final Pair<View,String>[] pack; private ExposeEvent(Bundle data, Pair<View,String>[] pack, int code){ this.data=data; this.pack=pack; this.code=code; } public static ExposeEvent exposePlaylist(Bundle data, Pair<View,String> ... pack){ return new ExposeEvent(data,pack,PLAYLIST); } public static ExposeEvent exposeTrack(Bundle data, Pair<View,String> ... pack){ return new ExposeEvent(data,pack,PLAYER); } public static ExposeEvent exposeUser(Bundle data, Pair<View,String>...pack){ return new ExposeEvent(data,pack,USER); } }
27.428571
86
0.688542
1036b356becbc80b3f9b9e4efb0cefd688086947
9,410
package com.inz.z.view.widget; import android.content.Context; import android.graphics.drawable.Drawable; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.ConstraintLayout; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.DataSource; import com.bumptech.glide.load.engine.GlideException; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.inz.z.R; import de.hdodenhof.circleimageview.CircleImageView; /** * @author Zhenglj * @version 1.0.0 * Create by inz in 2018/11/13 17:27. */ public class ItemDiaryInfoLayout extends ConstraintLayout { private View mView; private Context mContext; public ItemDiaryInfoLayout(Context context) { this(context, null); } public ItemDiaryInfoLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ItemDiaryInfoLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; } private RelativeLayout topRl; private CircleImageView userPhotoCiv; private CircleImageView userPhotoSignCiv; private TextView userNameTv; private TextView userSignLl; private ImageView userSign0Iv; private ImageView userSign1Iv; private ImageView userSign2Iv; private ImageView userSign3Iv; private ImageView[] userSigns; private LinearLayout sendInfoLl; private TextView sendTimeTv; private RelativeLayout topRightRl; private ImageView topRightMoreIv; private TextView topRightAttentionTv; private RelativeLayout contentRl; private TextView diaryContentTv; private LinearLayout imageLl; private void initView() { if (mView != null) { mView = LayoutInflater.from(mContext).inflate(R.layout.item_diary_info, null); topRl = mView.findViewById(R.id.item_diary_info_top_rl); userPhotoCiv = mView.findViewById(R.id.item_diary_info_user_photo_civ); userPhotoSignCiv = mView.findViewById(R.id.item_diary_info_user_photo_sign_civ); userNameTv = mView.findViewById(R.id.item_diary_info_user_name_tv); userSignLl = mView.findViewById(R.id.item_diary_info_user_sign_ll); userSign0Iv = mView.findViewById(R.id.item_diary_info_user_sign_0_iv); userSign1Iv = mView.findViewById(R.id.item_diary_info_user_sign_1_iv); userSign2Iv = mView.findViewById(R.id.item_diary_info_user_sign_2_iv); userSign3Iv = mView.findViewById(R.id.item_diary_info_user_sign_3_iv); userSigns = new ImageView[]{userSign0Iv, userSign1Iv, userSign2Iv, userSign3Iv}; sendInfoLl = mView.findViewById(R.id.item_diary_info_send_info_ll); sendTimeTv = mView.findViewById(R.id.item_diary_info_send_time_tv); topRightRl = mView.findViewById(R.id.item_diary_info_top_right_rl); topRightMoreIv = mView.findViewById(R.id.item_diary_info_top_right_more_iv); topRightAttentionTv = mView.findViewById(R.id.item_diary_info_top_right_attention_tv); contentRl = mView.findViewById(R.id.item_diary_info_content_rl); diaryContentTv = mView.findViewById(R.id.item_diary_info_content_info_tv); imageLl = mView.findViewById(R.id.item_diary_info_image_ll); LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); addView(mView, layoutParams); } } public void setUserPhotoSrc(String userPhotoSrc) { if (userPhotoCiv != null) { Glide.with(getContext()).load(userPhotoSrc).into(userPhotoCiv); } } public void setUserPhotoSignSrc(String userPhotoSignSrc) { if (userPhotoSignCiv != null) { Glide.with(getContext()).load(userPhotoSignSrc).listener(new RequestListener<Drawable>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { userPhotoSignCiv.setVisibility(GONE); return true; } @Override public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { return false; } }).into(userPhotoSignCiv); } } public void setUserName(String userName) { if (userNameTv != null) { userNameTv.setText(userName); } } public void setUserSignSrc(String[] userSignSrc) { if (userSigns != null) { if (userSignSrc.length > 0) { int i = 0; for (String singSrc : userSignSrc) { Glide.with(getContext()).load(singSrc).into(userSigns[i]); userSigns[i].setVisibility(VISIBLE); i++; } } } } public void setSendTime(String sendTime) { if (sendTimeTv != null) { sendTimeTv.setText(sendTime); } } public static enum RightMode { MORE, ATTENTION, RECOMMEND } public void setTopRightMode(RightMode rightMode) { if (topRightMoreIv != null && topRightAttentionTv != null) { switch (rightMode) { case MORE: topRightMoreIv.setVisibility(VISIBLE); topRightAttentionTv.setVisibility(GONE); break; case ATTENTION: case RECOMMEND: default: topRightMoreIv.setVisibility(GONE); topRightAttentionTv.setVisibility(VISIBLE); break; } } } /** * 设置日志 内容 * * @param content 内容 */ public void setDiaryContent(String content) { if (diaryContentTv != null) { diaryContentTv.setText(content); } } /** * 添加 日志图片 * * @param imageUrls 图片链接数组 */ public void addDiaryImages(String[] imageUrls) { if (imageLl != null) { RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); int width = imageLl.getMeasuredWidth(); if (width > 60) { float oneWidth = (width - 60) / 3; float twoWidth = (width - 40) / 2; int size = imageUrls.length; if (size == 1) { float thisWidth = oneWidth * 2 + 30; ImageView imageView = newImageView((int) twoWidth, (int) thisWidth, imageUrls[0]); imageLl.addView(imageView, layoutParams); } else if (size > 1) { // 四张图 if (size == 4) { RelativeLayout layout = null; for (int i = 0; i < size; i++) { if (i == 0 || i == 3) { layout = new RelativeLayout(getContext()); imageLl.addView(layout, layoutParams); } ImageView imageView = newImageView((int) oneWidth, (int) oneWidth, imageUrls[i]); layout.addView(imageView, layoutParams); } } else { RelativeLayout layout = null; if (size > 9) { size = 9; } for (int i = 0; i < size; i++) { if (i % 3 == 0) { layout = new RelativeLayout(getContext()); imageLl.addView(layout); } String imageUrl = imageUrls[i]; ImageView imageView = newImageView((int) oneWidth, (int) oneWidth, imageUrl); layout.addView(imageView, layoutParams); } } } else { imageLl.setVisibility(GONE); } } } } /** * 新建图片 * * @param width 宽 * @param imageUrl 图片链接 * @return 图片 */ private ImageView newImageView(int width, int height, String imageUrl) { RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.height = height; ImageView imageView = new ImageView(getContext()); layoutParams.setMargins(8, 8, 8, 8); imageView.setLayoutParams(layoutParams); imageView.setMinimumWidth(width); Glide.with(getContext()).load(imageUrl).into(imageView); return imageView; } }
37.943548
154
0.59373
6d22c5c6a467ec0a70f0b1645ef5462a59a55733
574
package com.eloKeyboard.base.utils; import org.junit.Assert; import org.junit.Test; public class CompatUtilsTest { @Test public void testObjectsEqual() { Assert.assertTrue(CompatUtils.objectEquals(null, null)); Assert.assertFalse(CompatUtils.objectEquals(null, new Object())); Assert.assertFalse(CompatUtils.objectEquals(new Object(), null)); Assert.assertTrue(CompatUtils.objectEquals(new String("test"), new String("test"))); Assert.assertFalse(CompatUtils.objectEquals(new String("test"), new String("test1"))); } }
33.764706
94
0.712544
12ad09cf2f0c9900c9c6dc82303411b7cb338200
1,281
package com.lindar.getaddress.io.client.api; import com.google.gson.reflect.TypeToken; import com.lindar.getaddress.io.client.util.GetAddressConfigs; import com.lindar.getaddress.io.client.vo.GetAddressResponse; import com.lindar.getaddress.io.client.vo.PrivateAddressVO; import com.lindar.wellrested.vo.Result; import lindar.acolyte.util.UrlAcolyte; import java.util.List; public class PrivateAddressResource extends AbstractResource { private static final String PRIVATE_ADDRESS_ENDPOINT = "/private-address"; public PrivateAddressResource(GetAddressConfigs getAddressConfigs) { super(getAddressConfigs); } public Result<List<PrivateAddressVO>> list(String postcode) { return getListRequest(createFullPath(postcode), new TypeToken<List<PrivateAddressVO>>() {}); } public Result<GetAddressResponse> add(String postcode, PrivateAddressVO privateAddressVO) { return postRequest(createFullPath(postcode), privateAddressVO); } public Result<GetAddressResponse> delete(String id, String postcode) { return deleteRequest(createFullPath(postcode), id); } private String createFullPath(String postcode) { return UrlAcolyte.safeConcat(PRIVATE_ADDRESS_ENDPOINT, postcode.replaceAll(" ", "")); } }
35.583333
100
0.76815
233258bc9c9144ce248f3678a5c9f93b6c2acad2
1,478
/* * Copyright 2012 GWT-Bootstrap * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.gwtbootstrap.client.ui; import com.github.gwtbootstrap.client.ui.base.HtmlWidget; import com.github.gwtbootstrap.client.ui.resources.Bootstrap; //@formatter:off /** * Simple wrapper for an HTML {@code <footer>} tag. * <p> * Doesn't have any special formatting. * </p> * * <p> * <h3>UiBinder Usage:</h3> * * <pre> * {@code * <b:Footer> * <g:Label>Some text</g:Label> * </b:Footer>} * </pre> * </p> * * @since 2.0.4.0 * * @author Dominik Mayer * @author ohashi keisuke */ //@formatter:on public class Footer extends HtmlWidget { // TODO: No nice style in bootstrap. Delete? /** * Creates an empty Footer. */ public Footer() { this(""); } /** * Creates a widget with the html. * @param html content html */ public Footer(String html) { super("footer" , html); setStyleName(Bootstrap.footer); } }
22.738462
76
0.669147
2358e2de3c8aa52ab560d782bef5e24dbf0856ac
398
/*Question 4 Write a program that takes a year from user and print whether that year is a leap year or not. Year is divisible by 4 or 400 but not 100*/ import java.util.*; class Question4{ public static void main (String[] args){ Scanner kb = new Scanner(System.in); int input =0; System.out.println("Enter year"); input = kb.nextInt(); System.out.println(answer); } }
20.947368
62
0.678392
d65e04c08e5eec67716ac612b404f9af2ea54506
2,104
/* package ukim.mk.finki.konstantin.bogdanoski.wp.web.servlets; import lombok.AllArgsConstructor; import org.thymeleaf.context.WebContext; import org.thymeleaf.spring5.SpringTemplateEngine; import ukim.mk.finki.konstantin.bogdanoski.wp.model.user.User; import ukim.mk.finki.konstantin.bogdanoski.wp.service.OrderService; import ukim.mk.finki.konstantin.bogdanoski.wp.service.UserService; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.logging.Logger; */ /** * @author Konstantin Bogdanoski ([email protected]) *//* @WebServlet(urlPatterns = "/admin") @AllArgsConstructor public class AdminServlet extends HttpServlet { private final UserService userService; private final OrderService orderService; private final SpringTemplateEngine springTemplateEngine; private final Logger logger; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logger.info("\u001B[33mGET method CALLED from Admin Servlet\u001B[0m"); resp.setContentType("text/html; charset=UTF-8"); req.setCharacterEncoding("UTF-8"); WebContext context = new WebContext(req, resp, req.getServletContext()); HttpSession session = context.getSession(); User user = new User(); if (userService.findByUsername((String) session.getAttribute("username")).isPresent()) user = userService.findByUsername((String) session.getAttribute("username")).get(); if (user.getUserRole().equals("ROLE_ADMIN")) { context.setVariable("orders", orderService.findAll()); session.setAttribute("orders", orderService.findAll()); springTemplateEngine.process("master-admin.html", context, resp.getWriter()); } else resp.sendError(404, "YOU ARE NOT ALLOWED TO BE HERE!"); } } */
38.962963
113
0.742395
34039572c453462258d806012d3d29217458449d
515
package com.revature; import com.revature.proxy.LoggingAspect; import com.revature.proxy.If; import com.revature.proxy.Original; import java.lang.reflect.Proxy; public class JdkProxyDemo { public static void main(String[] args) { Original original = new Original(); LoggingAspect handler = new LoggingAspect(original); If f = (If) Proxy.newProxyInstance(Original.class.getClassLoader(), new Class[] { If.class }, handler); f.originalMethod("Actual method logic!"); } }
25.75
111
0.706796
e7ab35d0dd88a5f5c3a35701d324280670e36de1
4,032
package com.galois.fiveui; import java.io.File; import java.io.IOException; import java.net.BindException; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.Assert; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import com.google.common.base.Function; import com.google.common.io.Files; import edu.uci.ics.crawler4j.util.IO; public class CrawlTest { // TODO need a system independent way of getting the resources path private static String resourceDir = "src/test/resources/crawlTest/"; private static Logger logger = Logger.getLogger("com.galois.fiveui.CrawlTest"); private static NanoHTTPD httpServer = null; @BeforeClass public static void setupCrawlTests() { // Set up a simple configuration that logs on the console. BasicConfigurator.configure(); logger.setLevel(Level.DEBUG); Logger root = Logger.getRootLogger(); root.setLevel(Level.ERROR); // start up local web server for crawl tests logger.info("Starting NanoHTTPD webserver in " + resourceDir + " on port 8080 ..."); try { httpServer = new NanoHTTPD(8080, new File(resourceDir)); } catch (BindException e) { logger.info("assuming that local web server is already running"); } catch (IOException e1) { e1.printStackTrace(); Assert.assertTrue("failed to start NanoHTTPD in resource directory", false); } } @AfterClass public static void teardown() { LogManager.shutdown(); httpServer.stop(); } // Requires Internet access // @Test public void corpDotGaloisCrawlTest() { File tmpPath = Files.createTempDir(); BasicCrawlerController con = new BasicCrawlerController("http://corp.galois.com", "http://corp.galois.com", 2, 5, 1000, 1, tmpPath.getAbsolutePath()); List<String> urls = null; try { urls = con.go(); System.out.println(urls.toString()); } catch (Exception e) { Assert.assertTrue("failed to complete webcrawl", false); e.printStackTrace(); } finally { IO.deleteFolder(tmpPath); } Assert.assertEquals((urls != null) && (urls.size() == 5), true); } @Test public void testLocalCrawlDepth3one() { doLocalCrawlTest("http://localhost:8080/one.html", 3, 10, 9); } @Test public void testLocalCrawlDepth3two() { doLocalCrawlTest("http://localhost:8080/two.html", 3, 10, 3); } @Test public void testLocalCrawlDepth0one() { doLocalCrawlTest("http://localhost:8080/one.html", 0, 10, 1); } @Test public void testCrawlWithPredicate() { CrawlParameters c = new CrawlParameters("5 5 100 *one.html"); doLocalCrawlTest("http://localhost:8080/one.html", c.matchFcn, c.depth, c.maxFetch, 1); } public void doLocalCrawlTest(String seed, int depth, int maxFetch, int oracle) { Function<String, Boolean> pred = new Function<String, Boolean>() { public Boolean apply(String s) { return s.startsWith("http"); } }; doLocalCrawlTest(seed, pred, depth, maxFetch, oracle); } public void doLocalCrawlTest(String seed, Function<String, Boolean> pred, int depth, int maxFetch, int oracle) { logger.info("Starting localCrawlTest ..."); logger.info(" seed " + seed + ", depth " + depth); File tmpPath = Files.createTempDir(); BasicCrawlerController con = new BasicCrawlerController(seed, pred, depth, maxFetch, 100, 1, tmpPath.getAbsolutePath()); List<String> urls = null; try { logger.info("Starting webcrawl ..."); urls = con.go(); logger.info("RETURN -- " + urls.toString()); } catch (Exception e) { e.printStackTrace(); Assert.assertTrue("failed to run webcrawler", false); } finally { IO.deleteFolder(tmpPath); } // assert that we got oracle number of URLs Assert.assertTrue("got " + urls.size() + " URLs, expected " + oracle, (urls != null) && (urls.size() == oracle)); } }
29.430657
114
0.680804
f8f29a9dbabbf5995a3358dbfca73260d32e02ba
4,204
package com.github.oxygenPlugins.common.gui.types; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.event.MouseListener; import java.util.ArrayList; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JTextField; import com.github.oxygenPlugins.common.gui.types.converter.TypeConverter; import com.github.oxygenPlugins.common.gui.types.panels.FocusTraversalField; import com.github.oxygenPlugins.common.gui.types.panels._EntryPanel; public class LabelField extends FocusTraversalField { /** * */ private static final long serialVersionUID = -4827605903105996871L; public static final String NULL_LABEL = "(no value)"; private final TypeConverter type; private Object value; private final ArrayList<_ValueListener> valueListener = new ArrayList<_ValueListener>(); private _EntryPanel entryPanel = null; private String title; LabelField(TypeConverter type, Container owner) { this(null, null, type, owner); } LabelField(JComponent prevComponent, JComponent nextComponent, TypeConverter type, Container owner) { super(prevComponent, nextComponent); this.setOpaque(true); this.type = type; this.setText(type.convertToString(type.getDefault())); this.setHorizontalAlignment(JTextField.CENTER); VerifierFactory.addVerifier(type, this, owner); removeAllFocusListener(); } public TypeConverter getType() { return type; } public String getValueAsString(){ return getValueAsString(type.convertToString(type.getDefault())); } public String getValueAsString(String defaultValue) { String val = type.convertToString(this.value); if (val == null) { return defaultValue; } return val; } @Override public void setText(String text) { if (this.type != null) { setValue(this.type.convertValue(text)); this.setStyle(Font.PLAIN); this.setBackground(Color.WHITE); this.setForeground(Color.BLACK); if(value == null){ this.setForeground(Color.RED); } else if (isValueDefault()) { this.setForeground(Color.GRAY); } if(text == null){ text = NULL_LABEL; this.setStyle(Font.ITALIC); } } this.setToolTipText(text); super.setText(text); checkMinimumSize(); } private boolean isValueDefault() { // string compare as date / time comparison does not work if(!type.hasDefault()){ return false; } String defAsString = type.convertToString(type.getDefault()); String valAsString = type.convertToString(this.value); return defAsString.equals(valAsString); } private void setValue(Object value) { Object oldVal = this.value; this.value = value; for (_ValueListener vl : valueListener) { vl.valueChanged(this.value, oldVal); } } @Override public void setMinimumSize(Dimension minimumSize) { // TODO Auto-generated method stub super.setMinimumSize(minimumSize); checkMinimumSize(); } private void checkMinimumSize() { int w = getWidth(); int h = getHeight(); Dimension minD = getMinimumSize(); w = minD.width > w ? minD.width : w; h = minD.height > h ? minD.height : h; this.setPreferredSize(new Dimension(w, h)); } private void setStyle(int style) { Font oFont = this.getFont(); if (oFont != null) { Font font = new Font(oFont.getName(), style, oFont.getSize()); this.setFont(font); } } public void addValueListener(_ValueListener listener) { this.valueListener.add(listener); } public void removeValueListener(_ValueListener listener) { this.valueListener.remove(listener); } // Focus public void activateVerifier(){ if(this.entryPanel != null){ entryPanel.activate(); } } @Override protected void myFocus(JComponent comp) { if(comp instanceof LabelField){ LabelField compLabelField = (LabelField) comp; compLabelField.activateVerifier(); } else { super.myFocus(comp); } } @Override public synchronized void addMouseListener(MouseListener l) { if(l instanceof _EntryPanel){ this.entryPanel = (_EntryPanel) l; } super.addMouseListener(l); } public void setTitle(String title){ this.title = title; } public String getTitle(){ return this.title; } }
22.481283
102
0.721694