blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
2563cebd8ad70df5f751ce43b35d62f614a23208
Java
memoriavirtual/memoria_virtual_src
/tags/mv_20100409_primeira_versao_operacional/memoriavirtual/src/mvirtual/catalog/heritage/AccessConditions.java
UTF-8
628
2.53125
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mvirtual.catalog.heritage; /** * * @author fabricio */ enum AccessConditions { FREE ("FREE", 0L), UNDER_CONSULT ("UNDER_CONSULT", 1L), NO_ACCESS ("NO_ACCESS", 2L), COPY_ACCESS ("COPY_ACCESS", 3L); private String name; private Long value; private AccessConditions (String name, Long value) { this.name = name; this.value = value; } public String getName() { return this.name; } public Long getValue() { return this.value; } }
true
22422a6f73daaa2872f2a16ee012552e265571f2
Java
AlHamidawiHani/tfzr
/src/main/java/tfzr/store/controller/UserController.java
UTF-8
2,142
2.3125
2
[]
no_license
package tfzr.store.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import tfzr.store.common.AbstractCommon; import tfzr.store.model.Role; import tfzr.store.model.User; @Controller public class UserController extends AbstractCommon{ public UserController() { super(); } @RequestMapping(value = "/public/user/edit", method = RequestMethod.GET) public String userEdit(Model model){ model.addAttribute("user", getCurrentUser()); model.addAttribute("userToSave", new User()); return "editAccount"; } @RequestMapping(value = "/public/user/save", method = RequestMethod.POST) public String userEditSave(@ModelAttribute("${userToSave}") User user){ user.setRole(Role.USER); userService.save(user); return "redirect:/public/index"; } @RequestMapping(value = "/admin/user/save", method = RequestMethod.POST) public String approveUser(@ModelAttribute("${userToSave}") User user){ User userToUpdate = userService.findByUsername(user.getUsername()); userToUpdate.setRole(Role.USER); userService.save(userToUpdate); return "redirect:/admin/users"; } @RequestMapping(value = "/admin/user/delete/{userId}", method = RequestMethod.GET) public String deleteUser(@PathVariable Integer userId){ userService.delete(userId); return "redirect:/admin/users"; } @RequestMapping(value = "/registration/new", method= RequestMethod.POST) public String register(@ModelAttribute("${registration}") User user, BindingResult errors){ user.setRole(Role.NULL); userService.save(user); return "redirect:/login"; } @RequestMapping(value = "/admin/users") public String approveUsers(Model model){ model.addAttribute("unapprovedUsers", userService.findAllUnapproved(Role.NULL)); model.addAttribute("${userToSave}", new User()); return "approveUser"; } }
true
8b0b909957ca210d1c7d0dd4765897446e7c8932
Java
icersummer/BookCollectorNoReturnActivity
/src/com/vjia/bookcollector/pojo/BookEntity.java
UTF-8
2,108
2.671875
3
[]
no_license
package com.vjia.bookcollector.pojo; public class BookEntity { private String title; private String author; /* multi-value */ private String link /* rel=alternate */; private String summary; // deprecate it, not sure difference in isbn10/isbn13 @Deprecated private String isbn10; private String isbn13; private String price; private String publisher; private String binding; private String pubdate; private String tags; public BookEntity(){ } public BookEntity(String title, String author){ this.title=title; this.author=author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getIsbn10() { return isbn10; } public void setIsbn10(String isbn10) { this.isbn10 = isbn10; } public String getIsbn13() { return isbn13; } public void setIsbn13(String isbn13) { this.isbn13 = isbn13; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getBinding() { return binding; } public void setBinding(String binding) { this.binding = binding; } public String getPubdate() { return pubdate; } public void setPubdate(String pubdate) { this.pubdate = pubdate; } public String getTags() { return tags; } public void setTags(String tags) { this.tags = tags; } @Override public String toString() { // TODO update toString() more clearly String str = String.format("%n title=%s,%n author=%s,%n isbn13=%s,%n link=%s,%n price=%s%n", title,author,isbn13,link,price); return super.toString() + str; } }
true
056d16c7fbeb6fe583116c6b513491fbf5fa6185
Java
WakkaFlocka239/ValeriaOnline
/src/main/java/me/wakka/valeriaonline/features/fame/FameCommand.java
UTF-8
2,984
2.375
2
[]
no_license
package me.wakka.valeriaonline.features.fame; import me.wakka.valeriaonline.ValeriaOnline; import me.wakka.valeriaonline.features.fame.menu.FameMenu; import me.wakka.valeriaonline.features.prefixtags.PrefixTags; import me.wakka.valeriaonline.framework.commands.models.CustomCommand; import me.wakka.valeriaonline.framework.commands.models.annotations.ConverterFor; import me.wakka.valeriaonline.framework.commands.models.annotations.Path; import me.wakka.valeriaonline.framework.commands.models.annotations.Permission; import me.wakka.valeriaonline.framework.commands.models.annotations.TabCompleterFor; import me.wakka.valeriaonline.framework.commands.models.events.CommandEvent; import me.wakka.valeriaonline.models.fame.Fame; import me.wakka.valeriaonline.models.fame.FameService; import me.wakka.valeriaonline.models.fame.PrefixTag; import me.wakka.valeriaonline.utils.Tasks; import org.bukkit.OfflinePlayer; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class FameCommand extends CustomCommand { FameService service = new FameService(); public FameCommand(CommandEvent event) { super(event); } @Path() void openMenu() { FameMenu.openMain(player()); } @Path("giveTag <player> <tag>") @Permission("group.admin") void giveTag(OfflinePlayer player, PrefixTag tag) { ValeriaOnline.getPerms().playerAdd(player.getPlayer(), tag.getPermission()); send("Gave " + player.getName() + " tag: " + tag.getName()); if (player.isOnline()) PrefixTags.obtainedMessage(player, Collections.singletonList(tag)); } @Path("give <player> <amount> <type>") @Permission("group.admin") void giveFame(OfflinePlayer player, int amount, FameService.FameType type) { Fame fame = service.get(player); fame.addPoints(type, amount); service.save(fame); Tasks.wait(5, () -> PrefixTags.updatePrefixTags(player)); } @Path("reset <player>") @Permission("group.admin") void reset(OfflinePlayer player) { Fame fame = service.get(player); service.delete(fame); for (PrefixTag activeTag : PrefixTags.getActiveTags()) { ValeriaOnline.getPerms().playerRemove(player.getPlayer(), activeTag.getPermission()); } } @Path("clearDatabase") @Permission("group.sev") void clearDatabase() { FameService service = new FameService(); service.deleteAll(); } @ConverterFor(PrefixTag.class) PrefixTag convertToPrefixTag(String value) { Optional<PrefixTag> prefixTag = PrefixTags.getActiveTags().stream() .filter(tag -> tag.getName().equalsIgnoreCase(value)) .findFirst(); if (!prefixTag.isPresent()) { error("Tag " + value + " not found"); return null; } return prefixTag.get(); } @TabCompleterFor(PrefixTag.class) List<String> tabCompletePrefixTag(String filter) { return PrefixTags.getActiveTags().stream() .filter(tag -> tag.getName().toLowerCase().startsWith(filter.toLowerCase())) .map(PrefixTag::getName) .collect(Collectors.toList()); } }
true
6651bee0cdfa4797af0de077f669d15fcc697d7d
Java
lirui-andy/zaitao
/src/main/java/com/yichang/uep/dto/ImportFaildLine.java
UTF-8
835
2.15625
2
[]
no_license
package com.yichang.uep.dto; import java.io.Serializable; public class ImportFaildLine implements Serializable { /** * */ private static final long serialVersionUID = 1L; int line; String reason; String rawData; public ImportFaildLine(int line, String reason) { super(); this.line = line; this.reason = reason; } public ImportFaildLine(int line, String reason, String rawData) { super(); this.line = line; this.reason = reason; this.rawData = rawData; } public int getLine() { return line; } public void setLine(int line) { this.line = line; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public String getRawData() { return rawData; } public void setRawData(String rawData) { this.rawData = rawData; } }
true
e92c024266a0571b72b22204bf099523ff2ae176
Java
github4n/cloud
/business-service/open-api-service-project/open-api-service/src/main/java/com/iot/ifttt/util/RedisKeyUtil.java
UTF-8
1,650
2.21875
2
[]
no_license
package com.iot.ifttt.util; /** * 描述:redis key 生成工具类 * 创建人: LaiGuiMing * 创建时间: 2018/4/27 13:40 */ public class RedisKeyUtil { private RedisKeyUtil() { } public static final long DEFAULT_EXPIRE_TIME_OUT_2 = 2 * 60 * 60l; public static final String IFTTT_DEVICE_KEY = "ifttt-com:device:%s:%s"; //设备状态缓存 public static final String IFTTT_SCENE_KEY = "ifttt-com:scene:%s"; //情景缓存 public static final String IFTTT_SECURITY_KEY = "ifttt-com:security:%s"; //安防缓存 public static final String IFTTT_SECURITY_TYPE_KEY = "ifttt-com:securityType:%s:%s"; //安防缓存 public static final String IFTTT_TRIGGER_KEY = "ifttt-com:trigger:%s"; //trigger缓存 public static final String IFTTT_CHECK_KEY = "ifttt-com:check:%s"; //重复执行缓存 public static String getIftttDeviceKey(String deviceId, String attr) { return String.format(IFTTT_DEVICE_KEY, deviceId, attr); } public static String getIftttSceneKey(String sceneId) { return String.format(IFTTT_SCENE_KEY, sceneId); } public static String getIftttSecurityKey(String userId) { return String.format(IFTTT_SECURITY_KEY, userId); } public static String getIftttSecurityTypeKey(String userId, String status) { return String.format(IFTTT_SECURITY_TYPE_KEY, userId, status); } public static String getIftttTriggerKey(String identity) { return String.format(IFTTT_TRIGGER_KEY, identity); } public static String getIftttCheckKey(String identity) { return String.format(IFTTT_CHECK_KEY, identity); } }
true
ac2d7a95545e3eebc64f240b9db85b64dd0fcaaa
Java
neriudon/test
/todo-oauth-auth/src/main/java/todo/oauth/api/oauth/TokenRevocationRestController.java
UTF-8
1,557
2.25
2
[]
no_license
package todo.oauth.api.oauth; import javax.inject.Inject; import org.springframework.http.HttpStatus; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import todo.oauth.domain.service.token.RevokeTokenService; /** * トークンの取り消しをするコントローラ */ @RestController @RequestMapping("oauth") public class TokenRevocationRestController { @Inject RevokeTokenService revokeTokenService; // /oauth/tokens/revoke" へのアクセスに対するメソッドとしてマッピング // ここで指定するパスはBasic認証の適用とCSRF対策機能の無効化をする @RequestMapping(value = "tokens/revoke", method = RequestMethod.POST) @ResponseStatus(HttpStatus.OK) public String revoke(@RequestParam("token") String token, @AuthenticationPrincipal UserDetails user) { // Basic認証で生成された認証情報からトークンの取り消し時のチェックで使用するクライアントIDを取得 String clientId = user.getUsername(); // RevokeTokenService を呼び出し、トークンを取り消す String result = revokeTokenService.revokeToken(token, clientId); return result; } }
true
053265dedae5d8f65c44c2601ba3a68226dda0d1
Java
RogerLwr/TPP
/seller/tTPseller/src/main/java/com/tianpingpai/seller/SellerApplication.java
UTF-8
4,122
1.789063
2
[]
no_license
package com.tianpingpai.seller; import android.app.Application; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import com.baidu.mapapi.SDKInitializer; import com.tianpingpai.core.ModelStatusListener; import com.tianpingpai.seller.tools.URLApi; import com.tianpingpai.core.ContextProvider; import com.tianpingpai.http.HttpRequest; import com.tianpingpai.http.OnPreDispatchListener; import com.tianpingpai.http.volley.VolleyDispatcher; import com.tianpingpai.seller.ui.LoginViewController; import com.tianpingpai.seller.ui.SplashViewController; import com.tianpingpai.seller.manager.UserManager; import com.tianpingpai.seller.model.UserModel; import com.tianpingpai.share.ShareService; import com.tianpingpai.share.weixin.WeixinConfig; import com.tianpingpai.ui.ContainerActivity; import com.tianpingpai.ui.FragmentContainerActivity; import com.tianpingpai.user.UserEvent; import com.tianpingpai.utils.Settings; import cn.jpush.android.api.JPushInterface; public class SellerApplication extends Application { private String versionString; private ModelStatusListener<UserEvent, UserModel> loginExpireListener = new ModelStatusListener<UserEvent, UserModel>() { @Override public void onModelEvent(UserEvent event, UserModel model) { if(event == UserEvent.LoginExpired){ Intent intent = new Intent(SellerApplication.this, ContainerActivity.class); intent.putExtra(ContainerActivity.KEY_CONTENT, LoginViewController.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } } }; @Override public void onCreate() { super.onCreate(); ContextProvider.init(this); ContextProvider.setBaseURL(URLApi.getBaseUrl()); SDKInitializer.initialize(this); // LeakCanary.install(this); VolleyDispatcher.getInstance().setOnPreDispatchListener(new OnPreDispatchListener() { @Override public void onPreDispatchRequest(HttpRequest<?> req) { UserModel user = UserManager.getInstance().getCurrentUser(); if (user != null) { req.addParam("accessToken", user.getAccessToken()); } } }); WeixinConfig config = new WeixinConfig(); config.setAppId("wx51c113c72adac0e2"); ShareService.getIntance().setWeixinConfig(config); FragmentContainerActivity.setFragmentContainerCallback(new FragmentContainerActivity.FragmentContainerCallback() { @Override public Class<?> onFirstActivityCreated( FragmentContainerActivity a) { return SplashViewController.class; } }); JPushInterface.setDebugMode(URLApi.IS_DEBUG); // 设置开启日志,发布时请关闭日志 JPushInterface.init(this); // 初始化 JPush String systemVersion = Build.VERSION.RELEASE; String appVersion = "unknown"; try { PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); appVersion = pInfo.versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } String uuid = Settings.getInstance().getUUID(); versionString = String.format("A^%s^S^%s^%s",systemVersion,appVersion,uuid); VolleyDispatcher.getInstance().setOnPreDispatchListener(mOnPreDispatchListener); UserManager.getInstance().registerListener(loginExpireListener); } private OnPreDispatchListener mOnPreDispatchListener = new OnPreDispatchListener() { @Override public void onPreDispatchRequest(HttpRequest<?> req) { UserModel user = UserManager.getInstance().getCurrentUser(); if (user != null) { req.addParam("accessToken", user.getAccessToken()); } req.addHeader("version",versionString); } }; }
true
5f28e54298bdca3582e5ab7a2be0f86360f695f0
Java
NeillWhite/eBiomer
/ShadeRef.java
UTF-8
30,872
2.015625
2
[ "MIT" ]
permissive
package com.goosebumpanalytics.biomer; /** * * ShadeRef.java * Copyright (c) 1998 Peter McCluskey, all rights reserved. * based in part on the code from transfor.c, pixutils.c and render.c in * RasMol2 Molecular Graphics by Roger Sayle, August 1995, Version 2.6 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and other materials provided with the distribution. * * This software is provided "as is" and any express or implied warranties, * including, but not limited to, the implied warranties of merchantability * or fitness for any particular purpose are disclaimed. In no event shall * Peter McCluskey be liable for any direct, indirect, incidental, special, * exemplary, or consequential damages (including, but not limited to, * procurement of substitute goods or services; loss of use, data, or * profits; or business interruption) however caused and on any theory of * liability, whether in contract, strict liability, or tort (including * negligence or otherwise) arising in any way out of the use of this * software, even if advised of the possibility of such damage. */ import java.awt.Color; import java.awt.image.MemoryImageSource; import java.awt.image.DirectColorModel; import java.awt.image.ColorModel; import java.awt.image.ImageProducer; import java.awt.*; import java.util.Vector; class RefCountColor { int refcount; Color color; RefCountColor(int r,int g,int b) { color = new Color(r,g,b); refcount = 0; } RefCountColor() { color = null; refcount = 0; } public final int getRed(){ return color.getRed(); } public final int getGreen(){ return color.getGreen(); } public final int getBlue(){ return color.getBlue(); } } class ViewStruct extends Object { public int fbuf[]; public short dbuf[]; public int xmax, ymax; public int yskip; public int size; ViewStruct(int high, int wide) { ymax = high; yskip = xmax = wide; int dx; if( (dx = xmax%4) != 0) xmax += 4-dx; size = xmax*ymax; fbuf = new int[size + 32]; dbuf = new short[size + 32]; int i; for(i = 0; i < size; ++i) dbuf[i] = -32000; } } class ArcEntry extends Object { static final int ARCSIZE = 2048; short dx,dy,dz; short inten; int offset; ArcEntry() { dx = dy = dz = 0; inten = 0; offset = 0; } } public class ShadeRef { int col; int shade; Color color; static ViewStruct view; static short LookUp[][]; private static final double Ambient = 0.05; private static final boolean EIGHTBIT = false; private static final int DefaultColDepth = (EIGHTBIT ? 16 : 32); private static int ColourDepth = DefaultColDepth; private static int ColourMask = ColourDepth-1; private static final int LutSize = (EIGHTBIT ? 256 : 1024); private static int Lut[] = new int[LutSize]; private static ColorModel colorModel; private static boolean ULut[] = new boolean[LutSize]; private static int RLut[] = new int[LutSize]; private static int GLut[] = new int[LutSize]; private static int BLut[] = new int[LutSize]; private static final int BackCol = 0; private static final int BoxCol = 1; private static final int LabelCol = 2; private static final int FirstCol = 3; private static int BackR,BackG,BackB; private static int LabR,LabG,LabB; private static int BoxR,BoxG,BoxB; private static boolean UseBackFade = false; private static int screenX, screenY, screenZ, staticColor, radius; public static long t1 = System.currentTimeMillis(); static ArcEntry ArcAc[] = new ArcEntry[ArcEntry.ARCSIZE]; static int ArcAcPtr = 0; static ArcEntry ArcDn[] = new ArcEntry[ArcEntry.ARCSIZE]; static int ArcDnPtr = 0; static boolean shiny = false; /* These values set the sizes of the sphere rendering * tables. The first value, maxrad, is the maximum * sphere radius and the second value is the table * size = (maxrad*(maxrad+1))/2 + 1 */ //#define MAXTABLE 32641 private static final int MAXRAD = 255; private static int ColConst[] = new int[MAXRAD]; private static final int MAXSHADE = 32; /* private static ShadeRef ScaleRef[] = new ShadeRef[MAXSHADE]; */ private static RefCountColor Shade[] = null; /* private static int MaskColour[MAXMASK]; private static int MaskShade[MAXMASK]; */ private static int ScaleCount; private static int LastShade; private static double LastRX,LastRY,LastRZ; private static double Zoom; public static int Colour2Shade(int x){ return ((int)((x)-FirstCol)/ColourDepth); } public static int Shade2Colour(int x){ return ((x)*ColourDepth+FirstCol); } public ShadeRef(int cola,int shadea,int r,int g,int b) { color = new Color(r,g,b); col = cola; shade = shadea; } private static boolean MatchChar(char a,char b){ return (((a)=='#')||((a)==(b))); } private static final double RootSix = Math.sqrt(6); private static final int ColBits = 24; static void InitialiseTransform() { Shade = new RefCountColor[MAXSHADE]; final boolean APPLEMAC = false; if(APPLEMAC) LastShade = Colour2Shade(LutSize-1); else LastShade = Colour2Shade(LutSize); int i; for( i=0; i<LastShade; i++ ) Shade[i] = new RefCountColor(); int rad; for( rad=0; rad<MAXRAD; rad++ ) { int maxval = (int)(RootSix*rad)+4; ColConst[rad] = (ColourDepth<<ColBits)/maxval; } InitialiseTables(); ResetColourMap(); } private static int CPKMAX(){ return CPKShade.length; } private static final ShadeRef CPKShade[] = { new ShadeRef( 0, 0, 200, 200, 200 ), /* 0 Light Grey */ new ShadeRef( 0, 0, 143, 143, 255 ), /* 1 Sky Blue */ new ShadeRef( 0, 0, 240, 0, 0 ), /* 2 Red */ new ShadeRef( 0, 0, 255, 200, 50 ), /* 3 Yellow */ new ShadeRef( 0, 0, 255, 255, 255 ), /* 4 White */ new ShadeRef( 0, 0, 255, 192, 203 ), /* 5 Pink */ new ShadeRef( 0, 0, 218, 165, 32 ), /* 6 Golden Rod */ new ShadeRef( 0, 0, 0, 0, 255 ), /* 7 Blue */ new ShadeRef( 0, 0, 255, 165, 0 ), /* 8 Orange */ new ShadeRef( 0, 0, 128, 128, 144 ), /* 9 Dark Grey */ new ShadeRef( 0, 0, 165, 42, 42 ), /* 10 Brown */ new ShadeRef( 0, 0, 160, 32, 240 ), /* 11 Purple */ new ShadeRef( 0, 0, 255, 20, 147 ), /* 12 Deep Pink */ new ShadeRef( 0, 0, 0, 255, 0 ), /* 13 Green */ new ShadeRef( 0, 0, 178, 34, 34 ), /* 14 Fire Brick */ new ShadeRef( 0, 0, 34, 139, 34 ) }; /* 15 Forest Green */ private static final ShadeRef Shapely[] = { new ShadeRef(0, 0, 140, 255, 140 ), /* ALA */ new ShadeRef(0, 0, 255, 255, 255 ), /* GLY */ new ShadeRef(0, 0, 69, 94, 69 ), /* LEU */ new ShadeRef(0, 0, 255, 112, 66 ), /* SER */ new ShadeRef(0, 0, 255, 140, 255 ), /* VAL */ new ShadeRef(0, 0, 184, 76, 0 ), /* THR */ new ShadeRef(0, 0, 71, 71, 184 ), /* LYS */ new ShadeRef(0, 0, 160, 0, 66 ), /* ASP */ new ShadeRef(0, 0, 0, 76, 0 ), /* ILE */ new ShadeRef(0, 0, 255, 124, 112 ), /* ASN */ new ShadeRef(0, 0, 102, 0, 0 ), /* GLU */ new ShadeRef(0, 0, 82, 82, 82 ), /* PRO */ new ShadeRef(0, 0, 0, 0, 124 ), /* ARG */ new ShadeRef(0, 0, 83, 76, 66 ), /* PHE */ new ShadeRef(0, 0, 255, 76, 76 ), /* GLN */ new ShadeRef(0, 0, 140, 112, 76 ), /* TYR */ new ShadeRef(0, 0, 112, 112, 255 ), /* HIS */ new ShadeRef(0, 0, 255, 255, 112 ), /* CYS */ new ShadeRef(0, 0, 184, 160, 66 ), /* MET */ new ShadeRef(0, 0, 79, 70, 0 ), /* TRP */ new ShadeRef(0, 0, 255, 0, 255 ), /* ASX */ new ShadeRef(0, 0, 255, 0, 255 ), /* GLX */ new ShadeRef(0, 0, 255, 0, 255 ), /* PCA */ new ShadeRef(0, 0, 255, 0, 255 ), /* HYP */ new ShadeRef(0, 0, 160, 160, 255 ), /* A */ new ShadeRef(0, 0, 255, 140, 75 ), /* C */ new ShadeRef(0, 0, 255, 112, 112 ), /* G */ new ShadeRef(0, 0, 160, 255, 160 ), /* T */ new ShadeRef(0, 0, 184, 184, 184 ), /* 28 -> BackBone */ new ShadeRef(0, 0, 94, 0, 94 ), /* 29 -> Special */ new ShadeRef(0, 0, 255, 0, 255 ) }; /* 30 -> Default */ private static final ShadeRef AminoShade[] = { new ShadeRef(0, 0, 230, 10, 10 ), /* 0 ASP, GLU */ new ShadeRef(0, 0, 20, 90, 255 ), /* 1 LYS, ARG */ new ShadeRef(0, 0, 130, 130, 210 ), /* 2 HIS */ new ShadeRef(0, 0, 250, 150, 0 ), /* 3 SER, THR */ new ShadeRef(0, 0, 0, 220, 220 ), /* 4 ASN, GLN */ new ShadeRef(0, 0, 230, 230, 0 ), /* 5 CYS, MET */ new ShadeRef(0, 0, 200, 200, 200 ), /* 6 ALA */ new ShadeRef(0, 0, 235, 235, 235 ), /* 7 GLY */ new ShadeRef(0, 0, 15, 130, 15 ), /* 8 LEU, VAL, ILE */ new ShadeRef(0, 0, 50, 50, 170 ), /* 9 PHE, TYR */ new ShadeRef(0, 0, 180, 90, 180 ), /* 10 TRP */ new ShadeRef(0, 0, 220, 150, 130 ), /* 11 PRO, PCA, HYP */ new ShadeRef(0, 0, 190, 160, 110 ) }; /* 12 Others */ private static final int AminoIndex[] = { 6, /*ALA*/ 7, /*GLY*/ 8, /*LEU*/ 3, /*SER*/ 8, /*VAL*/ 3, /*THR*/ 1, /*LYS*/ 0, /*ASP*/ 8, /*ILE*/ 4, /*ASN*/ 0, /*GLU*/ 11, /*PRO*/ 1, /*ARG*/ 9, /*PHE*/ 4, /*GLN*/ 9, /*TYR*/ 2, /*HIS*/ 5, /*CYS*/ 5, /*MET*/ 10, /*TRP*/ 4, /*ASX*/ 4, /*GLX*/ 11, /*PCA*/ 11 /*HYP*/ }; private static final ShadeRef HBondShade[] = { new ShadeRef(0, 0, 255, 255, 255 ), /* 0 Offset = 2 */ new ShadeRef(0, 0, 255, 0, 255 ), /* 1 Offset = 3 */ new ShadeRef(0, 0, 255, 0, 0 ), /* 2 Offset = 4 */ new ShadeRef(0, 0, 255, 165, 0 ), /* 3 Offset = 5 */ new ShadeRef(0, 0, 0, 255, 255 ), /* 4 Offset = -3 */ new ShadeRef(0, 0, 0, 255, 0 ), /* 5 Offset = -4 */ new ShadeRef(0, 0, 255, 255, 0 ) }; /* 6 Others */ private static final ShadeRef StructShade[] = { new ShadeRef(0, 0, 255, 255, 255 ), /* 0 Default */ new ShadeRef(0, 0, 255, 0, 128 ), /* 1 Alpha Helix */ new ShadeRef(0, 0, 255, 200, 0 ), /* 2 Beta Sheet */ new ShadeRef(0, 0, 96, 128, 255 ) }; /* 3 Turn */ private static final ShadeRef PotentialShade[] = { new ShadeRef(0, 0, 255, 0, 0 ), /* 0 Red 25 < V */ new ShadeRef(0, 0, 255, 165, 0 ), /* 1 Orange 10 < V < 25 */ new ShadeRef(0, 0, 255, 255, 0 ), /* 2 Yellow 3 < V < 10 */ new ShadeRef(0, 0, 0, 255, 0 ), /* 3 Green 0 < V < 3 */ new ShadeRef(0, 0, 0, 255, 255 ), /* 4 Cyan -3 < V < 0 */ new ShadeRef(0, 0, 0, 0, 255 ), /* 5 Blue -10 < V < -3 */ new ShadeRef(0, 0, 160, 32, 240 ), /* 6 Purple -25 < V < -10 */ new ShadeRef(0, 0, 255, 255, 255 ) }; /* 7 White V < -25 */ public static void CPKColourAttrib( Molecule m ) { int i; for( i=0; i<CPKMAX(); i++ ) CPKShade[i].col = 0; if(Shade == null) InitialiseTransform(); else ResetColourAttrib( m ); for(i = 0; i < m.numberOfAtoms; ++i) { Atom ptr = m.atom[ i ]; ShadeRef ref = CPKShade[ ptr.cpkColor ]; if(ref.col == 0) { ref.shade = DefineShade(ref.color.getRed(),ref.color.getGreen(),ref.color.getBlue() ); ref.col = Shade2Colour(ref.shade); } Shade[ref.shade].refcount++; ptr.setColor(ref.color,ref.col); } DefineColourMap(); } private static int DefineShade(int r, int g, int b ) { int d,dr,dg,db; int dist,best; int i; /* Already defined! */ for( i=0; i<LastShade; i++ ) if( Shade[i].refcount != 0) if( (Shade[i].color.getRed()==r) &&(Shade[i].color.getGreen()==g) &&(Shade[i].color.getBlue()==b) ) return(i); /* Allocate request */ for( i=0; i<LastShade; i++ ) if( Shade[i].refcount == 0) { Shade[i] = new RefCountColor(r,g,b); return(i); } System.err.println("Warning: Unable to allocate shade!"); best = dist = 0; /* Nearest match */ for( i=0; i<LastShade; i++ ) { dr = Shade[i].color.getRed() - r; dg = Shade[i].color.getGreen() - g; db = Shade[i].color.getBlue() - b; d = dr*dr + dg*dg + db*db; if( i == 0 || (d<dist) ) { dist = d; best = i; } } return( best ); } private static void ResetColourMap() { int i; /* if(EIGHTBIT) { for( i=0; i<256; i++ ) ULut[i] = false; } SpecPower = 8; FakeSpecular = False; Ambient = DefaultAmbient; */ UseBackFade = false; BackR = BackG = BackB = 0; BoxR = BoxG = BoxB = 255; LabR = LabG = LabB = 255; for( i=0; i<LastShade; i++ ) Shade[i].refcount = 0; /* ScaleCount = 0; */ } private static void ResetColourAttrib( Molecule m ) { int i; for(i = 0; i < m.numberOfAtoms; ++i) { Atom ptr = m.atom[ i ]; if ( ptr.getColorIndex() != 0 ) { int c = Colour2Shade(ptr.getColorIndex()); if(Shade[c].refcount > 0) Shade[c].refcount--; } } } private static void InitialiseTables() { int i,rad; short ptr[]; LookUp = new short[MAXRAD][MAXRAD]; LookUp[0][0] = 0; LookUp[1][0] = 1; LookUp[1][1] = 0; for( rad=2; rad<MAXRAD; rad++ ) { LookUp[rad][0] = (short)rad; int root = rad-1; int root2 = root*root; int arg = rad*rad; for( i=1; i<rad; i++ ) { /* arg = rad*rad - i*i */ arg -= (i<<1)-1; /* root = isqrt(arg) */ while( arg < root2 ) { root2 -= (root<<1)-1; root--; } /* Thanks to James Crook */ LookUp[rad][i] = (short)(((arg-root2)<i)? root : root+1); } LookUp[rad][rad] = 0; } } private static void SetLutEntry(int i, int r, int g, int b) { ULut[i] = true; RLut[i] = r; GLut[i] = g; BLut[i] = b; Lut[i] = (((r<<8)|g)<<8 ) | b; } private static double Power(double x, int y) { double result = x; while( y>1 ) { if((y&1) != 0) { result *= x; y--; } else { result *= result; y>>=1; } } return( result ); } private static void DefineColourMap() { double fade; double temp,inten; int col,r,g,b; int i,j,k; boolean DisplayMode = false; for( i=0; i<LutSize; i++ ) ULut[i] = false; colorModel = new DirectColorModel(24,0xff0000,0xff00,0xff); if( !DisplayMode ) { SetLutEntry(BackCol,BackR,BackG,BackB); SetLutEntry(LabelCol,LabR,LabG,LabB); SetLutEntry(BoxCol,BoxR,BoxG,BoxB); } else SetLutEntry(BackCol,80,80,80); double diffuse = 1.0 - Ambient; if( DisplayMode ) { for( i=0; i<ColourDepth; i++ ) { temp = (double)i/ColourMask; inten = diffuse*temp + Ambient; /* Unselected [40,40,255] */ /* Selected [255,160,0] */ r = (int)(255*inten); g = (int)(160*inten); b = (int)(40*inten); SetLutEntry( FirstCol+i, b, b, r ); SetLutEntry( Shade2Colour(1)+i, r, g, 0 ); } } else for( i=0; i<ColourDepth; i++ ) { temp = (double)i/ColourMask; inten = diffuse*temp + Ambient; fade = 1.0-inten; k = 0; if( shiny ) { temp = Power(temp,8); k = (int)(255*temp); temp = 1.0 - temp; inten *= temp; fade *= temp; } for( j=0; j<LastShade; j++ ) if( Shade[j].refcount != 0) { col = Shade2Colour(j); if( UseBackFade ) { temp = 1.0-inten; r = (int)(Shade[j].getRed()*inten + fade*BackR); g = (int)(Shade[j].getGreen()*inten + fade*BackG); b = (int)(Shade[j].getBlue()*inten + fade*BackB); } else { r = (int)(Shade[j].getRed()*inten); g = (int)(Shade[j].getGreen()*inten); b = (int)(Shade[j].getBlue()*inten); } if( shiny ) { r += k; g += k; b += k; } SetLutEntry( col+i, r, g, b ); } } } private static void UpdateLine(int wide, int dy, int col, int z, int rad, int offset, int dxmin, int dxmax) { int dx = -wide; short tptr[] = LookUp[wide]; int tindex = wide; int stdcol = Lut[col]; int cc = ColConst[rad]; int r = 0; while(wide == 1 && (long)(512+wide-dy)*(long)cc > (long)Integer.MAX_VALUE) { // prevent overflow in low radius inten calc cc = ColConst[rad + ++r]; } while(dx < dxmin && dx < 0) { --tindex; ++dx; } offset += dx; while(dx < 0 && dx < dxmax) { int dz = tptr[tindex--]; short depth = (short)(dz + z); if(depth > view.dbuf[offset]) { view.dbuf[offset] = depth; int inten = dz+dz+dx-dy; if( inten>0 ) { inten = (inten*cc) >> ColBits; try { view.fbuf[offset] = Lut[col+inten]; }catch(ArrayIndexOutOfBoundsException e) { System.err.println("ArrayIndexOutOfBoundsException " + inten + " " + (dz+dz+dx-dy) + "*" + cc + " r " + r); } } else view.fbuf[offset] = stdcol; } ++dx; ++offset; } if(dx < dxmax) { while(dx < dxmin) { ++tindex; ++dx; ++offset; } do { int dz = tptr[tindex++]; short depth = (short)(dz + z); if(depth > view.dbuf[offset]) { view.dbuf[offset] = depth; int inten = (dz)+(dz)+dx-dy; if( inten>0 ) { inten = (inten*cc) >> ColBits; try { view.fbuf[offset] = Lut[col+inten]; }catch(ArrayIndexOutOfBoundsException e) { System.err.println("ArrayIndexOutOfBoundsException " + inten + " " + (dz+dz+dx-dy) + "*" + cc + " r " + r); } } else view.fbuf[offset] = stdcol; } ++dx; ++offset; } while(dx <= wide && dx < dxmax); } } public static void DrawSphere(int x, int y, int z, int rad, int col) { int offset = (y-rad)*view.yskip + x; int fold = offset; int dy = -rad; int dxmax = view.xmax - x; int dxmin = -x; if(rad >= MAXRAD) { System.err.println("radius too big " + rad); return; } //System.err.println("offset " + offset + " y " + y + " x " + x + " rad " + rad + " t " + (((System.currentTimeMillis() - t1)/10)/100.0)); while(dy < 0 && y + dy < view.ymax) { if(y + dy >= 0) { int wide = LookUp[rad][-dy]; UpdateLine(wide, dy, col, z, rad, fold, dxmin, dxmax); } fold += view.yskip; dy++; } if(y + dy < view.ymax) do { if(y + dy >= 0) { int wide = LookUp[rad][dy]; UpdateLine(wide, dy, col, z, rad, fold, dxmin, dxmax); } fold += view.yskip; dy++; } while(dy <= rad && y + dy < view.ymax); } private static void DrawArcAc(int dbase,int fbase,int z,int c) { int i; for(i = 0; i < ArcAcPtr; ++i) { ArcEntry ptr = ArcAc[i]; short depth = (short)(ptr.dz+z); int ix = dbase + ptr.offset; if(ix >= view.size) break; if(ix >= 0 && depth > view.dbuf[ix]) { view.dbuf[dbase + ptr.offset] = depth; view.fbuf[fbase + ptr.offset] = Lut[ptr.inten+c]; } } } private static void DrawArcDn(int dbase,int fbase,int z, int c) { int i; for(i = 0; i < ArcDnPtr; ++i) { ArcEntry ptr = ArcDn[i]; short depth = (short)(ptr.dz+z); int ix = dbase + ptr.offset; if(ix >= view.size) break; if(ix >= 0 && depth > view.dbuf[ix]) { view.dbuf[dbase + ptr.offset] = depth; view.fbuf[fbase + ptr.offset] = Lut[ptr.inten+c]; } } } private static void DrawCylinderCaps(int x1,int y1,int z1, int x2,int y2,int z2, int c1,int c2,int rad) { int offset; int dx,dy,dz; int lx = x2-x1; int ly = y2-y1; int end = ly*view.yskip+lx; int temp = y1*view.yskip+x1; int fold = temp; int dold = temp; ArcAcPtr = 0; ArcDnPtr = 0; if(ArcAc[0] == null) { int i; for(i = 0; i < ArcEntry.ARCSIZE; ++i) { ArcAc[i] = new ArcEntry(); ArcDn[i] = new ArcEntry(); } } temp = -(rad*view.yskip); short wptr[] = LookUp[rad]; for( dy= -rad; dy<=rad; dy++ ) { int wide = wptr[Math.abs(dy)]; short lptr[] = LookUp[wide]; for( dx= -wide; dx<=wide; dx++ ) { dz = lptr[Math.abs(dx)]; int inten = dz + dz + dx + dy; if( inten>0 ) { inten = (int)((inten*ColConst[rad])>>ColBits); }else inten = 0; offset = temp+dx; if((x1+dx) >= 0 && (x1+dx) < view.xmax && (y1+dy) >= 0 && (y1+dy) < view.ymax) { short depth = (short)(dz+z1); if(depth > view.dbuf[dold + offset]) { view.dbuf[dold + offset] = depth; view.fbuf[fold + offset] = Lut[inten+c1]; } } if((x2+dx) >= 0 && (x2+dx) < view.xmax && (y2+dy) >= 0 && (y2+dy) < view.ymax) { short depth = (short)(dz+z2); if(depth > view.dbuf[dold + offset + end]) { view.dbuf[dold + offset + end] = depth; view.fbuf[fold + offset + end] = Lut[inten+c2]; } } // an out of bounds exception here means an excessive radius ArcAc[ArcAcPtr].offset = offset; ArcAc[ArcAcPtr].inten = (short)inten; ArcAc[ArcAcPtr].dx=(short)dx; ArcAc[ArcAcPtr].dy=(short)dy; ArcAc[ArcAcPtr].dz=(short)dz; ArcAcPtr++; ArcDn[ArcDnPtr].offset = offset; ArcDn[ArcDnPtr].inten = (short)inten; ArcDn[ArcDnPtr].dx=(short)dx; ArcDn[ArcDnPtr].dy=(short)dy; ArcDn[ArcDnPtr].dz=(short)dz; ArcDnPtr++; } temp += view.yskip; } } public static void DrawCylinder(int x1,int y1,int z1, int x2,int y2,int z2, int c1,int c2,int rad) { int dbase; int fbase; int zrate,zerr,ystep,err; int ix,iy,ax,ay; int lx,ly,lz; int mid,tmp; int temp; if(rad > 25) { System.err.println("bond radius " + rad + " too large; set to 25"); rad = 25; } if(false) System.err.println(x1 + "," + y1 + " - " + x2 + "," + y2 + " colors " + c1 + " " + c2 + " radius " + rad); /* Trivial Case */ if( (x1==x2) && (y1==y2) ) { if( z1>z2 ) { DrawSphere(x1,y1,z1,rad,c1); } else DrawSphere(x2,y2,z2,rad,c2); return; } if( z1<z2 ) { tmp=x1; x1=x2; x2=tmp; tmp=y1; y1=y2; y2=tmp; tmp=z1; z1=z2; z2=tmp; tmp=c1; c1=c2; c2=tmp; } DrawCylinderCaps(x1,y1,z1,x2,y2,z2,c1,c2,rad); lx = x2-x1; ly = y2-y1; lz = z2-z1; if( ly>0 ) { ystep = view.yskip; ay = ly; iy = 1; } else { ystep = -view.yskip; ay = -ly; iy = -1; } if( lx>0 ) { ax = lx; ix = 1; } else { ax = -lx; ix = -1; } zrate = lz/Math.max(ax,ay); temp = y1*view.yskip+x1; fbase = temp; dbase = temp; if( ax>ay ) { lz -= ax*zrate; zerr = err = -(ax>>1); if( c1 != c2 ) { mid = (x1+x2)>>1; while( x1!=mid ) { z1 += zrate; if( (zerr-=lz)>0 ) { zerr-=ax; z1--; } fbase+=ix; dbase+=ix; x1+=ix; if( (err+=ay)>0 ) { fbase+=ystep; dbase+=ystep; err-=ax; if(y1 >= 0 && y1 < view.ymax) DrawArcDn(dbase,fbase,z1,c1); } else if(y1 >= 0 && y1 < view.ymax) DrawArcAc(dbase,fbase,z1,c1); } } while( x1!=x2 ) { z1 += zrate; if( (zerr-=lz)>0 ) { zerr-=ax; z1--; } fbase+=ix; dbase+=ix; x1+=ix; if( (err+=ay)>0 ) { fbase+=ystep; dbase+=ystep; err-=ax; if(y1 >= 0 && y1 < view.ymax) DrawArcDn(dbase,fbase,z1,c2); } else if(y1 >= 0 && y1 < view.ymax) DrawArcAc(dbase,fbase,z1,c2); } } else /*ay>=ax*/ { lz -= ay*zrate; zerr = err = -(ay>>1); if( c1 != c2 ) { mid = (y1+y2)>>1; while( y1!=mid ) { z1 += zrate; if( (zerr-=lz)>0 ) { zerr-=ay; z1--; } fbase+=ystep; dbase+=ystep; y1+=iy; if( (err+=ax)>0 ) { fbase+=ix; dbase+=ix; err-=ay; if(y1 >= 0 && y1 < view.ymax) DrawArcAc(dbase,fbase,z1,c1); } if(y1 >= 0 && y1 < view.ymax) DrawArcDn(dbase,fbase,z1,c1); } } while( y1!=y2) { z1 += zrate; if( (zerr-=lz)>0 ) { zerr-=ay; z1--; } fbase+=ystep; dbase+=ystep; y1+=iy; if( (err+=ax)>0 ) { fbase+=ix; dbase+=ix; err-=ay; if(y1 >= 0 && y1 < view.ymax) DrawArcAc(dbase,fbase,z1,c2); } else if(y1 >= 0 && y1 < view.ymax) DrawArcDn(dbase,fbase,z1,c2); } } } public static void DrawLine(int x1,int y1,int z1, int x2,int y2,int z2, int color, int width) { int dbase; int fbase; int zrate,zerr,ystep,err; int ix,iy,ax,ay; int lx,ly,lz; int mid,tmp; int temp; if(width > 25) { System.err.println("bond radius " + width + " too large; set to 25"); width = 25; } /* Trivial Case */ if( (x1==x2) && (y1==y2) ) { if( z1>z2 ) { DrawSphere(x1,y1,z1,width,color); } else DrawSphere(x2,y2,z2,width,color); return; } if( z1<z2 ) { tmp=x1; x1=x2; x2=tmp; tmp=y1; y1=y2; y2=tmp; tmp=z1; z1=z2; z2=tmp; } lx = x2-x1; ly = y2-y1; lz = z2-z1; if( ly>0 ) { ystep = view.yskip; ay = ly; iy = 1; } else { ystep = -view.yskip; ay = -ly; iy = -1; } if( lx>0 ) { ax = lx; ix = 1; } else { ax = -lx; ix = -1; } zrate = lz/Math.max(ax,ay); temp = y1*view.yskip+x1; fbase = temp; dbase = temp; if( ax>ay ) { lz -= ax*zrate; zerr = err = -(ax>>1); while( x1!=x2 ) { z1 += zrate; if( (zerr-=lz)>0 ) { zerr-=ax; z1--; } fbase+=ix; dbase+=ix; x1+=ix; if( (err+=ay)>0 ) { fbase+=ystep; dbase+=ystep; err-=ax; if(x1 >= 0 && x1 < view.xmax && fbase > 0 && fbase < view.fbuf.length) UpdateLine(1, y1, color, z1, width, fbase, 0, view.ymax); } else if(x1 >= 0 && x1 < view.xmax && fbase > 0 && fbase < view.fbuf.length) UpdateLine(1, y1, color, z1, width, fbase, 0, view.ymax); } } else /*ay>=ax*/ { lz -= ay*zrate; zerr = err = -(ay>>1); while( y1!=y2) { z1 += zrate; if( (zerr-=lz)>0 ) { zerr-=ay; z1--; } fbase+=ystep; dbase+=ystep; y1+=iy; if( (err+=ax)>0 ) { fbase+=ix; dbase+=ix; err-=ay; if(y1 >= 0 && y1 < view.ymax && fbase > 0 && fbase < view.fbuf.length) UpdateLine(1, y1, color, z1, width, fbase, 0, view.ymax); } else if(y1 >= 0 && y1 < view.ymax && fbase > 0 && fbase < view.fbuf.length) UpdateLine(1, y1, color, z1, width, fbase, 0, view.ymax); } } } private static void Resize(int high, int wide) { if(view == null || view.xmax != wide || view.ymax != high) { view = new ViewStruct(high,wide); } } public static ImageProducer imageProducer(int xmax, int ymax) { InitialiseTransform(); Resize(ymax, xmax); t1 = System.currentTimeMillis(); return new MemoryImageSource(view.xmax, view.ymax, colorModel, view.fbuf, 0, view.yskip); } } /* void AminoColourAttrib() { ShadeRef *ref; Chain __far *chain; Group __far *group; Atom __far *ptr; int i; if( !Database ) return; for( i=0; i<13; i++ ) AminoShade[i].col = 0; ResetColourAttrib(); ForEachAtom if( ptr->flag&SelectFlag ) { if( IsAmino(group->refno) ) { ref = AminoShade + AminoIndex[group->refno]; } else ref = AminoShade+12; if( !ref->col ) { ref->shade = DefineShade( ref->r, ref->g, ref->b ); ref->col = Shade2Colour(ref->shade); } Shade[ref->shade].refcount++; ptr->col = ref->col; } } void ShapelyColourAttrib() { ShadeRef *ref; Chain __far *chain; Group __far *group; Atom __far *ptr; int i; if( !Database ) return; for( i=0; i<30; i++ ) Shapely[i].col = 0; ResetColourAttrib(); ForEachAtom if( ptr->flag&SelectFlag ) { if( IsAminoNucleo(group->refno) ) { ref = Shapely + group->refno; } else ref = Shapely+30; if( !ref->col ) { ref->shade = DefineShade( ref->r, ref->g, ref->b ); ref->col = Shade2Colour(ref->shade); } Shade[ref->shade].refcount++; ptr->col = ref->col; } } void StructColourAttrib() { ShadeRef *ref; Chain __far *chain; Group __far *group; Atom __far *ptr; int i; if( !Database ) return; if( InfoHelixCount<0 ) DetermineStructure(False); for( i=0; i<4; i++ ) StructShade[i].col = 0; ResetColourAttrib(); ForEachAtom if( ptr->flag&SelectFlag ) { if( group->struc & HelixFlag ) { ref = StructShade+1; } else if( group->struc & SheetFlag ) { ref = StructShade+2; } else if( group->struc & TurnFlag ) { ref = StructShade+3; } else ref = StructShade; if( !ref->col ) { ref->shade = DefineShade( ref->r, ref->g, ref->b ); ref->col = Shade2Colour(ref->shade); } Shade[ref->shade].refcount++; ptr->col = ref->col; } } int IsCPKColour(atom ptr ) { ShadeRef *cpk; ShadeDesc *col; cpk = CPKShade + Element[ptr->elemno].cpkcol; col = Shade + Colour2Shade(ptr->col); return( (col->r==cpk->r) && (col->g==cpk->g) && (col->b==cpk->b) ); } int IsVDWRadius( ptr ) Atom __far *ptr; { int rad; if( ptr->flag & SphereFlag ) { rad = ElemVDWRadius( ptr->elemno ); return( ptr->radius == rad ); } else return( False ); } */
true
0d728e12dd19e4a1f581c66d972ae058caf3874b
Java
AimeeCxy/superMarket
/src/com/shxt/supermarket/dialog/AddEmployeeInfor.java
GB18030
4,204
2.28125
2
[]
no_license
package com.shxt.supermarket.dialog; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import com.shxt.supermarket.utils.DBTools; public class AddEmployeeInfor extends Dialog { protected Object result; protected Shell shell; private Text text; private Text text_1; private Text text_2; private Text text_3; private Text text_4; private Text text_5; private Text text_6; private Text text_7; public AddEmployeeInfor(Shell parent, int style) { super(parent, style); setText("ԱϢ"); } public Object open(TableItem ti) { createContents(ti); shell.open(); shell.layout(); Display display = getParent().getDisplay(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } return result; } private void createContents(TableItem ti) { shell = new Shell(getParent(), getStyle()); shell.setSize(450, 300); shell.setText(getText()); Label lblId = new Label(shell, SWT.NONE); lblId.setBounds(34, 24, 31, 15); lblId.setText("ID"); Label lblNewLabel = new Label(shell, SWT.NONE); lblNewLabel.setBounds(34, 63, 31, 15); lblNewLabel.setText("\u59D3\u540D"); Label label = new Label(shell, SWT.NONE); label.setBounds(34, 105, 31, 15); label.setText("\u6027\u522B"); Label label_1 = new Label(shell, SWT.NONE); label_1.setBounds(34, 148, 31, 15); label_1.setText("\u5E74\u9F84"); text = new Text(shell, SWT.BORDER); text.setBounds(72, 21, 73, 21); text_1 = new Text(shell, SWT.BORDER); text_1.setBounds(72, 60, 73, 21); text_2 = new Text(shell, SWT.BORDER); text_2.setBounds(72, 102, 73, 21); text_3 = new Text(shell, SWT.BORDER); text_3.setBounds(72, 145, 73, 21); Label label_2 = new Label(shell, SWT.NONE); label_2.setBounds(173, 24, 31, 15); label_2.setText("\u5730\u5740"); Label label_3 = new Label(shell, SWT.NONE); label_3.setBounds(173, 63, 31, 15); label_3.setText("\u5BC6\u7801"); Label label_4 = new Label(shell, SWT.NONE); label_4.setBounds(173, 105, 31, 15); label_4.setText("\u9644\u52A0"); Label label_5 = new Label(shell, SWT.NONE); label_5.setBounds(173, 148, 31, 15); label_5.setText("\u7535\u8BDD"); text_4 = new Text(shell, SWT.BORDER); text_4.setBounds(210, 21, 130, 21); text_5 = new Text(shell, SWT.BORDER); text_5.setBounds(210, 60, 130, 21); text_6 = new Text(shell, SWT.BORDER); text_6.setBounds(210, 102, 130, 21); text_7 = new Text(shell, SWT.BORDER); text_7.setBounds(210, 145, 130, 21); Button btnAdd = new Button(shell, SWT.NONE); btnAdd.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if(text.getText().isEmpty()||text_1.getText().isEmpty()||text_2.getText().isEmpty()||text_3.getText().isEmpty()||text_4.getText().isEmpty()||text_5.getText().isEmpty()||text_6.getText().isEmpty()||text_7.getText().isEmpty()){ MessageBox message = new MessageBox(shell,SWT.ERROR); message.setText("ϵͳʾϢ"); message.setMessage("ҪӵԱϢ"); message.open(); }else{ DBTools db = DBTools.getDBTools("cxy_ccshxt", "cxy", "cxy"); result = db.updateNoIdReturnArrayByRCP("insert into employee (id,name,sex,age,address,password,elseinformation,telnumber,logiontime)values(?,?,?,?,?,?,?,?,?)", new Object[]{text.getText(),text_1.getText(),text_2.getText(),text_3.getText(),text_4.getText(),text_5.getText(),text_6.getText(),text_7.getText(),"δ¼"}); MessageBox message = new MessageBox(shell,SWT.CLOSE); message.setText("ϵͳʾϢ"); message.setMessage("һԱϢӳɹ~"); message.open(); shell.close(); } } }); btnAdd.setBounds(173, 202, 75, 25); btnAdd.setText("\u6DFB\u52A0"); } }
true
a6fac965c0430e215ba2c031f7271cda4c8c63e5
Java
guoqi1994/springboot-rocketmq
/src/main/java/com/willjo/mq/TransMessageRunner.java
UTF-8
3,949
2.171875
2
[]
no_license
package com.willjo.mq; import com.willjo.dal.entity.MqTransMessageEntity; import com.willjo.message.MqTransMessage; import com.willjo.service.MqTransMessageService; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.client.producer.SendStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import java.text.MessageFormat; import java.util.Objects; /** * @author willJo * @since 2020/12/16 */ public class TransMessageRunner implements ApplicationListener<ApplicationReadyEvent> { private static final Logger logger = LoggerFactory.getLogger(TransMessageRunner.class); @Autowired private RocketMqProducerService rocketMqProducerService; @Autowired private MqTransMessageService mqTransMessageService; /** * 事务最大等待时间,单位为秒 */ public static final int TRANS_MAX_WAITING_TIME = 30; @Override public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { System.out.println("run message send thread"); new Thread(() -> { while (true) { MqTransMessage message = null; try { message = MessageQueue.priorityQueue.take(); } catch (InterruptedException e) { } if (Objects.isNull(message)) { continue; } SendResult sendResult = null; try { String key = MessageFormat.format(MessageLock.LOCK_PREFIX, message.getId()); synchronized (key.intern()) { // 查询数据库确保是有值 MqTransMessageEntity mqTransMessageEntity = mqTransMessageService.selectById(message.getId()); if (Objects.isNull(mqTransMessageEntity)) { // 没有值有三种可能姓 ,一种是事务没结束,一种事务没成功,或者已经被定时任务发送了 long time = System.currentTimeMillis() - message.getCreateTime().getTime(); if(time / 1000 > TRANS_MAX_WAITING_TIME) { // 超过30秒还是查不到,就直接丢弃了,后面有定时任务兜底 logger.info(" due to over 30 second, discard message for messageId={}", message.getId()); } else { // 放到延迟队列处理 logger.info(" add message to delayQueue for messageId={}", message.getId()); MessageQueue.putInDelayQueue(message); } continue; } else { sendResult = rocketMqProducerService.synSend(message.getTopic(), message.getTag(), message.getMessage()); if (Objects.nonNull(sendResult) && SendStatus.SEND_OK.equals(sendResult.getSendStatus())) { mqTransMessageService.deleteById(message.getId()); } else { // 网路抖动等原因,继续放在优先队列进行发送 MessageQueue.priorityQueue.put(message); } } } } catch (Exception e) { logger.warn("mq send fail,message={}",e.getMessage(),e); MessageQueue.putInDelayQueue(message); } } },"transMessage").start(); } }
true
f2d213192f1b7723ac71d11d31ead7d2ac6b77d4
Java
ingogriebsch/bricks
/bricks-dashboard/src/test/java/com/github/ingogriebsch/bricks/dashboard/web/IndexControllerTest.java
UTF-8
8,459
1.632813
2
[ "Apache-2.0" ]
permissive
/*- * #%L * Bricks Dashboard * %% * Copyright (C) 2018 - 2019 Ingo Griebsch * %% * 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. * #L% */ package com.github.ingogriebsch.bricks.dashboard.web; import static java.util.stream.Collectors.toSet; import static com.github.ingogriebsch.bricks.dashboard.web.IndexController.MODEL_ATTRIBUTE_APPLICATIONS; import static com.github.ingogriebsch.bricks.dashboard.web.IndexController.MODEL_ATTRIBUTE_BREADCRUMB; import static com.github.ingogriebsch.bricks.dashboard.web.IndexController.PAGE_APPLICATIONS; import static com.github.ingogriebsch.bricks.dashboard.web.IndexController.PATH_APPLICATIONS; import static com.github.ingogriebsch.bricks.dashboard.web.IndexController.PATH_ROOT; import static com.github.ingogriebsch.bricks.dashboard.web.IndexController.buildPath; import static com.google.common.collect.Sets.newHashSet; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.springframework.http.MediaType.TEXT_HTML_VALUE; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import java.util.Set; import com.github.ingogriebsch.bricks.dashboard.DashboardProperties; import com.github.ingogriebsch.bricks.dashboard.service.ApplicationService; import com.github.ingogriebsch.bricks.model.Application; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; @ExtendWith(SpringExtension.class) @WebMvcTest(IndexController.class) public class IndexControllerTest { @Autowired private MockMvc mockMvc; @MockBean private ApplicationService applicationService; @MockBean private DashboardProperties dashboardProperties; @Test public void index_should_return_matching_redirect_if_isRedirectToApplicationViewIfOnlyOneAvailable_is_false() throws Exception { given(dashboardProperties.isRedirectToApplicationViewIfOnlyOneAvailable()).willReturn(false); ResultActions resultActions = mockMvc.perform(get(PATH_ROOT).accept(TEXT_HTML_VALUE)); resultActions.andExpect(status().is3xxRedirection()); resultActions.andExpect(redirectedUrl(PATH_APPLICATIONS)); verify(dashboardProperties).isRedirectToApplicationViewIfOnlyOneAvailable(); verifyNoMoreInteractions(dashboardProperties); verifyZeroInteractions(applicationService); } @Test public void index_should_return_matching_redirect_if_isRedirectToApplicationViewIfOnlyOneAvailable_is_true_and_no_applications_are_available() throws Exception { given(dashboardProperties.isRedirectToApplicationViewIfOnlyOneAvailable()).willReturn(true); given(applicationService.findAll()).willReturn(applications()); ResultActions resultActions = mockMvc.perform(get(PATH_ROOT).accept(TEXT_HTML_VALUE)); resultActions.andExpect(status().is3xxRedirection()); resultActions.andExpect(redirectedUrl(PATH_APPLICATIONS)); verify(dashboardProperties, times(1)).isRedirectToApplicationViewIfOnlyOneAvailable(); verifyNoMoreInteractions(dashboardProperties); verify(applicationService, times(1)).findAll(); verifyNoMoreInteractions(applicationService); } @Test public void index_should_return_matching_redirect_if_isRedirectToApplicationViewIfOnlyOneAvailable_is_true_and_several_applications_are_available() throws Exception { given(dashboardProperties.isRedirectToApplicationViewIfOnlyOneAvailable()).willReturn(true); given(applicationService.findAll()).willReturn(applications("id1", "id2", "id3")); ResultActions resultActions = mockMvc.perform(get(PATH_ROOT).accept(TEXT_HTML_VALUE)); resultActions.andExpect(status().is3xxRedirection()); resultActions.andExpect(redirectedUrl(PATH_APPLICATIONS)); verify(dashboardProperties, times(1)).isRedirectToApplicationViewIfOnlyOneAvailable(); verifyNoMoreInteractions(dashboardProperties); verify(applicationService, times(1)).findAll(); verifyNoMoreInteractions(applicationService); } @Test public void index_should_return_matching_redirect_if_isRedirectToApplicationViewIfOnlyOneAvailable_is_true_and_one_applications_is_available() throws Exception { String applicationId = "id1"; given(applicationService.findAll()).willReturn(applications(applicationId)); given(dashboardProperties.isRedirectToApplicationViewIfOnlyOneAvailable()).willReturn(true); ResultActions resultActions = mockMvc.perform(get(PATH_ROOT).accept(TEXT_HTML_VALUE)); resultActions.andExpect(status().is3xxRedirection()); resultActions.andExpect(redirectedUrl(buildPath(PATH_APPLICATIONS, applicationId))); verify(dashboardProperties, times(1)).isRedirectToApplicationViewIfOnlyOneAvailable(); verifyNoMoreInteractions(dashboardProperties); verify(applicationService, times(1)).findAll(); verifyNoMoreInteractions(applicationService); } @Test public void applications_should_return_matching_view_and_model_if_no_applications_are_available() throws Exception { given(applicationService.findAll()).willReturn(newHashSet()); ResultActions resultActions = mockMvc.perform(get(PATH_APPLICATIONS).accept(TEXT_HTML_VALUE)); resultActions.andExpect(status().isOk()); resultActions.andExpect(view().name(PAGE_APPLICATIONS)); resultActions.andExpect(model().attributeExists(MODEL_ATTRIBUTE_APPLICATIONS, MODEL_ATTRIBUTE_BREADCRUMB)); verify(applicationService).findAll(); verifyNoMoreInteractions(applicationService); verifyZeroInteractions(dashboardProperties); } @Test public void applications_should_return_matching_view_and_model_if_applications_are_available() throws Exception { given(applicationService.findAll()).willReturn(newHashSet(applications("id1", "id2", "id3"))); ResultActions resultActions = mockMvc.perform(get(PATH_APPLICATIONS).accept(TEXT_HTML_VALUE)); resultActions.andExpect(status().isOk()); resultActions.andExpect(view().name(PAGE_APPLICATIONS)); resultActions.andExpect(model().attributeExists(MODEL_ATTRIBUTE_APPLICATIONS, MODEL_ATTRIBUTE_BREADCRUMB)); verify(applicationService).findAll(); verifyNoMoreInteractions(applicationService); verifyZeroInteractions(dashboardProperties); } private static Set<Application> applications(String... ids) { return newHashSet(ids).stream().map(id -> application(id)).collect(toSet()); } private static Application application(String id) { Application application = new Application(); application.setId(id); application.setName(randomAlphabetic(12)); application.setDescription(randomAlphabetic(64)); application.setVersion("1.0.0"); return application; } }
true
39be23bc467046b28c0030911149236ae868a17c
Java
dance41ife/rateCurricula
/src/test/java/com/platform/OpenPlatformApplicationTests.java
UTF-8
3,531
2.0625
2
[]
no_license
package com.platform; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.platform.bean.Rel; import com.platform.bean.RespQues; import com.platform.bean.RespSubject; import com.platform.bean.Subject; import com.platform.dao.SubjectDao; import com.platform.service.QuesService; import com.platform.service.SubjectService; import com.platform.service.UserService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List; @SpringBootTest class OpenPlatformApplicationTests { @Autowired SubjectDao subjectDao; @Autowired UserService userService; @Autowired QuesService quesService; @Test void contextLoads() { } @Test void testMybatis01(){ System.out.println(subjectDao.findOneSubject().getSubject_name()); } @Test void testMybatis02(){ Subject subject = new Subject(); //subject.setSubject_id(2); subject.setSubject_tag("选修"); subject.setSubject_name("TEST_SubjectTag02"); subject.setSubject_path("XXXXX"); subjectDao.insertSingleSubject(subject); } @Test void testMybatis03(){ List<RespSubject> subjects = subjectDao.selectAllSubjectByUserName(1); subjects.forEach(item->{ System.out.println(item.getSubject_name()); }); } @Test void testMybatis04(){ //System.out.println(userService.findSingleUser("Megumi")); //System.out.println(userService.findSingleUserByNamePassW("Megumi","123456")); userService.addUser("Miziha","123456"); } @Test void testDate(){ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); System.out.println(df.format(new Date())); } @Test void testQues01(){ System.out.println(quesService.selectAllQuesBySubject(6).get(1)); } @Test void testQues02(){ RespQues ques = new RespQues(); ques.setSubject_id(6); ques.setQues_type("单"); ques.setQues_desc("以下谁是PG?"); ques.setAnswer1("宫城良田"); ques.setAnswer2("流川枫"); ques.setAnswer3("三井寿"); ques.setAnswer4("赤木刚宪"); ques.setTrue_answer("1"); ques.setCreate_by(0); quesService.insertSingleQues(ques); } @Test void testSubject01(){ subjectDao.selectAllSubject().forEach(item ->{ System.out.println(item.getSubject_name()); }); } @Test void testRel01(){ Rel rel = new Rel(); rel.setUser_id(2); rel.setSubject_id(3); subjectDao.insertSingleRel(rel); } @Test void testValidSubject() throws JsonProcessingException { List<RespSubject> lists = subjectDao.selectAllValidSubjectByUserName("Hinata"); ObjectMapper om = new ObjectMapper(); String list = om.writeValueAsString(lists); System.out.println(list); // Iterator<RespSubject> iterator = lists.iterator(); // while(iterator.hasNext()){ // System.out.println("1"); // RespSubject next = iterator.next(); // System.out.println(next.getSubject_name()); } @Test void testUpdatePoint(){ userService.UpdateUserPoint(1,"Megumi"); } }
true
de5ad9d87d9f06f8e4805af65abeec2a362a6bad
Java
quinnlin/fabric8
/components/fabric8-build-workflow/src/main/java/io/fabric8/workflow/build/trigger/BuildWorkItemHandler.java
UTF-8
4,284
2.203125
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2005-2015 Red Hat, Inc. * * Red Hat 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 io.fabric8.workflow.build.trigger; import io.fabric8.workflow.build.BuildCorrelationKey; import io.fabric8.workflow.build.correlate.BuildProcessCorrelator; import io.fabric8.workflow.build.correlate.BuildProcessCorrelators; import io.fabric8.utils.Strings; import org.kie.api.runtime.process.WorkItem; import org.kie.api.runtime.process.WorkItemHandler; import org.kie.api.runtime.process.WorkItemManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Invoked from inside a jBPM process to trigger a new build in OpenShift and register * the {@link BuildCorrelationKey} * of the new build into the {@link BuildProcessCorrelator} */ public class BuildWorkItemHandler implements WorkItemHandler { private static final transient Logger LOG = LoggerFactory.getLogger(BuildWorkItemHandler.class); private BuildProcessCorrelator buildProcessCorrelator = BuildProcessCorrelators.getSingleton(); private BuildTrigger buildTrigger = BuildTriggers.getSingleton(); public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { long processInstanceId = workItem.getProcessInstanceId(); long workItemId = workItem.getId(); String namespace = WorkItemHandlers.getMandatoryParameter(workItem, manager, "namespace"); String buildName = WorkItemHandlers.getMandatoryParameter(workItem, manager, "buildName"); LOG.info("Executing build: " + namespace + "/" + buildName + " processInstanceId: " + processInstanceId + " workItemId: " + workItemId); String buildUuid = null; try { buildUuid = triggerBuild(processInstanceId, workItemId, namespace, buildName); } catch (Exception e) { WorkItemHandlers.fail(workItem, manager, "Could not trigger build for namespace: " + namespace + " build: " + buildName, e); return; } if (Strings.isNullOrBlank(buildUuid)) { WorkItemHandlers.fail(workItem, manager, "Could not trigger build for namespace: " + namespace + " build: " + buildName); } // TODO else you could trigger completion using: // POST http://localhost:8080/jbpm-console/rest/runtime/demo:Build:1.0/workitem/INSERT_WORKITEMID_HERE/complete?map_Outcome=Success&map_ResultUrl=www.jbpm.org } /** * API to be invoked from the remote REST API */ public String triggerBuild(long processInstanceId, long workItemId, String namespace, String buildName) { String buildUuid; buildUuid = buildTrigger.trigger(namespace, buildName); LOG.info("Created " + buildUuid + " from build: " + namespace + "/" + buildName + " processInstanceId: " + processInstanceId + " workItemId: " + workItemId); if (Strings.isNotBlank(buildUuid)) { BuildCorrelationKey key = new BuildCorrelationKey(namespace, buildName, buildUuid); buildProcessCorrelator.putBuildWorkItemId(key, workItemId); } return buildUuid; } public void abortWorkItem(WorkItem workItem, WorkItemManager manager) { System.out.println("Aborting " + workItem.getParameter("BuildId")); } public BuildTrigger getBuildTrigger() { return buildTrigger; } public void setBuildTrigger(BuildTrigger buildTrigger) { this.buildTrigger = buildTrigger; } public BuildProcessCorrelator getBuildProcessCorrelator() { return buildProcessCorrelator; } public void setBuildProcessCorrelator(BuildProcessCorrelator buildProcessCorrelator) { this.buildProcessCorrelator = buildProcessCorrelator; } }
true
70cf6a25bfa24428ed5629ba7537caaf8c60496e
Java
unicorn2828/epam_task2_handling
/handling/src/main/java/by/kononov/handling/interpreter/MathExpression.java
UTF-8
132
1.882813
2
[]
no_license
package by.kononov.handling.interpreter; @FunctionalInterface public interface MathExpression{ void interpret(Context context); }
true
42adf47e908115a108bfc7f0c79cafd7e0a49487
Java
Scoped/WarriorCulturesShaolin
/WCS_common/WarriorCulturesShaolin/Scoped/com/github/lib/ItemIDs.java
UTF-8
4,537
1.835938
2
[]
no_license
package WarriorCulturesShaolin.Scoped.com.github.lib; public class ItemIDs { /** * Shaoli: Items */ public static final int ITEM_SHAOLIN_BLADES_ID_DEFAULT = 3862; public static final int ITEM_SHAOLIN_CLOTHS_ID_DEFAULT = 3864; public static final int ITEM_SHAOLIN_TIPS_ID_DEFAULT = 3865; public static final int ITEM_SHAOLIN_WEAPONHEADS_ID_DEFAULT = 3866; public static final int ITEM_SHAOLIN_IRONRING_ID_DEFAULT = 3867; public static final int ITEM_SHAOLIN_BAMBOOSHAFT_ID_DEFAULT = 3863; public static final int ITEM_SHAOLIN_STICKS_ID_DEFAULT = 3864; public static final int ITEM_DOOR_CHERRYWOOD_ID_DEFAULT = 3868; public static final int ITEM_DOOR_BAMBOO_ID_DEFAULT = 3869; /** * Shaolin Student: Armor - Number of final ints: 4 */ public static final int ITEM_SHAOLIN_STUDENT_LEGS_ID_DEFAULT = 3841; public static final int ITEM_SHAOLIN_STUDENT_ROBE_ID_DEFAULT = 3842; public static final int ITEM_SHAOLIN_STUDENT_HEADBAND_ID_DEFAULT = 3843; public static final int ITEM_SHAOLIN_STUDENT_SHOES_ID_DEFAULT = 3844; /** * Shaolin Student: Weapons - Number of final ints: 4 */ public static final int ITEM_SHAOLIN_MACHETE_ID_DEFAULT = 3845; public static final int ITEM_SHAOLIN_BUTTERFLY_ID_DEFAULT = 3846; public static final int ITEM_SHAOLIN_RISINGSUN_ID_DEFAULT = 3847; public static final int ITEM_SHAOLIN_DAO_ID_DEFAULT = 3848; /** * Shaolin Student: Spears(Top) - Number of final ints: 1 */ public static final int ITEM_SHAOLIN_HALBERD_ID_DEFAULT = 3849; /** * Shaolin Student: Tools - Number of final ints: 2 */ public static final int ITEM_SHAOLIN_SHOVEL_ID_DEFAULT = 3850; public static final int ITEM_SHAOLIN_SHEAR_ID_DEFAULT = 3851; public static final int ITEM_SHAOLIN_CARRYTORCH_ID_DEFAULT = 3868; /** * Monk Monk: Armor - Number of final ints: 4 */ public static final int ITEM_SHAOLIN_MONK_RATTANHATSHIELD_ID_DEFAULT = 3852; public static final int ITEM_SHAOLIN_MONK_ROBES_ID_DEFAULT = 3853; public static final int ITEM_SHAOLIN_MONK_SHOES_ID_DEFAULT = 3854; public static final int ITEM_SHAOLIN_MONK_PANTS_ID_DEFAULT = 3855; /** * Monk Monk: Weapons - Number of final ints: 4 */ public static final int ITEM_SHAOLIN_ROPEDART_ID_DEFAULT = 3856; public static final int ITEM_SHAOLIN_HOOKBLADE_ID_DEFAULT = 3857; public static final int ITEM_SHAOLIN_SWORD_ID_DEFAULT = 3858; public static final int ITEM_SHAOLIN_MASTERSTAFF_ID_DEFAULT = 3859; /** * Monk Monk: Spears(Top) - Number of final ints: 2 */ public static final int ITEM_SHAOLIN_SPEAR_ID_DEFAULT = 3860; public static final int ITEM_SHAOLIN_POLEARM_ID_DEFAULT = 3861; // None Final Ints /** * Shaolin Items */ public static int ITEM_SHAOLIN_BLADES_ID; public static int ITEM_SHAOLIN_CLOTHS_ID; public static int ITEM_SHAOLIN_TIPS_ID; public static int ITEM_SHAOLIN_WEAPONHEADS_ID; public static int ITEM_SHAOLIN_BAMBOOSHAFT_ID; public static int ITEM_SHAOLIN_STICKS_ID; public static int ITEM_SHAOLIN_IRONRING_ID; public static int ITEM_DOOR_CHERRYWOOD_ID; public static int ITEM_DOOR_BAMBOO_ID; /** * Shaolin: Armor */ public static int ITEM_SHAOLIN_STUDENT_LEGS_ID; public static int ITEM_SHAOLIN_STUDENT_ROBE_ID; public static int ITEM_SHAOLIN_STUDENT_HEADBAND_ID; public static int ITEM_SHAOLIN_STUDENT_SHOES_ID; public static int ITEM_SHAOLIN_LEGS_ID; public static int ITEM_SHAOLIN_ROBE_ID; public static int ITEM_SHAOLIN_HEADBAND_ID; public static int ITEM_SHAOLIN_SHOES_ID; /** * Shaolin Student: Weapons */ public static int ITEM_SHAOLIN_DAO_ID; public static int ITEM_SHAOLIN_MACHETE_ID; public static int ITEM_SHAOLIN_BUTTERFLY_ID; public static int ITEM_SHAOLIN_RISINGSUN_ID; /** * Shaolin Student: Spears(Top) */ public static int ITEM_SHAOLIN_HALBERD_ID; /** * Shaolin Student: Tools */ public static int ITEM_SHAOLIN_SHOVEL_ID; public static int ITEM_SHAOLIN_SHEAR_ID; public static int ITEM_SHAOLIN_CARRYTORCH_ID; /** * Shaolin Monk: Armor */ public static int ITEM_SHAOLIN_MONK_RATTANHATSHIELD_ID; public static int ITEM_SHAOLIN_MONK_ROBES_ID; public static int ITEM_SHAOLIN_MONK_SHOES_ID; public static int ITEM_SHAOLIN_MONK_PANTS_ID; /** * Shaolin Monk: Weapons */ public static int ITEM_SHAOLIN_ROPEDART_ID; public static int ITEM_SHAOLIN_HOOKBLADE_ID; public static int ITEM_SHAOLIN_SWORD_ID; public static int ITEM_SHAOLIN_MASTERSTAFF_ID; /** * Shaolin Monk: Spears(Top) */ public static int ITEM_SHAOLIN_SPEAR_ID; public static int ITEM_SHAOLIN_POLEARM_ID; }
true
320aa09bdf9d7573949a40a0dec68d0f3571f28c
Java
xdevroey/vibes
/vibes-selection/src/main/java/be/vibes/selection/random/UsageDrivenRandomSelector.java
UTF-8
3,117
2.53125
3
[ "Apache-2.0" ]
permissive
package be.vibes.selection.random; /*- * #%L * VIBeS: test case selection * %% * Copyright (C) 2014 - 2018 University of Namur * %% * 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. * #L% */ import be.vibes.selection.exception.SinkStateReachedException; import be.vibes.ts.State; import be.vibes.ts.TestCase; import be.vibes.ts.Transition; import be.vibes.ts.UsageModel; import com.google.common.collect.Lists; import java.util.Iterator; import java.util.List; /** * A selector to select random test cases from the given usage model, based on the weights of the different * transitions. Transitions with a higher weight have a higher probability to be selected during the selection process. * * @author Xavier Devroey - xavier.devroey@gmail.com */ public class UsageDrivenRandomSelector extends RandomTestCaseSelector { public UsageDrivenRandomSelector(UsageModel um, int maxNbrTry, int maxLength) { super(um, maxNbrTry, maxLength); } public UsageDrivenRandomSelector(UsageModel um) { super(um); } public UsageDrivenRandomSelector(UsageModel um, int maxLength) { super(um, maxLength); } @Override public UsageModel getTransitionSystem() { return (UsageModel) super.getTransitionSystem(); } @Override protected Transition getRandomTransition(TestCase tc) throws SinkStateReachedException { UsageModel um = getTransitionSystem(); State state = tc == null ? um.getInitialState() : tc.getLast().getTarget(); List<Transition> outgoings = Lists.newArrayList(um.getOutgoing(state)); if (outgoings.isEmpty()) { throw new SinkStateReachedException("Sink state " + state + " reached, could not select next transition!", state); } else { return getUsageBasedTransition(outgoings); } } private Transition getUsageBasedTransition(List<Transition> outgoings) { UsageModel um = getTransitionSystem(); // Get Maximum proba for remaining transitions double maxProba = 0; for (Transition tr : outgoings) { maxProba += um.getProbability(tr); } // Get the element with the proba' double randomNbr = random.nextDouble() * maxProba; int elemIdx = -1; maxProba = 0; Iterator<Transition> it = outgoings.iterator(); while (it.hasNext() && randomNbr >= maxProba) { Transition tr = it.next(); maxProba = maxProba + um.getProbability(tr); elemIdx++; } // Return the designated element return outgoings.get(elemIdx); } }
true
63ca4428a9d80f6a52e679c64c68da66e69cdbcb
Java
neerajtony73/java_codes
/Fib.java
UTF-8
288
2.484375
2
[]
no_license
NEERAJ TONY ID:1234083 HW_12 public class Fib { public static void main(String args[]){ int c0=0,c1=1,c2,i; int count=12; System.out.print(c0+" "+c1); for(i=2;i<count;i++){ c2=c0+c1; System.out.print(" "+c2); c0=c1; c1=c2; } } }
true
f06b6ab0b776644c5bcd3c1decef9d39df77d91d
Java
zhilien-tech/zhiliren-we
/we-web-parent/dlws-we-game/src/main/java/com/xiaoka/game/admin/checkFinance/service/FinanceService.java
UTF-8
1,558
1.804688
2
[]
no_license
package com.xiaoka.game.admin.checkFinance.service; import org.nutz.dao.pager.Pager; import com.xiaoka.game.admin.checkFinance.form.FinanceSqlForm; import com.xiaoka.game.admin.checkFinance.po.FinancePo; public interface FinanceService { /** * * 项目名称:dlws-xiaoka-game * 描述:财务审核列表 * 创建人: ln * 创建时间: 2016年8月11日 * 标记:admin * @param sqlForm * @param pager * @return * @version */ public Object queryCheckFinanceList(FinanceSqlForm sqlForm, Pager pager); /** * * 项目名称:dlws-xiaoka-game * 描述:根据ID获取提现内容详情,进行审核 * 创建人: ln * 创建时间: 2016年8月11日 * 标记: * @param sqlForm * @param pager * @return * @version */ public FinancePo getWidthAppById(Long uId, Pager pager); /** * * 项目名称:dlws-xiaoka-game * 描述:用户提现审核,审核失败 * 创建人: ln * 创建时间: 2016年8月11日 * 标记:ajax * @param queryForm 查询表单 * @param pager 分页对象 * @return * @version */ public Object checkFail(Long id); /** * * 项目名称:dlws-xiaoka-game * 描述:用户提现申请成功(打款) * 创建人: ln * 创建时间: 2016年8月12日 * 标记:用户提现申请成功(打款) * @param uId * @param pager * @return * @version */ public Object checkSuccess(Long id,String openId,Double checkMoney,Pager pager); }
true
cd6779c234667a35fe7c90c337c2ad0b22c00e84
Java
yizw/NewFastFrame
/chat/src/main/java/com/example/chat/mvp/PictureInfoTask/PicturePresenter.java
UTF-8
5,101
2.09375
2
[]
no_license
package com.example.chat.mvp.PictureInfoTask; import com.example.chat.api.PictureApi; import com.example.chat.base.Constant; import com.example.chat.bean.PictureBean; import com.example.chat.bean.PictureResponse; import com.example.chat.util.ChatUtil; import com.example.chat.util.LogUtil; import com.example.commonlibrary.BaseApplication; import com.example.commonlibrary.baseadapter.empty.EmptyLayout; import com.example.commonlibrary.utils.AppUtil; import com.google.gson.Gson; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; /** * 项目名称: TestChat * 创建人: 陈锦军 * 创建时间: 2017/1/9 0:07 * QQ: 1981367757 */ public class PicturePresenter extends PictureContacts.Presenter { private Gson mGson = new Gson(); private int mPage; public PicturePresenter(PictureContacts.View iView, PictureContacts.Model baseModel) { super(iView, baseModel); } @Override public void getPictureInfo(int page, final boolean showLoading) { mPage = page; if (mPage == 1) { baseModel.clearAllCacheData(); if (showLoading) { iView.showLoading("正在加载数据,请稍候.........."); } } LogUtil.e("加载的页数" + page); if (!AppUtil.isNetworkAvailable(BaseApplication.getInstance())) { iView.hideLoading(); iView.showError("网络连接失败", new EmptyLayout.OnRetryListener() { @Override public void onRetry() { getPictureInfo(mPage,showLoading); } }); return; } baseModel.getRepositoryManager().getApi(PictureApi.class) .getPictureInfo(ChatUtil.getPictureUrl(page)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<PictureResponse>() { @Override public void onSubscribe(@NonNull Disposable d) { addDispose(d); } @Override public void onNext(@NonNull PictureResponse pictureResponse) { LogUtil.e("接收到的图片数据" + mGson.toJson(pictureResponse)); if (!pictureResponse.isError()) { iView.onUpdatePictureInfo(pictureResponse.getResults()); for (PictureBean bean : pictureResponse.getResults()) { baseModel.savePictureInfo(bean.getUrl(), mGson.toJson(bean)); } baseModel.savePictureInfo(Constant.PICTURE_KEY + mPage, mGson.toJson(pictureResponse)); } else { LogUtil.e("服务器出错拉"); } } @Override public void onError(@NonNull Throwable e) { iView.hideLoading(); // 下拉加载设置重试,下拉加载不设置 if (mPage==1&&baseModel.getPictureInfo(Constant.PICTURE_KEY+mPage)==null) { iView.showError(e.getMessage(), new EmptyLayout.OnRetryListener() { @Override public void onRetry() { getPictureInfo(mPage,showLoading); } }); iView.showError(e.getMessage(),null); } iView.onUpdatePictureInfo(baseModel.getPictureInfo(Constant.PICTURE_KEY + mPage)); } @Override public void onComplete() { iView.hideLoading(); } }); } }
true
a042e2f4911dd065f0cd7407b3f21e7a10037bc2
Java
Faisal2736/MascoAndroid
/app/src/main/java/com/semicolons/masco/pk/dataModels/CartResponse.java
UTF-8
575
1.929688
2
[]
no_license
package com.semicolons.masco.pk.dataModels; import android.content.SharedPreferences; public class CartResponse { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } private SharedPreferences sharedPreferences; public void setSharedPreferences(SharedPreferences sharedPreferences) { this.sharedPreferences = sharedPreferences; } public SharedPreferences getSharedPreferences() { return sharedPreferences; } }
true
7ed79f9fe004127e4c5b4751dea58abdd354bae5
Java
rsnape/TechAdoption
/JReLM/edu/iastate/jrelm/rl/SimpleStatelessPolicy.java
UTF-8
14,619
2.96875
3
[]
no_license
/* * Created on Jun 21, 2004 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package edu.iastate.jrelm.rl; import java.util.ArrayList; import cern.jet.random.engine.MersenneTwister; import cern.jet.random.engine.RandomEngine; import edu.iastate.jrelm.core.Action; import edu.iastate.jrelm.core.ActionDomain; import edu.iastate.jrelm.util.SimpleEventGenerator; /** * A simple implementation of the StatelessPolicy interface. This is essentially a discrete * probability distribution governing the choice of Action from a given ActionDomain, * irrespective of the state of the world. To be used with a ReinforcementLearner * implementing a stateless algorithm. * * * @author Charles Gieseler * * @param <I> - the type used to identify Actions. * @param <A> - the type of Action used. * */ public class SimpleStatelessPolicy <I,A extends Action> extends AbstractStatelessPolicy<I,A> { private int randSeed; /** * Here a probability distribution function (pdf) is an array of probability values. When * used in conjuction with the eventGenerator, a value indicates the likelihood that * its index will be selected. * * Each Action has an ID and each Action ID has an index in the list of IDs kept * by the ActionDomain. The corresponding index in this probability distribution function * contains a probability value for that ID. So we have a mapping from probabilities to * Action IDs and from Action IDs to Actions. This allows the evenGenerator to use the * pdf to select Actions from the ActionDomain according to the specified probability * distribution. * * The probability values are modified by a ReinforcementLearner according to the * implemented learning algorithm. */ protected double[] probDistFunction; //Random number eventGenerator needed for the randomEngine event eventGenerator protected RandomEngine randomEngine; /* * Generates randomEngine events (action selections) according to the probabilities * over all actions in the ActionDomain. Probabilities are maintained in probDistFunction. */ // protected ModifiedEmpiricalWalker eventGenerator; protected SimpleEventGenerator eventGenerator; /* * The collection of possible Actions an agent is allowed to perform. */ protected ActionDomain<I,A> domain; /* * List of action ID's in the domain. Allows us to map from int values chosen given by * the event generator to actions in the domain. */ protected ArrayList<I> actionIDList; // Records the last action choosen by this policy. protected A lastAction; /* *************************************************************** * CONSTRUCTORS * ***************************************************************/ /** * Construct a SimpleStatelessPolicy using a given ActionDomain. Note, this * policy requires a finite domain of discrete actions. * * A new MersenneTwister seeded with the current time * ((int)System.currentTimeMillis()) is created as the RandomEngine for * this policy. Note: If creating multiple SimpleStatelessPolicies and * MersenneTwister is the desired RandomEngine, it will be more efficient to * create a single MersenneTwister and pass it to each new policy as it is * constructed. * * @see cern.jet.random.engine.MersenneTwister * * @param actionList - the collection of possible actions this policy learns over */ public SimpleStatelessPolicy(ActionDomain<I,A> actionDomain){ domain = actionDomain; randSeed = (int) System.currentTimeMillis(); randomEngine = new MersenneTwister(randSeed); //Initialize to uniform distribution int numActions = actionDomain.size(); probDistFunction = new double[numActions]; for(int i=0; i < numActions; i++) probDistFunction[i] = 1.0/((double)numActions); //System.out.println("SimpleStatelessLearner: "); //System.out.println(" probDistFunction[5]: " + probDistFunction[5]); //System.out.println(" 1.0/((double)numActions): " +1.0/((double)numActions) ); init(); } /** * Construct a SimplePolicy using the given ActionDomain and psuedo-random * generator seed. * * A new MersenneTwister seeded with the given seed value is created * as the RandomEngine for this policy. Note: If creating multiple * SimpleStatelessPolicies and MersenneTwister is the desired RandomEngine, * it will be more efficient to create a single MersenneTwister and pass it * to each new policy as it is constructed. * * @see cern.jet.random.engine.MersenneTwister * * @param aDomain - the collection of possible Actions * @param sDomain - the collection of possible States * @param randSeed - seed value for the random generator used in this policy */ public SimpleStatelessPolicy(ActionDomain<I,A> actionDomain, int randSeed){ domain = actionDomain; this.randSeed = randSeed; randomEngine = new MersenneTwister(this.randSeed); //Initialize to uniform distribution int numActions = actionDomain.size(); probDistFunction = new double[numActions]; for(int i=0; i < numActions; i++) probDistFunction[i] = 1.0/((double)numActions); init(); } /** * Construct a SimpleStatelessPolicy using a given ActionDomain and RandomEngine. Note, this * policy requires a finite domain of discrete actions. The policy will use the given * RandomEngine in selecting new choices. * * Note: RandomGenerator does not reveal the seed value being used. As such, * SimpleStatelessPolicy has no way of knowing what seed is being used when a pre-constructed * generator is supplied. SimpleStatlessPolicy will set the seed -1 and report this value * when getRandomSeed() is called. * * * @param actionList - the collection of possible actions this policy learns over * @param randomGen - the RandomEngine this policy will use */ public SimpleStatelessPolicy(ActionDomain<I,A> actionDomain, RandomEngine randomGen){ domain = actionDomain; randSeed = -1; randomEngine = randomGen; //Initialize to uniform distribution int numActions = actionDomain.size(); probDistFunction = new double[numActions]; for(int i=0; i < numActions; i++) probDistFunction[i] = 1.0/((double)numActions); init(); } /** * * A new MersenneTwister seeded with the current time * ((int)System.currentTimeMillis()) is created as the RandomEngine for * this policy. Note: If creating multiple SimplePolicies and MersenneTwister is the desired RandomEngine, * it will be more efficient to create a single MersenneTwister and pass it to each new policy * as it is constructed. * * @see cern.jet.random.engine.MersenneTwister */ public SimpleStatelessPolicy(ActionDomain<I,A> actionDomain, double[] initProbs){ domain = actionDomain; randSeed = (int) System.currentTimeMillis(); randomEngine = new MersenneTwister(randSeed); if(initProbs.length != domain.size()) throw new IllegalArgumentException("Cannot initialize policy with given initial" + " probabilities.\n Expected "+domain.size()+" values, but received "+ initProbs.length+". Using default uniform distribution."); probDistFunction = initProbs; init(); } public SimpleStatelessPolicy(ActionDomain<I,A> actionDomain, double[] initProbs, int randSeed) throws IllegalArgumentException{ domain = actionDomain; this.randSeed = randSeed; randomEngine = new MersenneTwister(this.randSeed); if(initProbs.length != domain.size()) throw new IllegalArgumentException("Cannot initialize policy with given initial" + " probabilities.\n Expected "+domain.size()+" values, but received "+ initProbs.length+". Using default uniform distribution."); probDistFunction = initProbs; init(); } /** * * Note: RandomGenerator does not reveal the seed value being used. As such, * SimpleStatelessPolicy has no way of knowing what seed is being used when a pre-constructed * generator is supplied. SimpleStatlessPolicy will set the seed -1 and report this value * when getRandomSeed() is called. * * @param actionDomain * @param initProbs * @param randomGen * @throws IllegalArgumentException */ public SimpleStatelessPolicy(ActionDomain<I,A> actionDomain, double[] initProbs, RandomEngine randomGen) throws IllegalArgumentException{ domain = actionDomain; this.randSeed = -1; randomEngine = randomGen; if(initProbs.length != domain.size()) throw new IllegalArgumentException("Cannot initialize policy with given initial" + " probabilities.\n Expected "+domain.size()+" values, but received "+ initProbs.length+". Using default uniform distribution."); probDistFunction = initProbs; init(); } /* *************************************************************** * INITIALIZATION * ***************************************************************/ protected void init(){ actionIDList = domain.getIDList(); // eventGenerator = new ModifiedEmpiricalWalker(probDistFunction, // ModifiedEmpiricalWalker.NO_INTERPOLATION, randomEngine); eventGenerator = new SimpleEventGenerator(probDistFunction, randomEngine); //Need to init the lastAction to something. Choose a random action lastAction = generateAction(); } /* *************************************************************** * MISCELLANEOUS * ***************************************************************/ /** * Choose an Action according to the current probability distribution * function. * * @return a new Action */ public A generateAction(){ int chosenIndex; I chosenID; A chosenAction; //Pick the index of an action. Note: indexes start at 0 chosenIndex = eventGenerator.nextEvent(); chosenID = actionIDList.get(chosenIndex); chosenAction = domain.getAction(chosenID); lastAction = chosenAction; return chosenAction; } /** * Reset this policy. Reverts to a uniform probability distribution over * the domain of actions. This only modifies the probability distribution. * It does not reset the RandomEngine. * * WARNING: This will effectivlely erase all learned Action probabilities * in this policy. * */ public void reset(){ int numActions = domain.size(); for(int i=0; i < numActions; i++) probDistFunction[i] = 1.0/((double)numActions); init(); } /* *************************************************************** * ACCESSOR METHODS * ***************************************************************/ /** * Retrieve the probability distribution used in selecting actions from the * action domain. * * @return the current probability distribution over the domain of actions. */ public double[] getDistribution() { return probDistFunction; } /** * Set the probability distribution used in selecting actions from the * action domain. The distribution is given as an array of doubles. * * Note: there should be a value for each Action in this policy's ActionDomain. Each * value is associated with the Action * * * @param distrib - the new collection of action choice probabilities */ public void setDistribution(double[] distrib) throws IllegalArgumentException{ if(distrib.length == domain.size()){ probDistFunction = distrib; // eventGenerator.setState(probDistFunction, ModifiedEmpiricalWalker.NO_INTERPOLATION); // eventGenerator.setState2(probDistFunction); eventGenerator.setState(probDistFunction); }else{ throw new IllegalArgumentException( "Cannot set given probability values." + " Expected "+domain.size()+" values, but received "+distrib.length+ ". Previous values will be used."); } } /** * Get the set of actions this policy uses. * @see edu.iastate.jrelm.rl.StatelessPolicy#getDomain() */ public ActionDomain<I,A> getActionDomain() { return domain; } /** * Retrieve the number of possible actions in the DiscreteFiniteDomain for * this policy. * * @return size of the ActionDomain */ public int getNumActions(){ return domain.size(); } /** * Get the last action chosen by this policy. * @see edu.iastate.jrelm.rl.StatelessPolicy#getLastAction() */ public A getLastAction(){ return lastAction; } /** * Gets the current probability of choosing an action. Parameter actionIndex indicates * which action in the policy's domain to lookup. If the given actionIndex is not within * the bounds of the domain, Not A Number is returned (Double.NaN). * * @param actionIndex - int indicator of which action to look up * @return the probability of the specified Action. Double.NaN if action index is out of * bounds for the domain of actions. */ public double getProbability(I actionID){ int index = actionIDList.indexOf(actionID); if((index >= 0) && (index < probDistFunction.length)) return probDistFunction[index]; else return Double.NaN; } /** * Updates the probability of choosing the indicated Action * * @param actionID - the index of the desired Action in this policy's ActionDomain. * @param newValue - new choice probability value to associate with this action. */ public void setProbability(I actionID, double newValue) { int index = actionIDList.indexOf(actionID); if(index >= 0 && index < domain.size()){ probDistFunction[index] = newValue; // eventGenerator.setState(probDistFunction, ModifiedEmpiricalWalker.NO_INTERPOLATION); // eventGenerator.setState2(probDistFunction); eventGenerator.setState(probDistFunction); }else{ throw new IllegalArgumentException( "Cannot set probability for action "+actionID + ". Action ID is not valid for this policy's ActionDomain."); } } /** * Sets the RandomEngine to be used by this policy. * * @param engine */ public void setRandomEngine(RandomEngine engine){ randomEngine = engine; eventGenerator.setRandomEngine(randomEngine); } public int getRandomSeed(){return randSeed; } /** * Resets the RandomEngine, initializing it with the given seed. The RandomEngine will * be set to a MersenneTwister. If you wish to use a different RandomEngine with this * seed, use setRandomEngine(RandomEngine). * * Note: Calling this method will create a new MersenneTwister. Repeated calls can lead * to perfomance issues. * * @see MersenneTwister cern.jet.random.engine.MersenneTwister * * @param seed - seed value */ public void setRandomSeed(int seed){ randSeed = seed; setRandomEngine(new MersenneTwister(seed)); } }
true
8d18ac6abde2aa0ef8a6b1c8d4916fcb6ba9ce13
Java
Geovany01/ProyectoProgra22021
/src/java/modelo/Puesto.java
UTF-8
4,499
2.671875
3
[]
no_license
package modelo; import java.awt.HeadlessException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import javax.swing.table.DefaultTableModel; public class Puesto { private int idPuesto; private String puesto; Conexion nuevaConexion; public Puesto() { } public Puesto(int idPuesto, String puesto) { this.idPuesto = idPuesto; this.puesto = puesto; } public int getIdPuesto() { return idPuesto; } public void setIdPuesto(int idPuesto) { this.idPuesto = idPuesto; } public String getPuesto() { return puesto; } public void setPuesto(String puesto) { this.puesto = puesto; } public HashMap dropSangre() { HashMap<String, String> drop = new HashMap(); try { String query = "SELECT idPuesto as id, puesto FROM puestos"; nuevaConexion = new Conexion(); nuevaConexion.abrirConexion(); ResultSet consulta = nuevaConexion.conexionBD.createStatement().executeQuery(query); while (consulta.next()) { drop.put(consulta.getString("id"), consulta.getString("puesto")); } nuevaConexion.cerrarConexion(); } catch (SQLException ex) { System.out.println(ex.getMessage()); } return drop; } public DefaultTableModel leer() { DefaultTableModel tabla = new DefaultTableModel(); try { nuevaConexion = new Conexion(); String query = "SELECT p.idPuesto as id, p.puesto FROM puestos as p;"; nuevaConexion.abrirConexion(); ResultSet consulta = nuevaConexion.conexionBD.createStatement().executeQuery(query); String encabezado[] = {"id", "puesto"}; tabla.setColumnIdentifiers(encabezado); String datos[] = new String[2]; while (consulta.next()) { datos[0] = consulta.getString("id"); datos[1] = consulta.getString("puesto"); tabla.addRow(datos); } nuevaConexion.cerrarConexion(); } catch (Exception ex) { System.out.println("Exception = " + ex.getMessage()); } return tabla; } public int agregar() { int retorno = 0; try { PreparedStatement parametro; String query; nuevaConexion = new Conexion(); nuevaConexion.abrirConexion(); query = "INSERT INTO puestos(puesto) VALUES(?);"; parametro = (PreparedStatement) nuevaConexion.conexionBD.prepareStatement(query); parametro.setString(1, getPuesto()); retorno = parametro.executeUpdate(); nuevaConexion.cerrarConexion(); } catch (HeadlessException | SQLException ex) { System.out.println("Error..." + ex.getMessage()); retorno = 0; } return retorno; } public int modificar() { int retorno = 0; try { PreparedStatement parametro; String query; nuevaConexion = new Conexion(); nuevaConexion.abrirConexion(); query = "update puestos set puesto=? where idPuesto = ?;"; parametro = (PreparedStatement) nuevaConexion.conexionBD.prepareStatement(query); parametro.setString(1, getPuesto()); parametro.setInt(2, getIdPuesto()); retorno = parametro.executeUpdate(); nuevaConexion.cerrarConexion(); } catch (HeadlessException | SQLException ex) { System.out.println("Error..." + ex.getMessage()); retorno = 0; } return retorno; } public int eliminar() { int retorno = 0; try { PreparedStatement parametro; String query; nuevaConexion = new Conexion(); nuevaConexion.abrirConexion(); query = "delete from puestos where idPuesto = ?;"; parametro = (PreparedStatement) nuevaConexion.conexionBD.prepareStatement(query); parametro.setInt(1, getIdPuesto()); retorno = parametro.executeUpdate(); nuevaConexion.cerrarConexion(); } catch (HeadlessException | SQLException ex) { System.out.println("Error..." + ex.getMessage()); retorno = 0; } return retorno; } }
true
3556e8aa5a5153eb133b08a71f49b371001ba1fd
Java
bbw1992/boot-netty-test
/netty-server/src/main/java/com/bai/server/HeartBeatSimpleHandle.java
UTF-8
5,473
2.359375
2
[ "Apache-2.0" ]
permissive
package com.bai.server; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; import io.netty.util.CharsetUtil; import lombok.extern.slf4j.Slf4j; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; @Slf4j public class HeartBeatSimpleHandle extends SimpleChannelInboundHandler<ByteBuf> { AtomicLong count = new AtomicLong(0); @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { log.info("channelInactive"); super.channelRegistered(ctx); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent idleStateEvent = (IdleStateEvent) evt; if (idleStateEvent.state() == IdleState.READER_IDLE) { log.info("失联了!"); log.info(ctx.channel().remoteAddress().toString()); //向客户端发送消息 ctx.writeAndFlush("Hello, are you still alive?").addListener(ChannelFutureListener.CLOSE_ON_FAILURE); } } super.userEventTriggered(ctx, evt); } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { log.info("channelRegistered"); String ip = ChannelUtil.getIp(ctx); ChannelUtil.channelMap.put(ip, ctx.channel()); for (Map.Entry<String, Channel> m : ChannelUtil.channelMap.entrySet()) { log.info("key:" + m.getKey()); log.info("value:" + m.getValue()); log.info("port:" + ChannelUtil.getPort(ctx)); } log.info("当前用户数 : {}", ChannelUtil.channelMap.size()); ChannelFuture future = ChannelUtil.channelMap.get(ip).writeAndFlush("register successed"); if (future.isDone()) { log.info(String.format("发送结果 : %s", future.isSuccess())); } super.channelRegistered(ctx); } @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { log.info("channelUnregistered"); ChannelUtil.channelMap.remove(ChannelUtil.getIp(ctx)); log.info("移除后用户数 : {}", ChannelUtil.channelMap.size()); super.channelUnregistered(ctx); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { log.info("channelActive"); super.channelActive(ctx); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { log.info("channelReadComplete"); super.channelReadComplete(ctx); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { log.info("handlerAdded"); log.info("当前用户id : {}", ctx.channel().id().asLongText()); super.handlerAdded(ctx); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { log.info("handlerRemoved"); log.info("移除当前用户id : {}", ctx.channel().id().asLongText()); super.handlerRemoved(ctx); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { log.info("exceptionCaught"); super.exceptionCaught(ctx, cause); } @Override public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { log.info("channelWritabilityChanged"); super.channelWritabilityChanged(ctx); } @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception { log.info("ByteBuf={}", byteBuf); byte[] barray = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, barray); log.info("ByteBuf array={}", Arrays.toString(barray)); byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.duplicate().readBytes(bytes); log.info(new String(bytes, CharsetUtil.ISO_8859_1)); log.info(new String(bytes, CharsetUtil.US_ASCII)); log.info(new String(bytes, CharsetUtil.UTF_8)); log.info(new String(bytes, CharsetUtil.UTF_16)); log.info(new String(bytes, CharsetUtil.UTF_16LE)); log.info(new String(bytes, Charset.forName("GBK"))); log.info("byteBuf={}", byteBuf); log.info("count : " + count.addAndGet(1)); ChannelFuture future = ctx.writeAndFlush("11111111111111111111111111111111111111111111111111111111111111111111111111111111111"); if (future.isDone()) { log.info(String.format("发送结果 : %s", future.isSuccess())); if (!future.isSuccess()) log.info(String.format("exception : %s", future.cause().getMessage())); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { log.info("msg={}", msg); ChannelFuture future = ctx.writeAndFlush("11111111111111111111111111111111111111111111111111111111111111111111111111111111111"); if (future.isDone()) { log.info(String.format("发送结果 : %s", future.isSuccess())); if (!future.isSuccess()) log.info(String.format("exception : %s", future.cause().getMessage())); } super.channelRead(ctx, msg); } }
true
d1b8a1415a80c5a2b735a51e619809b2273aff04
Java
beijingwode/factory_outside
/src/main/java/com/wode/factory/outside/controller/SmsProxyController.java
UTF-8
1,946
1.90625
2
[]
no_license
package com.wode.factory.outside.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONObject; import com.wode.comm.sms.client.SmsClient; import com.wode.common.util.ActResult; import com.wode.factory.stereotype.NoCheckAsync; import com.wode.factory.util.IPUtils; @Controller @RequestMapping("smsProxy") @ResponseBody public class SmsProxyController extends BaseController { static SmsClient client=new SmsClient(); @RequestMapping("sendSms") public ActResult<String> sendSms(String mobile, String signature, String content, String source,HttpServletRequest request) { return client.send(mobile, signature, content, IPUtils.getClientAddress(request), source); } @RequestMapping("sendSmsTempCode") @NoCheckAsync public ActResult<String> sendSmsTempCode(String mobile, String signature, String content, String source,String jSonParams,String outId,boolean isAsync, String notifyUrl,HttpServletRequest request) { if(isAsync) { JSONObject paramas = new JSONObject(); //String from= org.apache.commons.codec.binary.Base64.encodeBase64String(body.toJSONString().getBytes()); paramas.put("mobile",mobile); paramas.put("signature",signature); paramas.put("content",content); paramas.put("ip",IPUtils.getClientAddress(request)); paramas.put("source",source); paramas.put("outId",outId); paramas.put("jSonParams",org.apache.commons.codec.binary.Base64.encodeBase64String(jSonParams.getBytes())); Long cid = this.saveCommand("smsProxy", "sendSmsTempCode", notifyUrl, paramas); return ActResult.success(cid+""); } else { return client.send(mobile, signature, content, IPUtils.getClientAddress(request), source,jSonParams,outId); } } }
true
8bff263611ffbef2679f5dfb772a1bfee7976a2f
Java
ResurrectionRemix/android_frameworks_base
/core/java/android/hardware/camera2/utils/ArrayUtils.java
UTF-8
5,918
2.78125
3
[ "Apache-2.0", "LicenseRef-scancode-unicode" ]
permissive
/* * Copyright (C) 2014 The Android Open Source Project * * 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 android.hardware.camera2.utils; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Various assortment of array utilities. */ public class ArrayUtils { private static final String TAG = "ArrayUtils"; private static final boolean DEBUG = false; /** Return the index of {@code needle} in the {@code array}, or else {@code -1} */ public static <T> int getArrayIndex(T[] array, T needle) { if (array == null) { return -1; } int index = 0; for (T elem : array) { if (Objects.equals(elem, needle)) { return index; } index++; } return -1; } /** Return the index of {@code needle} in the {@code array}, or else {@code -1} */ public static int getArrayIndex(int[] array, int needle) { if (array == null) { return -1; } for (int i = 0; i < array.length; ++i) { if (array[i] == needle) { return i; } } return -1; } /** * Create an {@code int[]} from the {@code List<>} by using {@code convertFrom} and * {@code convertTo} as a one-to-one map (via the index). * * <p>Strings not appearing in {@code convertFrom} are ignored (with a logged warning); * strings appearing in {@code convertFrom} but not {@code convertTo} are silently * dropped.</p> * * @param list Source list of strings * @param convertFrom Conversion list of strings * @param convertTo Conversion list of ints * @return An array of ints where the values correspond to the ones in {@code convertTo} * or {@code null} if {@code list} was {@code null} */ public static int[] convertStringListToIntArray( List<String> list, String[] convertFrom, int[] convertTo) { if (list == null) { return null; } List<Integer> convertedList = convertStringListToIntList(list, convertFrom, convertTo); int[] returnArray = new int[convertedList.size()]; for (int i = 0; i < returnArray.length; ++i) { returnArray[i] = convertedList.get(i); } return returnArray; } /** * Create an {@code List<Integer>} from the {@code List<>} by using {@code convertFrom} and * {@code convertTo} as a one-to-one map (via the index). * * <p>Strings not appearing in {@code convertFrom} are ignored (with a logged warning); * strings appearing in {@code convertFrom} but not {@code convertTo} are silently * dropped.</p> * * @param list Source list of strings * @param convertFrom Conversion list of strings * @param convertTo Conversion list of ints * @return A list of ints where the values correspond to the ones in {@code convertTo} * or {@code null} if {@code list} was {@code null} */ public static List<Integer> convertStringListToIntList( List<String> list, String[] convertFrom, int[] convertTo) { if (list == null) { return null; } List<Integer> convertedList = new ArrayList<>(list.size()); for (String str : list) { int strIndex = getArrayIndex(convertFrom, str); // Guard against unexpected values if (strIndex < 0) { if (DEBUG) Log.v(TAG, "Ignoring invalid value " + str); continue; } // Ignore values we can't map into (intentional) if (strIndex < convertTo.length) { convertedList.add(convertTo[strIndex]); } } return convertedList; } /** * Convert the list of integers in {@code list} to an {@code int} array. * * <p>Every element in {@code list} must be non-{@code null}.</p> * * @param list a list of non-{@code null} integers * * @return a new int array containing all the elements from {@code list} * * @throws NullPointerException if any of the elements in {@code list} were {@code null} */ public static int[] toIntArray(List<Integer> list) { if (list == null) { return null; } int[] arr = new int[list.size()]; int i = 0; for (int elem : list) { arr[i] = elem; i++; } return arr; } /** * Returns true if the given {@code array} contains the given element. * * @param array {@code array} to check for {@code elem} * @param elem {@code elem} to test for * @return {@code true} if the given element is contained */ public static boolean contains(int[] array, int elem) { return getArrayIndex(array, elem) != -1; } /** * Returns true if the given {@code array} contains the given element. * * @param array {@code array} to check for {@code elem} * @param elem {@code elem} to test for * @return {@code true} if the given element is contained */ public static <T> boolean contains(T[] array, T elem) { return getArrayIndex(array, elem) != -1; } private ArrayUtils() { throw new AssertionError(); } }
true
8bc34922b9711dd2382b782eb25ac6a9a79bedb7
Java
seanlab/javasample
/src/me/seanxiao/leetcode/BinaryTreeZigzagLevelOrderTraversal.java
UTF-8
1,368
3.296875
3
[]
no_license
package me.seanxiao.leetcode; import java.util.ArrayList; public class BinaryTreeZigzagLevelOrderTraversal { public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>(); ArrayList<TreeNode> nodes = new ArrayList<TreeNode>(); if (root == null) { return results; } nodes.add(root); int order = 1; while (!nodes.isEmpty()) { ArrayList<TreeNode> temp = new ArrayList<TreeNode>(); ArrayList<Integer> result = new ArrayList<Integer>(); for (int i = 0; i < nodes.size(); i++) { if (nodes.get(i).left != null) { temp.add(nodes.get(i).left); } if (nodes.get(i).right != null) { temp.add(nodes.get(i).right); } } if (order == 1) { for (int i = 0; i < nodes.size(); i++) { result.add(nodes.get(i).val); } } else { for (int i = nodes.size() - 1; i >= 0; i--) { result.add(nodes.get(i).val); } } order *= -1; results.add(result); nodes = temp; } return results; } }
true
6c212ad5f7a205fa2f26729ebdcd1d8a1826fc3e
Java
olivierthas/Programming-Essentials-2
/Werkcollege8/src/oefening3/Swingcomponenten.java
UTF-8
4,386
2.953125
3
[ "MIT" ]
permissive
package oefening3; import java.awt.Color; import java.awt.GridLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; public class Swingcomponenten { private JFrame frame; private JButton button; private JTextField textField; private JLabel label; private ButtonGroup buttonGroup; private JCheckBox checkBox; private JComboBox<String> comboBox; private JPanel panel; private JPanel smallPanel1, smallPanel2, smallPanel3, smallPanel4, verySmallPanel; private JRadioButton radioButton1 = new JRadioButton("optie1", true); private JRadioButton radioButton2 = new JRadioButton("optie2"); private JRadioButton radioButton3 = new JRadioButton("optie3"); private boolean crossPlatform = true; private JRadioButton getRadioButton1() { return radioButton1; } private JRadioButton getRadioButton2() { return radioButton2; } private JRadioButton getRadioButton3() { return radioButton3; } private JButton getButton() { if (button == null) { button = new JButton(); button.setText("Klik mij"); } return button; } private ButtonGroup getButtonGroup() { if (buttonGroup == null) { buttonGroup = new ButtonGroup(); buttonGroup.add(getRadioButton1()); buttonGroup.add(getRadioButton2()); buttonGroup.add(getRadioButton3()); } return buttonGroup; } private JCheckBox getCheckBox() { if (checkBox == null) { checkBox = new JCheckBox("vinken"); } return checkBox; } private JComboBox<String> getComboBox() { if (comboBox == null) { String[] content = { "een", "twee", "drie" }; comboBox = new JComboBox<String>(content); } return comboBox; } private JLabel getLabel() { if (label == null) { label = new JLabel("Vaste tekst"); } return label; } private JTextField getTextField() { if (textField == null) { textField = new JTextField(20); } return textField; } private JFrame getFrame() { if (frame == null) { frame = new JFrame(); frame.setSize(300, 200); frame.setContentPane(getContentPane()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } // demonstratie van het gebruik van de UIManager // gebruik van CrossPlatformLookandFeel try { if (crossPlatform) UIManager.setLookAndFeel(UIManager .getCrossPlatformLookAndFeelClassName()); else UIManager.setLookAndFeel(UIManager .getSystemLookAndFeelClassName()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } SwingUtilities.updateComponentTreeUI(frame); return frame; } private JPanel getContentPane() { if (panel == null) { panel = new JPanel(); panel.setLayout(new GridLayout(4, 1)); panel.add(getSmallPanel1()); panel.add(getSmallPanel2()); panel.add(getSmallPanel3()); panel.add(getSmallPanel4()); } return panel; } public static void main(String[] args) { Swingcomponenten swingcomponenten = new Swingcomponenten(); swingcomponenten.getFrame().setVisible(true); } private JPanel getSmallPanel1() { if (smallPanel1 == null) { smallPanel1 = new JPanel(); // smallPanel1.setLayout(new FlowLayout()); // FlowLayout is de default layoutmanager van een JPanel. smallPanel1.add(getVerySmallPanel()); } return smallPanel1; } public JPanel getSmallPanel2() { if (smallPanel2 == null) { smallPanel2 = new JPanel(); smallPanel2.add(getTextField()); } return smallPanel2; } public JPanel getSmallPanel3() { if (smallPanel3 == null) { smallPanel3 = new JPanel(); smallPanel3.add(getLabel()); getButtonGroup(); smallPanel3.add(radioButton1); smallPanel3.add(radioButton2); smallPanel3.add(radioButton3); } return smallPanel3; } public JPanel getSmallPanel4() { if (smallPanel4 == null) { smallPanel4 = new JPanel(); smallPanel4.add(getCheckBox()); smallPanel4.add(getComboBox()); } return smallPanel4; } public JPanel getVerySmallPanel() { if (verySmallPanel == null) { verySmallPanel = new JPanel(); verySmallPanel.setBackground(Color.blue); verySmallPanel.add(getButton()); } return verySmallPanel; } }
true
ee59cd1c34262f8a1bf912f9fe696fb14cb9dc3d
Java
trohman/Java-Projects
/Grapher3D/src/pkg3ddisplay/MatrixOperator.java
UTF-8
1,322
3.59375
4
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pkg3ddisplay; /** * * contains a method that multiplies two matrixes * * @author Rohman */ public class MatrixOperator { /** * multiplies the two provided matrixes * If the dimensions of the matrixes are incompatible * a new matrix is returned * * @param matrix1 first matrix * @param matrix2 second matrix * @return the product of the matrixes */ public static Matrix multiply(Matrix matrix1, Matrix matrix2){ Matrix newMatrix = new Matrix(); newMatrix.setDimension(matrix1.numRows(), matrix2.numColumns()); if(matrix1.numColumns() == matrix2.numRows()){ for(int row = 0; row < matrix1.numRows(); row++){ for(int col = 0; col < matrix2.numColumns();col++){ double sum = 0; for(int element = 0; element < matrix2.numRows(); element++){ sum += matrix1.getElement(row, element)*matrix2.getElement(element, col); } newMatrix.setElement(sum,row,col); } } return newMatrix; }else{ return new Matrix(); } } }
true
eece851971431a82930376a4ae84481034d7e31d
Java
jkarethiya/jdk7
/src/main/java/com/jk/jdk/core/accessspecifier/privatee/CallToPrivateMethod.java
UTF-8
1,822
3.40625
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.jk.jdk.core.accessspecifier.privatee; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * * @author Jitendra */ public class CallToPrivateMethod { public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class c = SimpleClass.class; Method[] methods = c.getDeclaredMethods(); String methodName = ""; Object returnValue = null; for(Method method : methods) { method.setAccessible(true); methodName = method.getName(); if(Modifier.isPrivate(method.getModifiers())){ if(Modifier.isStatic(method.getModifiers())) { System.out.println("static methodName: " + methodName); returnValue = method.invoke(SimpleClass.class, 10, "A", new Double[] {1.0, 2.0}); System.out.println("returnValue: " + returnValue); } else { System.out.println("non-static methodName: " + methodName); returnValue = method.invoke(new SimpleClass(), new Object[] {}); System.out.println("returnValue: " + returnValue); } } } } } class SimpleClass { private int getInteger() { return 10; } private static String getIntegerWithParameter(int a, String obj, Double[] args) { return a + obj.toString() + args[0].toString() + args[1].toString(); } }
true
dc181614601cdbfa77e36c4120f3e190bf2dd76c
Java
RayHo8224/ePOS
/src/main/java/com/discount/model/DiscountVO.java
UTF-8
440
2.21875
2
[]
no_license
package com.discount.model; public class DiscountVO implements java.io.Serializable{ private static final long serialVersionUID = 1L; private String dis_id; private Float dis_price; public String getDis_id() { return dis_id; } public void setDis_id(String dis_id) { this.dis_id = dis_id; } public Float getDis_price() { return dis_price; } public void setDis_price(Float dis_price) { this.dis_price = dis_price; } }
true
65bf052c9ceb0b41964f93ba9c2c64c7658670b3
Java
briupdingcm/hadoop
/mapred/src/main/java/com/briup/mr/inputFormat/reader/ysw/MaxTemperatureByYearStation.java
UTF-8
2,065
2.265625
2
[]
no_license
package com.briup.mr.inputFormat.reader.ysw; import com.briup.mr.type.YearStation; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import java.io.IOException; public class MaxTemperatureByYearStation extends Configured implements Tool { public static void main(String... args) throws Exception { System.exit(ToolRunner.run(new MaxTemperatureByYearStation(), args)); } @Override public int run(String[] arg0) throws Exception { Configuration conf = getConf(); Job job = Job.getInstance(conf); job.setJarByClass(MaxTemperatureByYearStation.class); job.setJobName("Max Temperature By Year Station"); job.setInputFormatClass(YearStationInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); YearStationInputFormat.addInputPath(job, new Path(conf.get("input"))); FileOutputFormat.setOutputPath(job, new Path(conf.get("output"))); job.setReducerClass(MaxTemperatureReducer.class); job.setOutputKeyClass(YearStation.class); job.setOutputValueClass(IntWritable.class); return (job.waitForCompletion(true) ? 0 : 1); } static class MaxTemperatureReducer extends Reducer<YearStation, IntWritable, YearStation, IntWritable> { public void reduce(YearStation key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int maxValue = Integer.MIN_VALUE; for (IntWritable value : values) { maxValue = Math.max(maxValue, value.get()); } context.write(key, new IntWritable(maxValue)); } } }
true
ec55a9025d37c04fa0f456aa21374f67ce797ddb
Java
navinvishy/dynamodbsql
/src/main/java/com/jobvite/dynamodbsql/dynamo/model/OrExpr.java
UTF-8
1,069
2.84375
3
[]
no_license
package com.jobvite.dynamodbsql.dynamo.model; import com.jobvite.dynamodbsql.translator.visitor.ExprVisitor; public class OrExpr extends ConditionExpr { private ConditionExpr left; private ConditionExpr right; public OrExpr(ConditionExpr left, ConditionExpr right){ this.left = left; this.right = right; } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } public ConditionExpr getLeft() { return left; } public void setLeft(ConditionExpr left) { this.left = left; } public ConditionExpr getRight() { return right; } public void setRight(ConditionExpr right) { this.right = right; } @Override public String toString() { return left.toString() + " OR " + right.toString(); } @Override public boolean isAncestorOf(ConditionExpr expr) { if(expr == left || expr == right){ return true; } return left.isAncestorOf(expr) || right.isAncestorOf(expr); } }
true
d9dd990e0746642547d1d11c336d9e14dfb3606c
Java
Jay2645/geniusect-sim
/abilities/AbilityFlashFire.java
UTF-8
421
2.453125
2
[]
no_license
package geniusectsim.abilities; import geniusectsim.battle.Type; import geniusectsim.pokemon.Pokemon; /** * A class representing the "Flash Fire" ability. * @author TeamForretress */ public class AbilityFlashFire extends Ability { public AbilityFlashFire() { rating = 3; } @Override public void setUser(Pokemon u) { u.addImmunity(Type.Fire); user = u; } //TODO: Boost the power of fire-type moves. }
true
887af5e29c23dcc0c36f9b66efe9d3cace0b8aed
Java
evrenvural/admin-panel
/src/main/java/com/evrenvural/admin/service/IssueService.java
UTF-8
411
1.804688
2
[]
no_license
package com.evrenvural.admin.service; import com.evrenvural.admin.dto.IssueDto; import com.evrenvural.admin.util.TPage; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; public interface IssueService { IssueDto save(IssueDto issue); IssueDto getById(Long id); TPage<IssueDto> getAllPageable(Pageable pageable); Boolean delete(IssueDto issue); }
true
4f3d20ad2ba33bb14e8be80141f238d66f828ba2
Java
melnyk-alex/Example-JDBC-with-JFrame
/JavaJDBCFrames/src/ua/com/codefire/jdbc_swing/MainFrame.java
UTF-8
12,843
2.0625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ua.com.codefire.jdbc_swing; import java.awt.Window; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.sql.SQLException; import java.util.List; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.TableModel; import ua.com.codefire.jdbc_swing.db.MySQLDAO; /** * * @author human */ public class MainFrame extends javax.swing.JFrame { private MySQLDAO mysqldao; /** * Creates new form Main */ public MainFrame() { this.mysqldao = new MySQLDAO(dbProperties); initComponents(); setLocationRelativeTo(null); try { List<String> databaseList = mysqldao.getDatabaseList(); DefaultComboBoxModel dcbm = new DefaultComboBoxModel(databaseList.toArray()); jcbDatabases.setModel(dcbm); } catch (SQLException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } } /** * 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(); jcbDatabases = new javax.swing.JComboBox<>(); jbShowTables = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jlTables = new javax.swing.JList<>(); jScrollPane2 = new javax.swing.JScrollPane(); jtTableData = new javax.swing.JTable(); jbDumpDatabase = new javax.swing.JButton(); jmbMain = new javax.swing.JMenuBar(); jmFile = new javax.swing.JMenu(); jmiPreferences = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JPopupMenu.Separator(); jmiExit = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Select database: "); jbShowTables.setText("SHOW TABLES"); jbShowTables.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbShowTablesActionPerformed(evt); } }); jlTables.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jlTablesMouseClicked(evt); } }); jScrollPane1.setViewportView(jlTables); jtTableData.setAutoCreateRowSorter(true); jtTableData.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); jtTableData.setCellSelectionEnabled(true); jtTableData.setEditingRow(1); jtTableData.setShowGrid(true); jScrollPane2.setViewportView(jtTableData); jbDumpDatabase.setText("DUMP DATABASE"); jbDumpDatabase.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbDumpDatabaseActionPerformed(evt); } }); jmFile.setText("File"); jmiPreferences.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK)); jmiPreferences.setText("Preferences"); jmiPreferences.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jmiPreferencesActionPerformed(evt); } }); jmFile.add(jmiPreferences); jmFile.add(jSeparator1); jmiExit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK)); jmiExit.setText("Exit"); jmiExit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jmiExitActionPerformed(evt); } }); jmFile.add(jmiExit); jmbMain.add(jmFile); setJMenuBar(jmbMain); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 648, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcbDatabases, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbShowTables) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbDumpDatabase))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jbShowTables) .addComponent(jcbDatabases, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1) .addComponent(jbDumpDatabase)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 540, Short.MAX_VALUE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jbShowTablesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbShowTablesActionPerformed String databaseName = jcbDatabases.getSelectedItem().toString(); try { DefaultListModel dlm = new DefaultListModel(); for (String tableName : mysqldao.getTablesList(databaseName)) { dlm.addElement(tableName); } jlTables.setModel(dlm); } catch (SQLException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jbShowTablesActionPerformed private void jlTablesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jlTablesMouseClicked if (evt.getClickCount() == 2 && jlTables.getSelectedIndex() >= 0) { String databaseName = jcbDatabases.getSelectedItem().toString(); String tableName = jlTables.getSelectedValue(); try { TableModel tableDataModel = mysqldao.getTableDataModel(databaseName, tableName); jtTableData.setModel(tableDataModel); } catch (SQLException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_jlTablesMouseClicked private void jbDumpDatabaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbDumpDatabaseActionPerformed int answer = JOptionPane.showConfirmDialog(this, "Dump database with data?", "Database dump", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); switch (answer) { case JOptionPane.YES_OPTION: { // TODO: Do dump database structure with data. try { String dumpDatabase = mysqldao.dumpDatabase(jcbDatabases.getSelectedItem().toString()); System.out.println(dumpDatabase); JFileChooser fileChooser = new JFileChooser(new File("").getAbsoluteFile()); fileChooser.setFileFilter(new FileNameExtensionFilter("SQL File", "sql")); if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { Path target = fileChooser.getSelectedFile().toPath(); try { Files.copy(new ByteArrayInputStream(dumpDatabase.getBytes()), target, StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } } } catch (SQLException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } } break; case JOptionPane.NO_OPTION: // TODO: Do dump database only structure. break; } }//GEN-LAST:event_jbDumpDatabaseActionPerformed private void jmiExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiExitActionPerformed dispose(); }//GEN-LAST:event_jmiExitActionPerformed private void jmiPreferencesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmiPreferencesActionPerformed boolean exists = false; for (Window window : getWindows()) { if (window instanceof PreferenceFrame) { exists = true; window.setVisible(true); break; } } if (!exists) { PreferenceFrame preferenceFrame = new PreferenceFrame(); preferenceFrame.setLocationRelativeTo(this); preferenceFrame.setVisible(true); } }//GEN-LAST:event_jmiPreferencesActionPerformed private static Properties dbProperties; /** * @param args the command line arguments */ public static void main(String args[]) { try { Class.forName(com.mysql.jdbc.Driver.class.getName()); } catch (ClassNotFoundException ex) { } dbProperties = new Properties(); try { dbProperties.load(new FileInputStream("db.properties")); } catch (IOException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new MainFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JPopupMenu.Separator jSeparator1; private javax.swing.JButton jbDumpDatabase; private javax.swing.JButton jbShowTables; private javax.swing.JComboBox<String> jcbDatabases; private javax.swing.JList<String> jlTables; private javax.swing.JMenu jmFile; private javax.swing.JMenuBar jmbMain; private javax.swing.JMenuItem jmiExit; private javax.swing.JMenuItem jmiPreferences; private javax.swing.JTable jtTableData; // End of variables declaration//GEN-END:variables }
true
9e2b61ce6ed362533876e77746a506924be9d844
Java
santhoshscse/ChessValidator
/src/main/java/com/target/chess/validator/PawnMoveValidator.java
UTF-8
7,588
2.6875
3
[]
no_license
package com.target.chess.validator; import java.util.List; import com.target.chess.exception.MoveException; import com.target.chess.exception.MoveException.ErrorCode; import com.target.chess.model.Board; import com.target.chess.model.Command; import com.target.chess.model.Location; import com.target.chess.model.Piece; import com.target.chess.model.PieceType; import com.target.chess.model.Player; import com.target.chess.util.ChessUtil; public class PawnMoveValidator extends PieceMoveValidator { private static final PieceType PAWN = PieceType.P; @Override public Location getSourceLocation(Board board, Player player, Command command) throws Exception { Location source = command.getSourceLocation(); Location target = command.getTargetLocation(); boolean isCapture = command.isCapture(); return fillSource(board, player, source, target, isCapture); } @Override public Location getEnPassant(Board board, Location source, Location target) { Location loc = null; if (source.getFile() == target.getFile()) { if (source.getRank() - target.getRank() == 2) { char tmpRank = (char) (source.getRank() - 1); loc = new Location(); loc.setFile(source.getFile()); loc.setRank(tmpRank); } else if (target.getRank() - source.getRank() == 2) { char tmpRank = (char) (target.getRank() - 1); loc = new Location(); loc.setFile(source.getFile()); loc.setRank(tmpRank); } } return loc; } private Location fillSource(Board board, Player player, Location source, Location target, boolean isCapture) throws Exception { char sourceFile = 0; char sourceRank = 0; if (source != null) { sourceFile = source.getFile(); sourceRank = source.getRank(); } if (ChessUtil.isEmpty(sourceFile) && ChessUtil.isEmpty(sourceRank)) { source = fillSource(board, player, target, isCapture); } else if (!ChessUtil.isEmpty(sourceFile) && ChessUtil.isEmpty(sourceRank)) { source = fillSourceWithFile(board, player, sourceFile, target, isCapture); } else if (ChessUtil.isEmpty(sourceFile) && !ChessUtil.isEmpty(sourceRank)) { source = fillSourceWithRank(board, player, sourceRank, target, isCapture); } else { source = fillSourceWithFileRank(board, player, source, target, isCapture); } if (source == null || ChessUtil.isEmpty(source.getFile()) || ChessUtil.isEmpty(source.getRank())) { throw new MoveException(ErrorCode.INVALIDSOURCE); } return source; } private Location fillSourceWithFileRank(Board board, Player player, Location source, Location target, boolean isCapture) { Piece srcPiece = board.getPieceByLocation(source); if (srcPiece.getPieceType() == PAWN) { boolean isWhite = ChessUtil.isWhite(player); if (isWhite) { if (isCapture) { if (source.getRank() + 1 == target.getRank() && source.getFile() == target.getFile()) { return source; } } else { if (source.getRank() + 1 == target.getRank() && source.getFile() == target.getFile()) { return source; } else if (source.getRank() == '2' && source.getRank() + 2 == target.getRank() && source.getFile() == target.getFile()) { return source; } } } else { if (isCapture) { if (source.getRank() - 1 == target.getRank() && source.getFile() == target.getFile()) { return source; } } else { if (source.getRank() - 1 == target.getRank() && source.getFile() == target.getFile()) { return source; } else if (source.getRank() == '7' && source.getFile() == target.getRank() && source.getFile() == target.getFile()) { return source; } } } return null; } return null; } private Location fillSourceWithRank(Board board, Player player, char sourceRank, Location target, boolean isCapture) throws Exception { boolean isWhite = ChessUtil.isWhite(player); List<Location> locList = board.getAllLocationsOfPiece(PAWN, isWhite); Location source = null; Location tmpLoc = null; for (Location loc : locList) { if (tmpLoc != null) { if (source == null) { source = tmpLoc; tmpLoc = null; } else { throw new MoveException(ErrorCode.AMBIGIUTY); } } if (loc.getRank() == sourceRank && loc.getFile() - 1 == target.getFile()) { tmpLoc = loc; } else if (loc.getRank() == sourceRank && loc.getFile() + 1 == target.getFile()) { tmpLoc = loc; } } if (source == null) { source = tmpLoc; } return source; } private Location fillSourceWithFile(Board board, Player player, char sourceFile, Location target, boolean isCapture) throws Exception { boolean isWhite = ChessUtil.isWhite(player); List<Location> locList = board.getAllLocationsOfPiece(PAWN, isWhite); Location source = null; Location tmpLoc = null; for (Location loc : locList) { if (tmpLoc != null) { if (source == null) { source = tmpLoc; tmpLoc = null; } else { throw new MoveException(ErrorCode.AMBIGIUTY); } } if (isWhite) { if (isCapture) { if (loc.getRank() + 1 == target.getRank() && sourceFile == target.getFile()) { tmpLoc = loc; } } else { if (loc.getRank() + 1 == target.getRank() && sourceFile == target.getFile()) { tmpLoc = loc; } else if (loc.getRank() == '2' && loc.getRank() + 2 == target.getRank() && sourceFile == target.getFile()) { tmpLoc = loc; } } } else { if (isCapture) { if (loc.getRank() - 1 == target.getRank() && sourceFile == target.getFile()) { tmpLoc = loc; } } else { if (loc.getRank() - 1 == target.getRank() && sourceFile == target.getFile()) { tmpLoc = loc; } else if (loc.getRank() == '7' && sourceFile == target.getRank() && loc.getFile() == target.getFile()) { tmpLoc = loc; } } } } if (source == null) { source = tmpLoc; } return source; } private Location fillSource(Board board, Player player, Location target, boolean isCapture) throws Exception { boolean isWhite = ChessUtil.isWhite(player); List<Location> locList = board.getAllLocationsOfPiece(PAWN, isWhite); Location source = null; Location tmpLoc = null; for (Location loc : locList) { if (tmpLoc != null) { if (source == null) { source = tmpLoc; tmpLoc = null; } else { throw new MoveException(ErrorCode.AMBIGIUTY); } } if (isWhite) { if (isCapture) { if (loc.getRank() + 1 == target.getRank() && loc.getFile() - 1 == target.getFile()) { tmpLoc = loc; } else if (loc.getRank() + 1 == target.getRank() && loc.getFile() + 1 == target.getFile()) { tmpLoc = loc; } } else { if (loc.getRank() + 1 == target.getRank() && loc.getFile() == target.getFile()) { tmpLoc = loc; } else if (tmpLoc == null && loc.getRank() == '2' && loc.getRank() + 2 == target.getRank() && loc.getFile() == target.getFile()) { tmpLoc = loc; } } } else { if (isCapture) { if (loc.getRank() - 1 == target.getRank() && loc.getFile() - 1 == target.getFile()) { tmpLoc = loc; } else if (loc.getRank() - 1 == target.getRank() && loc.getFile() + 1 == target.getFile()) { tmpLoc = loc; } } else { if (loc.getRank() - 1 == target.getRank() && loc.getFile() == target.getFile()) { tmpLoc = loc; } else if (loc.getRank() == '7' && loc.getRank() - 2 == target.getRank() && loc.getFile() == target.getFile()) { tmpLoc = loc; } } } } if (source == null) { source = tmpLoc; } return source; } }
true
6f2c7a3422b232cd632ea7ec368a66b50d65db95
Java
frodoking/Java
/java_data_structure/src/main/java/cn/com/frodo/algorithm/leetcode/LC142DetectCycle.java
UTF-8
2,396
3.609375
4
[]
no_license
package cn.com.frodo.algorithm.leetcode; import cn.com.frodo.LinkedNode; import cn.com.frodo.algorithm.AlgorithmPoint; import cn.com.frodo.algorithm.IAlgorithm; /** * 142. 环形链表 II * 给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。 * * 如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。 * * 不允许修改 链表。 * * * * 示例 1: * * * * 输入:head = [3,2,0,-4], pos = 1 * 输出:返回索引为 1 的链表节点 * 解释:链表中有一个环,其尾部连接到第二个节点。 * 示例 2: * * * * 输入:head = [1,2], pos = 0 * 输出:返回索引为 0 的链表节点 * 解释:链表中有一个环,其尾部连接到第一个节点。 * 示例 3: * * * * 输入:head = [1], pos = -1 * 输出:返回 null * 解释:链表中没有环。 */ @Deprecated @AlgorithmPoint(tag = {AlgorithmPoint.Tag.leetcode, AlgorithmPoint.Tag.frequently}, difficulty = AlgorithmPoint.Difficulty.medium, category = AlgorithmPoint.Category.linklist) public class LC142DetectCycle implements IAlgorithm { @Override public void exec() { } /** * 主要思路,是快慢指针终究会在环上相遇。 * 假设起点到环的距离 A,环入口到相遇的部分分为 B,C。那么快指针走了 A + B + C + B、慢指针走了 A + B。 * 那么 A + B + C + B = 2 * (A + B)。所以A=C,所以相遇后,让快指针重新一步一步走,那么他们一定会在入口相遇。 */ public LinkedNode detectCycle(LinkedNode head) { LinkedNode nodeS = head; LinkedNode nodeF = head; do { if (nodeF==null || nodeF.next == null) return null; nodeS = nodeS.next; nodeF = nodeF.next.next; } while (nodeS != nodeF); nodeF = head; while (nodeS!=nodeF) { nodeS = nodeS.next; nodeF = nodeF.next; } return nodeF; } }
true
f5de64c7920b272e7e562c9465962f83187ca9ba
Java
csj4032/enjoy-algorithm
/baekjoon/src/main/java/p11728/Main.java
UTF-8
1,148
3.28125
3
[]
no_license
package p11728; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); StringBuilder sb = new StringBuilder(); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[] p = new int[n]; int[] q = new int[m]; st = new StringTokenizer(br.readLine().trim(), " "); for (int i = 0; i < n; i++) p[i] = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine().trim(), " "); for (int i = 0; i < m; i++) q[i] = Integer.parseInt(st.nextToken()); int i = 0; int j = 0; while (true) { int a = p[i]; int b = q[j]; if (a > b) { sb.append(b + " "); j++; } else { sb.append(a + " "); i++; } if (i == n) break; if (j == m) break; } for (; i < n; i++) sb.append(p[i] + " "); for (; j < m; j++) sb.append(q[j] + " "); System.out.println(sb.toString()); } }
true
4a999d07958967489b1d234fa0a92e7d8dcef4ea
Java
tawfiqul-islam/RM-Simulator
/simulator/src/Policy/RRScheduler.java
UTF-8
810
2.09375
2
[ "Apache-2.0" ]
permissive
package Policy; import Entity.Job; import Entity.VM; import Manager.Controller; import Manager.StatusUpdater; import java.util.ArrayList; public class RRScheduler { public static boolean findSchedule(Job job) { boolean found=false; for(int j=0,i=0;j<job.getE();i++) { if(i==Controller.vmList.size()){ i=0; if(!found) break; found=false; } VM vm = Controller.vmList.get(i); if (SchedulerUtility.resourceConstraints(job,vm)) { j++; StatusUpdater.subtractVMresource(vm,job); job.addplacementVM(vm.getVmID()); found=true; } } return SchedulerUtility.placeExecutors(job); } }
true
a613c30c00ddb9682b390cb48adf705a91d71f9d
Java
liubenwei/QCache
/src/java/main/recycle/MarkExpire.java
UTF-8
2,764
2.59375
3
[]
no_license
package recycle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import store.CacheFileGroup; import store.MappedFile; import store.StoreOptions; import java.util.List; /** * 标记所有超时的数据. */ public class MarkExpire implements Mark{ private static Logger logger = LoggerFactory.getLogger(MarkExpire.class); /** * Cache存储的文件 */ private CacheFileGroup cacheFileGroup; public MarkExpire(CacheFileGroup cacheFileGroup){ this.cacheFileGroup = cacheFileGroup; } @Override public int mark() { int result = 0; long scanPosition = StoreOptions.OS_PAGE_SIZE; long maxPosition = cacheFileGroup.getWriteSize(); long baseTime = cacheFileGroup.getFirstTime(); List<MappedFile> mappedFileList = cacheFileGroup.getMappedFileList(); int fileSize = cacheFileGroup.getFileSize(); //遍历所有缓存 int fileIndex; int fileOffset; while (scanPosition < maxPosition) { //计算那个文件 fileIndex = (int) (scanPosition / (long) fileSize); //计算文件的位置 fileOffset = (int) (scanPosition % fileSize); if (fileOffset + 21 <= fileSize) { //该文件后面可能还有消息,尝试读 MappedFile mappedFile = mappedFileList.get(fileIndex); //size 2B short size = mappedFile.getShort(fileOffset); if (size <= 21 || size + fileOffset > fileSize) { scanPosition = (fileIndex + 1) * (long) fileSize; continue; } //status 1B byte status = mappedFile.getByte(fileOffset + 2); //该记录已被删除 if (status == (byte) 1) { scanPosition += size; continue; } //timeOut 4B int timeOut = mappedFile.getInt(fileOffset + 11); if (timeOut == -1) { //这个消息不会过期 scanPosition += size; continue; } //storeTime 4B int storeTime = mappedFile.getInt(fileOffset + 7); if (timeOut > 0 && System.currentTimeMillis() - storeTime - baseTime > timeOut) { //logger.info("time out!"); //标记删除 mappedFile.put(fileOffset + 2,(byte) 1); result++; } scanPosition += size; } else { scanPosition = (fileIndex + 1) * (long) fileSize; } } return result; } }
true
42b804a6839401edb3c3fba4983ad1af7e5006f8
Java
ZesenWang/MyCodeRepository--Eclipse
/Calculator/src/com/example/calculator/MainActivity.java
UTF-8
4,265
2.046875
2
[]
no_license
package com.example.calculator; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.os.Build; public class MainActivity extends ActionBarActivity implements OnClickListener{ private Button bt1; private Button bt2; private Button bt3; private Button bt4; private Button bt5; private Button bt6; private Button bt7; private Button bt8; private Button bt9; private Button bt0; private Button btplus; private Button btminus; private Button btmulti; private Button btdivide; private Button btc; private Button btdel; private Button btdot; private Button btequal; private EditText et_input; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_input=(EditText)findViewById(R.id.et_input); bt1=(Button)findViewById(R.id.bt1); bt2=(Button)findViewById(R.id.bt2); bt3=(Button)findViewById(R.id.bt3); bt4=(Button)findViewById(R.id.bt4); bt5=(Button)findViewById(R.id.bt5); bt6=(Button)findViewById(R.id.bt6); bt7=(Button)findViewById(R.id.bt7); bt8=(Button)findViewById(R.id.bt8); bt9=(Button)findViewById(R.id.bt9); bt0=(Button)findViewById(R.id.bt0); btc=(Button)findViewById(R.id.btc); btdel=(Button)findViewById(R.id.btdel); btplus=(Button)findViewById(R.id.btplus); btminus=(Button)findViewById(R.id.btminus); btmulti=(Button)findViewById(R.id.btmulti); btdivide=(Button)findViewById(R.id.btdivide); btequal=(Button)findViewById(R.id.btequal); btdot=(Button)findViewById(R.id.btdot); bt1.setOnClickListener(this); bt2.setOnClickListener(this); bt3.setOnClickListener(this); bt4.setOnClickListener(this); bt5.setOnClickListener(this); bt6.setOnClickListener(this); bt7.setOnClickListener(this); bt8.setOnClickListener(this); bt9.setOnClickListener(this); bt0.setOnClickListener(this); btdel.setOnClickListener(this); btc.setOnClickListener(this); btplus.setOnClickListener(this); btminus.setOnClickListener(this); btmulti.setOnClickListener(this); btdivide.setOnClickListener(this); btequal.setOnClickListener(this); btdot.setOnClickListener(this); } @Override public void onClick(View arg0) { // TODO Auto-generated method stub String str=new String(et_input.getText().toString()); switch(arg0.getId()){ case R.id.bt0: case R.id.bt1: case R.id.bt2: case R.id.bt3: case R.id.bt4: case R.id.bt5: case R.id.bt6: case R.id.bt7: case R.id.bt8: case R.id.bt9: et_input.setText(str+((Button)arg0).getText()); break; case R.id.btdot: et_input.setText(str+'.'); break; case R.id.btplus: et_input.setText(str+" + "); break; case R.id.btminus: et_input.setText(str+" - "); break; case R.id.btmulti: et_input.setText(str+" * "); break; case R.id.btdivide: et_input.setText(str+" / "); break; case R.id.btequal: getResult(); break; case R.id.btdel: et_input.setText(str.substring(0,str.length()-1)); break; case R.id.btc: et_input.setText(""); break; } } public void getResult(){ String str=et_input.getText().toString(); int space=str.indexOf(' '); String oprand1=str.substring(0,space); String oprand2=str.substring(space+3); String operator=str.substring(space+1,space+2); double op1=Double.parseDouble(oprand1); double op2=Double.parseDouble(oprand2); double result=0; String minus="-"; String multi="*"; if(operator.equals("+")) result=op1+op2; else if(operator.equals(minus)) result=op1-op2; else if(operator.equals(multi)) result=op1*op2; else result=op1/op2; et_input.setText(result+""); }; }
true
64b2dbb54afa6a88ad7f21943f752049622ef200
Java
Tonio993/Scrap-Code
/fabrizio_maurizio/src/fabrizio_maurizio/Roba.java
UTF-8
181
2.1875
2
[]
no_license
package fabrizio_maurizio; public class Roba { private String coso; public String getCoso() { return coso; } public void setCoso(String coso) { this.coso = coso; } }
true
291ea15f1ce5b5e6266acbf7f83bed1e37d3b564
Java
kbiid/Torpedo
/Study/src/main/java/threadex/traning/Main.java
UTF-8
223
1.539063
2
[]
no_license
package threadex.traning; public class Main { public static void main(String[] args) { ThreadTest test = new ThreadTest(Integer.parseInt(args[0])); test.setTestNum(100); test.runTestSwitch("extends"); } }
true
5e32d6db4df092a77c5530a4c8baefd247c4c655
Java
bongthoi/vinhsang-full-web-stanalone-v1-20180209
/src/main/java/vinhsang/controller/AboutCtrl.java
UTF-8
1,826
2.078125
2
[]
no_license
package vinhsang.controller; import java.util.Locale; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import vinhsang.domain.About; import vinhsang.layout.support.web.MessageHelper; import vinhsang.service.AboutService; @Controller public class AboutCtrl { @Autowired private AboutService aboutService; @RequestMapping(value = {"admin/about"}, method = RequestMethod.GET) public ModelAndView index(Locale locale) { ModelAndView mav=new ModelAndView(); mav.addObject("headTitle", "About"); //mav.addObject("about",new About() ); //System.out.println(aboutService.findByLang(locale.toString()).toString()); mav.addObject("about",aboutService.findByLang(locale.toString()) ); mav.setViewName("admin/about/about"); return mav; } @PostMapping("admin/about/save") public String save(@Valid @ModelAttribute About about, BindingResult result, RedirectAttributes ra){ if (result.hasErrors()) { return "admin/about/about"; } try{ aboutService.save(about); MessageHelper.addSuccessAttribute(ra, "save.success"); }catch(Exception ex){ MessageHelper.addSuccessAttribute(ra, "save.fail"); } return "redirect:/admin/about"; } }
true
c2e9cfc9f6aec48d8572aa8cea88ed7940e2b293
Java
stpetkov/reminder
/src/bubblesort/Solution.java
UTF-8
688
2.8125
3
[]
no_license
package bubblesort; import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int tC=sc.nextInt(); String a=sc.next(); String b=sc.next(); Set <Character> set=new HashSet<Character>(); for(Character g:a.toCharArray()){ set.add(g); } int count=0; for(Character h:b.toCharArray()){ if(set.contains(h)){ count=count+2; } } System.out.println(count); }}
true
8bc3ed7abc9d4feba49064c06eae71271fcd2aaf
Java
mikhailbohdanov/JQuantium_old
/src/com/quantium/web/bean/core/Response.java
UTF-8
5,524
2.109375
2
[]
no_license
package com.quantium.web.bean.core; import com.quantium.web.bean.Url; import com.quantium.web.bean.security.UserSecurity; import com.quantium.web.bean.security.permissions.AccessManager; import com.quantium.web.service.Languages; import com.quantium.web.service.MainServices; import com.quantium.web.util.UserHelper; import org.json.simple.JSONObject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * Author FREEMAN * Created 12.11.14 */ public class Response { public static boolean hasAjax(HttpServletRequest request) { String param = null; boolean ajax = false; try { if ((param = request.getHeader("X-REQUESTED-WITH")) != null && param.equals("XMLHttpRequest")) ajax = true; } catch (Exception e){} if (!ajax) try { if ((param = request.getHeader("HTTP-X-REQUESTED-WITH")) != null && param.equals("XMLHttpRequest")) ajax = true; } catch (Exception e){} if (!ajax || (param = request.getParameter("_ajax")) != null) try { if (param.equals("true")) ajax = true; else if (param.equals("false")) ajax = false; } catch (Exception e){} return ajax; } protected HashMap<String, Long> errors = new HashMap<String, Long>(); protected HttpServletRequest request = null; protected HttpServletResponse response = null; protected Url url = null; protected UserSecurity user; protected AccessManager manager; private long START_MILLIS = System.currentTimeMillis(); private long START_NANO = System.nanoTime(); protected Response() { this.user = UserHelper.getMe(); if (this.user != null) this.manager = this.user.getAccessManager(); } public Response(HttpServletRequest request) { this(); this.request = request; } public Response(HttpServletRequest request, HttpServletResponse response) { this(); this.request = request; this.response = response; } public long getDurationMillis() { return System.currentTimeMillis() - START_MILLIS; } public long getDurationNano() { return System.nanoTime() - START_NANO; } public long getDuration() { return Long.parseLong(String.valueOf(getDurationMillis()) + String.valueOf(getDurationNano())); } public HttpServletRequest getRequest() { return request; } public HttpServletResponse getResponse() { return response; } public boolean languageSet(String code) { if (!Languages.hasLanguage(code)) return false; if (request.getSession() != null) request.getSession().setAttribute("language", code); if (user != null) { user.setLanguageCode(code); MainServices.securityService.updateSecurityUser(user); } return true; } public Response addError(String errorType, long errorCode) { if (errors.containsKey(errorType)) errors.replace(errorType, errors.get(errorType) | errorCode); else errors.put(errorType, errorCode); return this; } public boolean hasError() { if (errors.size() == 0) return false; for (Map.Entry<String, Long> entry : errors.entrySet()) if (entry.getValue() > 0) return true; return false; } public boolean hasError(String errorType, long errorCode) { if (!errors.containsKey(errorType)) return false; else return (errors.get(errorType) & errorCode) > 0; } public boolean hasError(Class className, long errorCode) { if (!errors.containsKey(className)) return false; else return (errors.get(className) & errorCode) > 0; } public Url getUrl() { return url; } public Response setUrl(Url url) { this.url = url; return this; } public JSONObject getReturn() { JSONObject out = new JSONObject(); if (!hasError()) return out; out.put("errors", this.errors); return out; } public UserSecurity getUser() { return user; } public Response setUser(UserSecurity user) { this.user = user; if (user != null) this.manager = user.getAccessManager(); return this; } public boolean hasAccess(String access, String value) { if (manager != null) return manager.has(access, value); return false; } public boolean hasAny(String... accesses) { if (manager == null) return false; for (String access : accesses) if (manager.hasAny(access)) return true; return false; } public boolean hasAnyAccess(String access) { return manager != null && manager.hasAny(access); } public boolean hasAnyAccess(String access, String... values) { return manager != null && manager.hasAny(access, values); } public boolean hasAllAccess(String access, String... values) { return manager != null && manager.hasAll(access, values); } }
true
9fa4d471af22f1043267eb74ac3ec59966d9fe80
Java
anton-dev-ua/TheLife
/src/main/java/thelife/engine/hashlife/Universe.java
UTF-8
391
2.3125
2
[]
no_license
package thelife.engine.hashlife; import java.math.BigInteger; public class Universe extends CachedQuadTreeUniverse { @Override protected Block createInitialBlock() { return HashLifeBlock.create(3); } @Override protected BigInteger incGeneration(BigInteger generation, int level) { return generation.add(BigInteger.valueOf(2).pow(level - 2)); } }
true
3d91aa9e80c315019128e0492eb54a19554928d7
Java
17Wang/MyNote
/MyNote/src/MyNote/NoteWriteArea.java
UTF-8
2,815
2.859375
3
[]
no_license
package MyNote; import javax.swing.*; import javax.swing.text.DefaultStyledDocument; import javax.swing.text.StyledDocument; import java.awt.*; import java.awt.color.ICC_Profile; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class NoteWriteArea extends JTextArea { private Note _note; NoteWriteArea(Note note){ super(); _note=note; //制表符设置成2个字符 this.setTabSize(2); this.setText(null); this.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); if(e.isMetaDown()) { showPopupMenu(e.getComponent(), e.getX(), e.getY()); } } }); } public void showPopupMenu(Component invoker, int x, int y) { // 创建 弹出菜单 对象 JPopupMenu popupMenu = new JPopupMenu(); // 创建 一级菜单 JMenuItem copyMenuItem = new JMenuItem("复制"); JMenuItem pasteMenuItem = new JMenuItem("粘贴"); JMenu editMenu = new JMenu("编辑"); // 需要 添加 二级子菜单 的 菜单,使用 JMenu // 创建 二级菜单 JMenuItem findMenuItem = new JMenuItem("查找"); JMenuItem replaceMenuItem = new JMenuItem("替换"); // 添加 二级菜单 到 "编辑"一级菜单 editMenu.add(findMenuItem); editMenu.add(replaceMenuItem); // 添加 一级菜单 到 弹出菜单 popupMenu.add(copyMenuItem); popupMenu.add(pasteMenuItem); popupMenu.addSeparator(); // 添加一条分隔符 popupMenu.add(editMenu); // 添加菜单项的点击监听器 findMenuItem.addActionListener(new ActionListener() { private boolean _czfirst=true; @Override public void actionPerformed(ActionEvent e) { if(_czfirst) _note.GETSElf().GetMenu().GetEditor().Search(); _note.GETSElf().GetMenu().GetEditor().jd.setVisible(true); _czfirst=false; } }); replaceMenuItem.addActionListener(new ActionListener() { private boolean _thfirst=true; @Override public void actionPerformed(ActionEvent e) { if(_thfirst) _note.GETSElf().GetMenu().GetEditor().Replace(); _note.GETSElf().GetMenu().GetEditor().jd0.setVisible(true); _thfirst=false; } }); // ...... // 在指定位置显示弹出菜单 popupMenu.show(invoker, x, y); } }
true
1e0291bfa9b80b1226ee904768d681d237ee3038
Java
eaksi/SolGDX
/STactics/src/com/github/eaksi/stactics/db/RNG.java
UTF-8
411
2.5
2
[]
no_license
package com.github.eaksi.stactics.db; import java.util.Random; /** * A very basic Random Number Generator class. Will be expanded later. */ public class RNG { // TODO: (low priority) Prevent save scumming private static Random rng; public static void initialize() { rng = new Random(); } public static int nextInt(int bound) { return rng.nextInt(bound); } }
true
b7793332a1052072adab98a807de869165f29227
Java
mischelll/Java-Fundamentals-Module
/Methods - LAB/PrintingTriangle.java
UTF-8
604
3.578125
4
[]
no_license
package JavaFundamnetalsLab; import java.util.Scanner; public class PrintingTriangle { public static void main(String[] args) { printTri(new Scanner(System.in).nextInt()); } static void printLine(int start, int end){ for (int i = start; i <= end; i++) { System.out.print(i+ " "); } System.out.println(); } static void printTri(int n){ for (int i = 1; i <= n ; i++) { printLine(1, i); } for (int i = n -1; i >= 1 ; i--) { printLine(1,i); } } }
true
3305f805dd74b537c9ee3917f45c5839bdb1595a
Java
alfalar/agrinsaweb
/agrinsa/src/co/geographs/agrinsa/dao/NuevoLoteDao.java
UTF-8
2,516
2.4375
2
[]
no_license
package co.geographs.agrinsa.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.engine.SessionFactoryImplementor; import org.springframework.orm.hibernate3.HibernateTemplate; import co.geographs.agrinsa.dao.business.Coordenadas; import co.geographs.agrinsa.dao.business.NuevosLotes; public class NuevoLoteDao { private HibernateTemplate hibernateTemplate; public void setSessionFactory(SessionFactory sessionFactory) { this.hibernateTemplate = new HibernateTemplate(sessionFactory); } /** * Inserta una lista de lotes nuevos en la capa nuevolotefeature * @param nuevoslotes * @return */ public String crearPuntosLote(ArrayList<NuevosLotes> nuevoslotes ){ try{ PreparedStatement query =null; Connection conection=((SessionFactoryImplementor)this.hibernateTemplate.getSessionFactory()).getConnectionProvider() .getConnection(); conection.setAutoCommit(false); Session sesion=this.hibernateTemplate.getSessionFactory().getCurrentSession(); Query querymax=sesion.createSQLQuery("select MAX(lf.LoteNuevoID) from dbo.NUEVOLOTEFEATURE_VW lf"); List<String> maximo=querymax.list(); Iterator iterator = maximo.iterator(); int loteid=0; while(iterator.hasNext()){ try{ loteid = (Integer)iterator.next(); }catch(Exception e){} } for(NuevosLotes nl:nuevoslotes){ loteid++; int numvisita=0; int calificacion=nl.getCalifilote(); int usuarioid=nl.getUsuarioid(); String agricultor=nl.getAgricultor(); String nombrelote=nl.getNombrelote(); int i=0; for(Coordenadas co:nl.getCoordenadas()){ i++; double longitud=co.getLongitud(); double latitud=co.getLatitud(); query = conection.prepareStatement("{call guardapunto (?,?,?,?,?,?,?,?)}"); query.setInt(1, loteid); query.setInt(2, numvisita); query.setInt(3, calificacion); query.setInt(4, usuarioid); query.setDouble(5, latitud); query.setDouble(6, longitud); query.setString(7, agricultor); query.setString(8, nombrelote); query.executeUpdate(); //System.out.println("COORDENADA INSERTADA "+i); } } conection.commit(); conection.close(); return "OK"; }catch(Exception e){ e.printStackTrace(); return "ERROR:"+e.getMessage(); } } }
true
1872db81c85b8fd946d33827f217f7b6ba6e4db9
Java
adnan260896/MeritnatiomProject_1
/Meritnation_grp_project/Meritnation/src/test/java/com/StepDefinition/Meritnation_editprofileStep.java
UTF-8
7,587
2.390625
2
[]
no_license
package com.StepDefinition; import java.io.IOException; import org.apache.log4j.Logger; import com.baseclass.library; import com.excelutility.excelUtil; import com.pages.Meritnation_EditProfile; import com.seleniumutil.seleniumutil; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class Meritnation_editprofileStep extends library { Meritnation_EditProfile profile; seleniumutil util; Logger log = Logger.getLogger("Logger"); excelUtil ex = new excelUtil(); //@tc_01_login @Given("^I need to launch the browser$") public void i_need_to_launch_the_browser() throws InterruptedException { launchapp(); util = new seleniumutil(driver); util.close_popup(); log.info("user launches the browser"); } @Given("^I am on the homepage$") public void i_am_on_the_homepage() { log.info("User is on the homepage"); } @Given("^I click on the login link$") public void i_click_on_the_login_link() throws IOException { profile = new Meritnation_EditProfile(driver); profile.clickLoginLink(); util = new seleniumutil(driver); util.takeSnapShot("C:\\Users\\SRAAWYA CH\\eclipse-workspace\\Meritnation\\src\\test\\resources\\Screenshots\\ClickedLoginLink.png"); log.info("user is on the login page"); } @When("^I enter the valid \"([^\"]*)\" and \"([^\"]*)\"$") public void i_enter_the_valid_and(String username, String password) { profile = new Meritnation_EditProfile(driver); profile.enterDetails(username, password); log.info("user enters the valid username and password"); } @Then("^I click on the login button$") public void i_click_on_the_login_button0() throws IOException { profile = new Meritnation_EditProfile(driver); profile.clickLoginBtn(); util.close_popup2(); util = new seleniumutil(driver); util.takeSnapShot("C:\\Users\\SRAAWYA CH\\eclipse-workspace\\Meritnation\\src\\test\\resources\\Screenshots\\StudentLoginSuccess.png"); browser_close(); log.info("user is logged in to the website and closes the browser"); } //@tc_02_editprofile @Given("^I log in with credentials \"([^\"]*)\" and \"([^\"]*)\"$") public void i_log_in_with_credentials_and(String username, String password) { launchapp(); util = new seleniumutil(driver); util.close_popup(); profile = new Meritnation_EditProfile(driver); profile.clickLoginLink(); profile.enterDetails(username, password); profile.clickLoginBtn(); util.close_popup2(); log.info("user is logged in to the website "); } @Given("^I click on profile icon$") public void i_click_on_profile_icon() { profile = new Meritnation_EditProfile(driver); profile.clickProfileIcon(); log.info("user clicks on profile icon"); } @Given("^click on My Account$") public void click_on_My_Account() { profile = new Meritnation_EditProfile(driver); profile.clickMyAccount(); log.info("user clicks on my account"); } @When("^I navigate to profile page$") public void i_navigate_to_profile_page1() throws IOException { util = new seleniumutil(driver); util.takeSnapShot("C:\\Users\\SRAAWYA CH\\eclipse-workspace\\Meritnation\\src\\test\\resources\\Screenshots\\NavigateToProfilePage.png"); log.info("user navigates to profile page"); } @When("^I click on Edit profile$") public void i_click_on_Edit_profile() { profile = new Meritnation_EditProfile(driver); profile.clickEditProfile(); log.info("user clicks on edit profile"); } @Then("^I change password with newPassword$") public void i_change_password_with_newPassword() throws IOException { profile = new Meritnation_EditProfile(driver); String password = ex.excel_read(6, 1); String newPassword = ex.excel_read(6, 2); profile.changePassword(password, newPassword); //if password changed,update login in other testcases with new password util = new seleniumutil(driver); sleep(3000); util.takeSnapShot("C:\\Users\\SRAAWYA CH\\eclipse-workspace\\Meritnation\\src\\test\\resources\\Screenshots\\UpdatePasswordSuccess.png"); browser_close(); log.info("user changes password and updates the account details "); } //@tc_03_editprofile @Then("^I update account details with emailId and grade$") public void i_update_account_details_with_emailId_and_grade() throws IOException { profile = new Meritnation_EditProfile(driver); String alter_emailid = ex.excel_read(8,1); String grade = ex.excel_read(8, 2); profile.updateAccountDetails(alter_emailid, grade); util = new seleniumutil(driver); sleep(3000); util.takeSnapShot("C:\\Users\\SRAAWYA CH\\eclipse-workspace\\Meritnation\\src\\test\\resources\\Screenshots\\UpdateAccountDetailsSuccess.png"); browser_close(); log.info("User updates account details with school name and Grade"); } @Then("^I click save button$") public void i_click_save_button() { log.info("user clicks save button"); } //@tc_03_editprofile @When("^I navigate to profile page$") public void i_navigate_to_profile_page() { profile = new Meritnation_EditProfile(driver); profile.clickProfileIcon(); profile.clickMyAccount(); profile.clickEditProfile(); log.info("user navigates to profile page"); } @Then("^I update my personal details with DOB and State$") public void i_update_my_personal_details_with_DOB_and_State() throws IOException { profile = new Meritnation_EditProfile(driver); String State = ex.excel_read(10,2); profile.updatePersonalDetails("22-05-1998",State); util = new seleniumutil(driver); sleep(3000); util.takeSnapShot("C:\\Users\\SRAAWYA CH\\eclipse-workspace\\Meritnation\\src\\test\\resources\\Screenshots\\UpdatePersonalDetails.png"); log.info("user updates personal details"); } //@tc_04_editprofile @Then("^I update my School details with SchoolName$") public void i_update_my_School_details_with_SchoolName() throws IOException { profile = new Meritnation_EditProfile(driver); String schoolName = ex.excel_read(12,1); profile.updateSchoolDetails(schoolName); util = new seleniumutil(driver); util.takeSnapShot("C:\\Users\\SRAAWYA CH\\eclipse-workspace\\Meritnation\\src\\test\\resources\\Screenshots\\UpdateSchoolDetailsSuccess.png"); browser_close(); log.info("user updates school details"); } //@tc_05_editprofile @Then("^I update parent details with parentName , parentEmailId and MobileNo.$") public void i_update_parent_details_with_parentName_parentEmailId_and_MobileNo() throws IOException { profile = new Meritnation_EditProfile(driver); String parentName = ex.excel_read(14,1); String parentEmailId = ex.excel_read(14,2); profile.updateParentDetails(parentName, parentEmailId, "9874632145"); util = new seleniumutil(driver); util.takeSnapShot("C:\\Users\\SRAAWYA CH\\eclipse-workspace\\Meritnation\\src\\test\\resources\\Screenshots\\UpdateParentDetailsSuccess.png"); browser_close(); log.info("user updates parent's details"); } //@tc_06_logout @Then("^I click on logout button$") public void i_click_on_logout_button() { profile = new Meritnation_EditProfile(driver); profile.logout(); log.info("user clicks on logout button"); } @Then("^I am logged out$") public void i_am_logged_out() throws IOException { util = new seleniumutil(driver); util.takeSnapShot("C:\\Users\\SRAAWYA CH\\eclipse-workspace\\Meritnation\\src\\test\\resources\\Screenshots\\LogoutSuccess.png"); browser_close(); log.info("user is logged out of the account"); } }
true
053f7d7fe56ba4d7a2102b138fa180da91ee1bc1
Java
shikarimithila/JOB_PORTAL
/src/controller/RecruiterLogin.java
UTF-8
720
1.890625
2
[]
no_license
package controller; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class RecruiterLogin extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException { System.out.println("Recruiterlogin"); request.getRequestDispatcher("Recruiter.jsp").forward(request, response); } }
true
2e9659cb64835bc9c724f01300036a0304e9e4dc
Java
WrRaThY/trade-validator
/src/main/java/priv/rdo/trade/validation/ValidationManager.java
UTF-8
1,428
2.296875
2
[]
no_license
package priv.rdo.trade.validation; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import priv.rdo.trade.model.input.Trade; import priv.rdo.trade.model.output.ValidationResult; import priv.rdo.trade.validation.validators.Validator; import java.util.Collection; import java.util.stream.Stream; @Component public class ValidationManager { private static final XLogger LOG = XLoggerFactory.getXLogger(ValidationManager.class); private final ValidationChain validationChain; public ValidationManager(ApplicationContext ctx) { validationChain = new ValidationChain(); addValidators(ctx); } private void addValidators(ApplicationContext ctx) { LOG.debug("Initializing validation manager..."); Collection<Validator> validators = findValidators(ctx); LOG.debug("Found {} validators: {}", validators.size(), validators); validators.forEach(validationChain::addValidator); LOG.debug("Added validators to the validation chain"); } private Collection<Validator> findValidators(ApplicationContext ctx) { return ctx.getBeansOfType(Validator.class).values(); } public Stream<ValidationResult> validate(Trade trade) { LOG.entry(trade); return LOG.exit(validationChain.validate(trade)); } }
true
16f6495ab61a5bfe8c93d5ef85ba51a3a717b3fa
Java
dither001/PrehistoricEclipse
/src/main/java/net/guavy/prehistoriceclipse/client/model/MegalodonModel.java
UTF-8
15,397
2.28125
2
[ "CC0-1.0" ]
permissive
package net.guavy.prehistoriceclipse.client.model; import net.guavy.prehistoriceclipse.entity.DinosaurEntity; import software.bernie.geckolib.animation.render.AnimatedModelRenderer; // Made with Blockbench 3.5.4 // Exported for Minecraft version 1.12.2 or 1.15.2 (same format for both) for entity models animated with GeckoLib // Paste this class into your mod and follow the documentation for GeckoLib to use animations. You can find the documentation here: https://github.com/bernie-g/geckolib // Blockbench plugin created by Gecko public class MegalodonModel extends DinosaurModel<DinosaurEntity> { private final AnimatedModelRenderer root; private final AnimatedModelRenderer bodymain; private final AnimatedModelRenderer body1; private final AnimatedModelRenderer head; private final AnimatedModelRenderer jawlow1; private final AnimatedModelRenderer jawlow2; private final AnimatedModelRenderer jawlow3; private final AnimatedModelRenderer jawlow4; private final AnimatedModelRenderer teeth; private final AnimatedModelRenderer jawup1; private final AnimatedModelRenderer jawup2; private final AnimatedModelRenderer jawup3; private final AnimatedModelRenderer jawup4; private final AnimatedModelRenderer teeth2; private final AnimatedModelRenderer Body2; private final AnimatedModelRenderer Tail; private final AnimatedModelRenderer shape18; private final AnimatedModelRenderer shape182; private final AnimatedModelRenderer tail5; private final AnimatedModelRenderer tailfin1; private final AnimatedModelRenderer tailfin2; private final AnimatedModelRenderer tailfin5; private final AnimatedModelRenderer tailfin4; private final AnimatedModelRenderer tailfin6; private final AnimatedModelRenderer dorsalfin7; private final AnimatedModelRenderer dorsalfin8; private final AnimatedModelRenderer dorsalfin3fgdf; private final AnimatedModelRenderer dorsalfin3fgd; private final AnimatedModelRenderer dorsalfin1; private final AnimatedModelRenderer dorsalfin2; private final AnimatedModelRenderer dorsalfin3; private final AnimatedModelRenderer dorsalfin4; private final AnimatedModelRenderer fin4; private final AnimatedModelRenderer fin5; private final AnimatedModelRenderer fin6; private final AnimatedModelRenderer fin1; private final AnimatedModelRenderer fin2; private final AnimatedModelRenderer fin3; public MegalodonModel() { textureWidth = 100; textureHeight = 100; root = new AnimatedModelRenderer(this); root.setRotationPoint(0.0F, 0.0F, 0.0F); root.setModelRendererName("root"); this.registerModelRenderer(root); bodymain = new AnimatedModelRenderer(this); bodymain.setRotationPoint(0.0F, 19.2F, -1.1F); root.addChild(bodymain); setRotationAngle(bodymain, 0.0182F, 0.0F, 0.0F); bodymain.setTextureOffset(0, 18).addBox(-4.0F, -3.5F, -5.0F, 8.0F, 8.0F, 8.0F, 0.0F, true); bodymain.setModelRendererName("bodymain"); this.registerModelRenderer(bodymain); body1 = new AnimatedModelRenderer(this); body1.setRotationPoint(0.0F, -0.8F, -4.7F); bodymain.addChild(body1); setRotationAngle(body1, 0.0415F, 0.0F, 0.0F); body1.setTextureOffset(25, 13).addBox(-3.5F, -2.5F, -3.0F, 7.0F, 7.0F, 3.0F, 0.0F, true); body1.setModelRendererName("body1"); this.registerModelRenderer(body1); head = new AnimatedModelRenderer(this); head.setRotationPoint(0.0F, 0.8F, -2.5F); body1.addChild(head); setRotationAngle(head, 0.034F, 0.0F, 0.0F); head.setTextureOffset(0, 63).addBox(-3.0F, -2.983F, -3.5003F, 6.0F, 6.0F, 4.0F, 0.0F, true); head.setModelRendererName("head"); this.registerModelRenderer(head); jawlow1 = new AnimatedModelRenderer(this); jawlow1.setRotationPoint(0.0F, 1.0889F, -2.999F); head.addChild(jawlow1); setRotationAngle(jawlow1, -0.0782F, 0.0F, 0.0F); jawlow1.setTextureOffset(48, 0).addBox(-2.0F, 0.0F, -4.0F, 4.0F, 1.0F, 4.0F, 0.03F, true); jawlow1.setModelRendererName("jawlow1"); this.registerModelRenderer(jawlow1); jawlow2 = new AnimatedModelRenderer(this); jawlow2.setRotationPoint(0.0F, 1.0F, -4.0F); jawlow1.addChild(jawlow2); setRotationAngle(jawlow2, -0.3599F, 0.0F, 0.0F); jawlow2.setTextureOffset(49, 6).addBox(-2.0F, -1.0F, 0.0F, 4.0F, 1.0F, 1.0F, 0.03F, true); jawlow2.setModelRendererName("jawlow2"); this.registerModelRenderer(jawlow2); jawlow3 = new AnimatedModelRenderer(this); jawlow3.setRotationPoint(0.0F, 0.0F, 1.0F); jawlow2.addChild(jawlow3); setRotationAngle(jawlow3, 0.182F, 0.0F, 0.0F); jawlow3.setTextureOffset(54, 10).addBox(-2.0F, -1.0F, 0.0F, 4.0F, 1.0F, 1.0F, 0.03F, true); jawlow3.setModelRendererName("jawlow3"); this.registerModelRenderer(jawlow3); jawlow4 = new AnimatedModelRenderer(this); jawlow4.setRotationPoint(0.0F, 0.0F, 1.0F); jawlow3.addChild(jawlow4); setRotationAngle(jawlow4, 0.0367F, 0.0F, 0.0F); jawlow4.setTextureOffset(52, 14).addBox(-2.0F, -1.0F, 0.0F, 4.0F, 1.0F, 2.0F, 0.03F, true); jawlow4.setModelRendererName("jawlow4"); this.registerModelRenderer(jawlow4); teeth = new AnimatedModelRenderer(this); teeth.setRotationPoint(-0.5F, -0.5F, -0.8F); jawlow1.addChild(teeth); teeth.setTextureOffset(67, 0).addBox(-1.0F, 0.0F, -3.0F, 3.0F, 1.0F, 3.0F, 0.03F, true); teeth.setModelRendererName("teeth"); this.registerModelRenderer(teeth); jawup1 = new AnimatedModelRenderer(this); jawup1.setRotationPoint(0.0F, 0.017F, -2.8003F); head.addChild(jawup1); setRotationAngle(jawup1, 0.1285F, 0.0F, 0.0F); jawup1.setTextureOffset(23, 63).addBox(-2.5F, -2.9103F, -4.3058F, 5.0F, 3.0F, 5.0F, 0.0F, true); jawup1.setModelRendererName("jawup1"); this.registerModelRenderer(jawup1); jawup2 = new AnimatedModelRenderer(this); jawup2.setRotationPoint(0.0F, -1.5103F, -2.5058F); jawup1.addChild(jawup2); setRotationAngle(jawup2, 0.4458F, 0.0F, 0.0F); jawup2.setTextureOffset(21, 72).addBox(-2.5F, -2.0F, -2.0F, 5.0F, 3.0F, 1.0F, 0.0F, true); jawup2.setModelRendererName("jawup2"); this.registerModelRenderer(jawup2); jawup3 = new AnimatedModelRenderer(this); jawup3.setRotationPoint(0.0F, -0.2F, -0.7F); jawup2.addChild(jawup3); setRotationAngle(jawup3, 0.166F, 0.0F, 0.0F); jawup3.setTextureOffset(0, 54).addBox(-2.5F, -2.0F, -2.0F, 5.0F, 3.0F, 1.0F, 0.0F, true); jawup3.setModelRendererName("jawup3"); this.registerModelRenderer(jawup3); jawup4 = new AnimatedModelRenderer(this); jawup4.setRotationPoint(0.0F, 0.5897F, 0.7942F); jawup1.addChild(jawup4); setRotationAngle(jawup4, -0.2025F, 0.0F, 0.0F); jawup4.setTextureOffset(0, 74).addBox(-2.5F, -1.0F, -5.0F, 5.0F, 2.0F, 5.0F, 0.0F, true); jawup4.setModelRendererName("jawup4"); this.registerModelRenderer(jawup4); teeth2 = new AnimatedModelRenderer(this); teeth2.setRotationPoint(0.0F, 0.4F, -1.9F); jawup4.addChild(teeth2); teeth2.setTextureOffset(67, 5).addBox(-2.0F, 0.0F, -3.0F, 4.0F, 1.0F, 3.0F, 0.0F, true); teeth2.setModelRendererName("teeth2"); this.registerModelRenderer(teeth2); Body2 = new AnimatedModelRenderer(this); Body2.setRotationPoint(0.0F, 0.3F, 3.0F); bodymain.addChild(Body2); setRotationAngle(Body2, -0.0819F, 0.0F, 0.0F); Body2.setTextureOffset(0, 0).addBox(-3.5F, -3.5946F, -1.1309F, 7.0F, 7.0F, 5.0F, 0.0F, true); Body2.setModelRendererName("Body2"); this.registerModelRenderer(Body2); Tail = new AnimatedModelRenderer(this); Tail.setRotationPoint(0.0F, -0.3946F, 3.8691F); Body2.addChild(Tail); setRotationAngle(Tail, 0.0157F, 0.0F, 0.0F); Tail.setTextureOffset(25, 0).addBox(-3.0F, -2.8998F, -0.978F, 6.0F, 6.0F, 5.0F, 0.0F, true); Tail.setModelRendererName("Tail"); this.registerModelRenderer(Tail); shape18 = new AnimatedModelRenderer(this); shape18.setRotationPoint(0.0F, -0.1998F, 4.022F); Tail.addChild(shape18); setRotationAngle(shape18, 0.0087F, 0.0F, 0.0F); shape18.setTextureOffset(0, 42).addBox(-2.0F, -2.4999F, -0.9869F, 4.0F, 5.0F, 6.0F, 0.0F, true); shape18.setModelRendererName("shape18"); this.registerModelRenderer(shape18); shape182 = new AnimatedModelRenderer(this); shape182.setRotationPoint(0.0F, -0.1999F, 5.0131F); shape18.addChild(shape182); shape182.setTextureOffset(22, 49).addBox(-1.5F, -1.9F, -1.0F, 3.0F, 4.0F, 6.0F, 0.0F, true); shape182.setModelRendererName("shape182"); this.registerModelRenderer(shape182); tail5 = new AnimatedModelRenderer(this); tail5.setRotationPoint(0.0F, 0.0F, 5.0F); shape182.addChild(tail5); tail5.setTextureOffset(17, 37).addBox(-1.0F, -1.5F, -1.0F, 2.0F, 3.0F, 6.0F, 0.0F, true); tail5.setModelRendererName("tail5"); this.registerModelRenderer(tail5); tailfin1 = new AnimatedModelRenderer(this); tailfin1.setRotationPoint(0.0F, 0.0F, 3.0F); tail5.addChild(tailfin1); setRotationAngle(tailfin1, -0.5878F, 0.0F, 0.0F); tailfin1.setTextureOffset(39, 33).addBox(-0.5F, -4.0F, -1.0F, 1.0F, 4.0F, 3.0F, 0.0F, true); tailfin1.setModelRendererName("tailfin1"); this.registerModelRenderer(tailfin1); tailfin2 = new AnimatedModelRenderer(this); tailfin2.setRotationPoint(0.0F, -1.9F, 2.0F); tailfin1.addChild(tailfin2); setRotationAngle(tailfin2, -0.3187F, 0.0F, 0.0F); tailfin2.setTextureOffset(40, 42).addBox(-0.5F, 0.0F, 0.0F, 1.0F, 3.0F, 2.0F, 0.0F, true); tailfin2.setModelRendererName("tailfin2"); this.registerModelRenderer(tailfin2); tailfin5 = new AnimatedModelRenderer(this); tailfin5.setRotationPoint(0.0F, 1.7F, 1.2F); tailfin2.addChild(tailfin5); setRotationAngle(tailfin5, -1.4048F, 0.0F, 0.0F); tailfin5.setTextureOffset(40, 48).addBox(-0.5F, -3.0F, -1.0F, 1.0F, 3.0F, 2.0F, 0.0F, true); tailfin5.setModelRendererName("tailfin5"); this.registerModelRenderer(tailfin5); tailfin4 = new AnimatedModelRenderer(this); tailfin4.setRotationPoint(0.0F, -3.8F, 0.5F); tailfin1.addChild(tailfin4); setRotationAngle(tailfin4, -0.0113F, 0.0F, 0.0F); tailfin4.setTextureOffset(31, 33).addBox(-0.5F, -4.0F, -1.0F, 1.0F, 4.0F, 2.0F, 0.0F, true); tailfin4.setModelRendererName("tailfin4"); this.registerModelRenderer(tailfin4); tailfin6 = new AnimatedModelRenderer(this); tailfin6.setRotationPoint(0.0F, -3.8F, 0.6F); tailfin4.addChild(tailfin6); setRotationAngle(tailfin6, -0.1072F, 0.0F, 0.0F); tailfin6.setTextureOffset(50, 33).addBox(-0.5F, -3.0F, -1.0F, 1.0F, 3.0F, 1.0F, 0.0F, true); tailfin6.setModelRendererName("tailfin6"); this.registerModelRenderer(tailfin6); dorsalfin7 = new AnimatedModelRenderer(this); dorsalfin7.setRotationPoint(0.0F, 0.2F, -0.6F); shape182.addChild(dorsalfin7); setRotationAngle(dorsalfin7, -0.3595F, 0.0F, 0.0F); dorsalfin7.setTextureOffset(66, 40).addBox(-0.5F, -3.0F, 0.0F, 1.0F, 3.0F, 3.0F, 0.0F, true); dorsalfin7.setModelRendererName("dorsalfin7"); this.registerModelRenderer(dorsalfin7); dorsalfin8 = new AnimatedModelRenderer(this); dorsalfin8.setRotationPoint(0.0F, -1.8F, -0.1F); dorsalfin7.addChild(dorsalfin8); setRotationAngle(dorsalfin8, -0.2826F, 0.0F, 0.0F); dorsalfin8.setTextureOffset(66, 63).addBox(-0.5F, -3.0F, 0.0F, 1.0F, 3.0F, 2.0F, 0.0F, true); dorsalfin8.setModelRendererName("dorsalfin8"); this.registerModelRenderer(dorsalfin8); dorsalfin3fgdf = new AnimatedModelRenderer(this); dorsalfin3fgdf.setRotationPoint(0.0F, -0.3999F, 0.4131F); shape18.addChild(dorsalfin3fgdf); setRotationAngle(dorsalfin3fgdf, -2.0687F, -0.0869F, -0.2845F); dorsalfin3fgdf.setTextureOffset(66, 47).addBox(-0.5F, -3.0F, 0.0F, 1.0F, 4.0F, 4.0F, 0.0F, true); dorsalfin3fgdf.setModelRendererName("dorsalfin3fgdf"); this.registerModelRenderer(dorsalfin3fgdf); dorsalfin3fgd = new AnimatedModelRenderer(this); dorsalfin3fgd.setRotationPoint(0.2F, -0.4001F, 0.421F); shape18.addChild(dorsalfin3fgd); setRotationAngle(dorsalfin3fgd, -2.0687F, -0.0869F, 0.2845F); dorsalfin3fgd.setTextureOffset(66, 47).addBox(-0.5F, -3.0F, 0.0F, 1.0F, 4.0F, 4.0F, 0.0F, false); dorsalfin3fgd.setModelRendererName("dorsalfin3fgd"); this.registerModelRenderer(dorsalfin3fgd); dorsalfin1 = new AnimatedModelRenderer(this); dorsalfin1.setRotationPoint(0.0F, -3.5F, -0.8F); bodymain.addChild(dorsalfin1); setRotationAngle(dorsalfin1, -0.182F, 0.0F, 0.0F); dorsalfin1.setTextureOffset(55, 54).addBox(-0.5F, -1.0F, 0.0F, 1.0F, 1.0F, 5.0F, 0.0F, true); dorsalfin1.setModelRendererName("dorsalfin1"); this.registerModelRenderer(dorsalfin1); dorsalfin2 = new AnimatedModelRenderer(this); dorsalfin2.setRotationPoint(0.0F, 0.0F, 0.4F); dorsalfin1.addChild(dorsalfin2); setRotationAngle(dorsalfin2, -0.148F, 0.0F, 0.0F); dorsalfin2.setTextureOffset(48, 47).addBox(-0.5F, -3.0F, 0.0F, 1.0F, 3.0F, 4.0F, 0.0F, true); dorsalfin2.setModelRendererName("dorsalfin2"); this.registerModelRenderer(dorsalfin2); dorsalfin3 = new AnimatedModelRenderer(this); dorsalfin3.setRotationPoint(0.0F, -1.9F, 0.4F); dorsalfin2.addChild(dorsalfin3); setRotationAngle(dorsalfin3, -0.148F, 0.0F, 0.0F); dorsalfin3.setTextureOffset(68, 56).addBox(-0.5F, -3.0F, 0.0F, 1.0F, 3.0F, 3.0F, 0.0F, true); dorsalfin3.setModelRendererName("dorsalfin3"); this.registerModelRenderer(dorsalfin3); dorsalfin4 = new AnimatedModelRenderer(this); dorsalfin4.setRotationPoint(0.0F, -1.8F, 0.5F); dorsalfin3.addChild(dorsalfin4); setRotationAngle(dorsalfin4, -0.148F, 0.0F, 0.0F); dorsalfin4.setTextureOffset(55, 41).addBox(-0.5F, -3.0F, 0.0F, 1.0F, 3.0F, 2.0F, 0.0F, true); dorsalfin4.setModelRendererName("dorsalfin4"); this.registerModelRenderer(dorsalfin4); fin4 = new AnimatedModelRenderer(this); fin4.setRotationPoint(2.7F, 1.8F, -3.5F); bodymain.addChild(fin4); setRotationAngle(fin4, 0.3053F, 0.07F, -0.8639F); fin4.setTextureOffset(49, 21).addBox(-0.5F, 0.0F, -1.5F, 1.0F, 2.0F, 4.0F, 0.0F, false); fin4.setModelRendererName("fin4"); this.registerModelRenderer(fin4); fin5 = new AnimatedModelRenderer(this); fin5.setRotationPoint(-0.5F, 1.0F, 0.5F); fin4.addChild(fin5); setRotationAngle(fin5, 0.0171F, 0.0F, 0.0F); fin5.setTextureOffset(59, 25).addBox(0.0F, 0.0F, -1.5F, 1.0F, 3.0F, 3.0F, 0.0F, false); fin5.setModelRendererName("fin5"); this.registerModelRenderer(fin5); fin6 = new AnimatedModelRenderer(this); fin6.setRotationPoint(0.0F, 3.0F, -1.0F); fin5.addChild(fin6); setRotationAngle(fin6, 0.0585F, 0.0F, 0.0F); fin6.setTextureOffset(59, 36).addBox(0.0F, 0.0F, 0.0F, 1.0F, 2.0F, 2.0F, 0.0F, false); fin6.setModelRendererName("fin6"); this.registerModelRenderer(fin6); fin1 = new AnimatedModelRenderer(this); fin1.setRotationPoint(-2.7F, 1.8F, -3.5F); bodymain.addChild(fin1); setRotationAngle(fin1, 0.3053F, -0.07F, 0.8639F); fin1.setTextureOffset(49, 21).addBox(-0.5F, 0.0F, -1.5F, 1.0F, 2.0F, 4.0F, 0.0F, false); fin1.setModelRendererName("fin1"); this.registerModelRenderer(fin1); fin2 = new AnimatedModelRenderer(this); fin2.setRotationPoint(-0.5F, 1.0F, 0.5F); fin1.addChild(fin2); setRotationAngle(fin2, 0.0171F, 0.0F, 0.0F); fin2.setTextureOffset(59, 25).addBox(0.0F, 0.0F, -1.5F, 1.0F, 3.0F, 3.0F, 0.0F, false); fin2.setModelRendererName("fin2"); this.registerModelRenderer(fin2); fin3 = new AnimatedModelRenderer(this); fin3.setRotationPoint(0.0F, 3.0F, -1.0F); fin2.addChild(fin3); setRotationAngle(fin3, 0.0585F, 0.0F, 0.0F); fin3.setTextureOffset(59, 36).addBox(0.0F, 0.0F, 0.0F, 1.0F, 2.0F, 2.0F, 0.0F, false); fin3.setModelRendererName("fin3"); this.registerModelRenderer(fin3); this.rootBones.add(root); } }
true
31672043dc55b0c7dc9d43e0e75b629566f1d206
Java
kyeongsikkim/TestRepositroy
/JavaFXProgramming/src/ch17/homework/exam32/RootController.java
UTF-8
5,852
2.796875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ch17.homework.exam32; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.util.Callback; /** * FXML Controller class * * @author Administrator */ public class RootController implements Initializable { @FXML//FXML 로 사용할 경우는 private ListView<Food> listView;//필드에서만 사용이 가능하다 FXML 은 //fx:id 컨트롤러에 FXML 어노테이션으로 참조하기 위해서 사용하는것이고 //코드에서 직접 id 값으로 객체를 찾을 때 사용을 하거나 CSS에서 객체를 찾을 때 사용을 한다. //lookup("id") 으로 아이디를 주게 되면은 id 에 해당하는 객체가 리턴된다.메소드가 실행하면서fxml 의 객체를 찾아 사용하는 경우 //lookup 메소드를 id 를 줘서 찾는다.한곳에 두가지 사용가능하다. fx:id 와 id 값 두개 다 가능 @Override public void initialize(URL url, ResourceBundle rb) { listView.setCellFactory(new Callback<ListView<Food>, ListCell<Food>>() {//팩토리 객체이다 머를 만드는 역할을 한다.셀을 만드는 객체를 등록하겠다. @Override public ListCell<Food> call(ListView<Food> param) {//폰갯수만큼 리스트 셀을 만드는 역할 외부에서 폰객체가 들어올 때 실행한다.셀을 만들어서 리턴하는 역할을 한다. ListCell<Food>listCell=new ListCell<Food>(){//리스트 셀을 상속해서 자식객체로 만든다. @Override//업데이트 아이템 재정의 한다 protected void updateItem(Food item, boolean empty) {//기본값이 true 이다. super.updateItem(item, empty);//부모에특정내용을 시켜야 한다. if(empty)return;//맨처음 실행할때는 폰객체가 없다. 그래서 그냥실행을 시키게 되면 에러난다. try { //셀안에 들어갈 내용을 구성하는 곳이다. 셀안에 들어가는 메소드내용 phone item.fxml 을 결합해서 call 메소드 를 통해서 만들어 낸다. HBox hbox=(HBox)FXMLLoader.load(getClass().getResource("food.fxml"));//루트 컨테이너 ImageView foodImage=(ImageView)hbox.lookup("#image");//id 값 lookup 은 노드값을 리턴하기 때문에 강제 형변환을 해준다. Label foodName=(Label)hbox.lookup("#name");//id 로 넣어줄때는#을 붙여줘야한다. ImageView starImage=(ImageView)hbox.lookup("#score"); System.out.println(starImage.toString()); Label foodContent=(Label)hbox.lookup("#content"); System.out.println(foodContent.toString()); foodImage.setImage(new Image(getClass().getResource("images/"+item.getImage()).toString())); foodName.setText(item.getName()); System.out.println(foodName.toString()); foodContent.setText(item.getDescription()); System.out.println(foodContent.toString()); System.out.println(item.getScore()); starImage.setImage(new Image(getClass().getResource("images/"+"star"+item.getScore()+".png").toString())); //cell 의 내용으로 설정하는 것이다 setGraphic(hbox); } catch (IOException ex) {} } };//익명객체일때 객체만들때 클래스면 상속해서 자식객체로 만들고 인터페이스는 구현하는 것이다. return listCell; } });//하나의 행을 만드는 놈을 셋팅하겠다.call 은 phone 객체가listView 에 들어오면은 그걸로 cell을 만들어 준다. //선택 속성감시 // listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Food>(){ // @Override // public void changed(ObservableValue<? extends Food> observable, Food oldValue, Food newValue) { // System.out.println(newValue.getName()+":"+newValue.getImage()); // } // // }); ObservableList<Food>value=FXCollections.observableArrayList(); value.add(new Food("food01.png","삼겹살",3,"짱맛")); value.add(new Food("food02.png","장어",5,"존맛")); value.add(new Food("food03.png","장어맛",8,"개맛")); listView.setItems(value); } } //리스트 뷰는 안에 항목을 cell 이라고 부른다.cell 은 팩토리가 만들어 준다. callBack 이라는 객체를 통해서 만든다. //콜백이라는 객체로 셀을 만들고 셀안에 들어가는 것은 item.fxml 을 로드 한다.셀안에 머가 들어간다.폰에잇는객체를 fxml 에다가 //정보를 넣어줘서 로드한다. 첫번째 클래스 phone 만들고 두번째로 fxml 을 만들고 3 셀팩토리를 만든다.
true
c0eb6e36ddd07f689165eaa813a0930ff1601cad
Java
dlwo01/github50
/Java/src/ch11/_01_ArrayExceptionEx.java
UTF-8
921
3.734375
4
[]
no_license
package ch11; public class _01_ArrayExceptionEx { public static void main(String[] args) { /* * 예외 처리 목적 : 정상종료 * try { * 예외가 발생할 수 있는 코드 부분 * } catch(처리할 예외 타입 e) { * try 블록안에서 예외가 발생했을 때 예외를 처리하는 부분 * } finally { * 항상 수행되는 부분, 주로 자원해제를 위한 close() 문장이 온다. * } */ int[] array = new int[5]; try { for(int i = 0; i <= array.length; i++) { array[i] = i; System.out.println(array[i]); // 예외가 발생 } } catch(ArrayIndexOutOfBoundsException e){ System.out.println(e);//java.lang.ArrayIndexOutOfBoundsException: 5 System.out.println("예외 처리 부분"); } System.out.println("종료합니다."); } } //예외처리는 비정상처리를 막아주는 역할
true
902f55a0be4c1a7f9ad82af32ed72bf4a0d8d83d
Java
magicgis/mshop
/src/main/java/com/misuosi/mshop/entity/WaybillTemplate.java
UTF-8
2,732
1.921875
2
[]
no_license
/* * Copyright (c) 2014 * 广州米所思信息科技有限公司(Guangzhou Mythos Information technology co., LTD) * All rights reserved. */ package com.misuosi.mshop.entity; import com.misuosi.mshop.db.Entity; import com.misuosi.mshop.db.annotation.Id; import java.sql.Timestamp; /** * Description : 实体类 WaybillTemplate * <br><br>Time : 2015/07/14 08:46 * * @author GenEntity * @version 1.0 * @since 1.0 */ public class WaybillTemplate extends Entity { @Id private Integer wateId; private Integer excoId; private String wateName; private Double wateLength; private Double wateHeight; private String watePictureUrl; private Short wateOffsetX; private Short wateOffsetY; private Byte wateDefault; private Byte wateType; private String wateContent; private Timestamp wateModifyTime; private Timestamp wateCreateTime; public Integer getWateId() { return wateId; } public void setWateId(Integer wateId) { this.wateId = wateId; } public Integer getExcoId() { return excoId; } public void setExcoId(Integer excoId) { this.excoId = excoId; } public String getWateName() { return wateName; } public void setWateName(String wateName) { this.wateName = wateName; } public Double getWateLength() { return wateLength; } public void setWateLength(Double wateLength) { this.wateLength = wateLength; } public Double getWateHeight() { return wateHeight; } public void setWateHeight(Double wateHeight) { this.wateHeight = wateHeight; } public String getWatePictureUrl() { return watePictureUrl; } public void setWatePictureUrl(String watePictureUrl) { this.watePictureUrl = watePictureUrl; } public Short getWateOffsetX() { return wateOffsetX; } public void setWateOffsetX(Short wateOffsetX) { this.wateOffsetX = wateOffsetX; } public Short getWateOffsetY() { return wateOffsetY; } public void setWateOffsetY(Short wateOffsetY) { this.wateOffsetY = wateOffsetY; } public Byte getWateDefault() { return wateDefault; } public void setWateDefault(Byte wateDefault) { this.wateDefault = wateDefault; } public Byte getWateType() { return wateType; } public void setWateType(Byte wateType) { this.wateType = wateType; } public String getWateContent() { return wateContent; } public void setWateContent(String wateContent) { this.wateContent = wateContent; } public Timestamp getWateModifyTime() { return wateModifyTime; } public void setWateModifyTime(Timestamp wateModifyTime) { this.wateModifyTime = wateModifyTime; } public Timestamp getWateCreateTime() { return wateCreateTime; } public void setWateCreateTime(Timestamp wateCreateTime) { this.wateCreateTime = wateCreateTime; } }
true
6415c675fd0c8ddd758deb05665569033e357599
Java
libgdx/libgdx
/extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/org/jbox2d/particle/ParticleBodyContact.java
UTF-8
498
2.53125
3
[ "Apache-2.0", "LicenseRef-scancode-other-copyleft", "CC-BY-SA-3.0", "LicenseRef-scancode-proprietary-license" ]
permissive
package org.jbox2d.particle; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; public class ParticleBodyContact { /** Index of the particle making contact. */ public int index; /** The body making contact. */ public Body body; /** Weight of the contact. A value between 0.0f and 1.0f. */ float weight; /** The normalized direction from the particle to the body. */ public final Vec2 normal = new Vec2(); /** The effective mass used in calculating force. */ float mass; }
true
9a00ac3c7d3f6c53d4da14633a8f0b4c152d7429
Java
navedev/genericstream
/genericstream/src/main/java/com/demo/genericstream/service/MessagingService.java
UTF-8
909
2.171875
2
[]
no_license
/** * Test Copyright Code */ package com.demo.genericstream.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.support.MessageBuilder; import org.springframework.stereotype.Service; import org.springframework.util.MimeTypeUtils; import com.demo.genericstream.model.Note; import com.demo.genericstream.stream.MessageStream; import lombok.extern.slf4j.Slf4j; @Service @Slf4j public class MessagingService { @Autowired private MessageStream messageStream; public void sendMessage(Note note) { log.info("Inside sendMessage()"); MessageChannel msgChannel = messageStream.outboundMessage(); msgChannel.send(MessageBuilder.withPayload(note) .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON).build()); } }
true
4b54781367c201eb9effeda650bc7d95f7a84295
Java
yu199195/jsb
/src/main/java/com/taobao/api/response/CainiaoWaybillIiGetResponse.java
UTF-8
2,459
1.804688
2
[]
no_license
package com.taobao.api.response; import com.taobao.api.TaobaoObject; import com.taobao.api.TaobaoResponse; import com.taobao.api.internal.mapping.ApiField; import com.taobao.api.internal.mapping.ApiListField; import java.util.List; public class CainiaoWaybillIiGetResponse extends TaobaoResponse { private static final long serialVersionUID = 3748413974868424859L; @ApiListField("modules") @ApiField("waybill_cloud_print_response") private List<WaybillCloudPrintResponse> modules; public void setModules(List<WaybillCloudPrintResponse> modules) { this.modules = modules; } public List<WaybillCloudPrintResponse> getModules() { return this.modules; } public static class WaybillCloudPrintResponse extends TaobaoObject { private static final long serialVersionUID = 1273273372915274396L; @ApiField("encoding_type") private Long encodingType; @ApiField("object_id") private String objectId; @ApiField("print_data") private String printData; @ApiField("signature") private String signature; @ApiField("template_url") private String templateUrl; @ApiField("waybill_code") private String waybillCode; public Long getEncodingType() { return this.encodingType; } public void setEncodingType(Long encodingType) { this.encodingType = encodingType; } public String getObjectId() { return this.objectId; } public void setObjectId(String objectId) { this.objectId = objectId; } public String getPrintData() { return this.printData; } public void setPrintData(String printData) { this.printData = printData; } public String getSignature() { return this.signature; } public void setSignature(String signature) { this.signature = signature; } public String getTemplateUrl() { return this.templateUrl; } public void setTemplateUrl(String templateUrl) { this.templateUrl = templateUrl; } public String getWaybillCode() { return this.waybillCode; } public void setWaybillCode(String waybillCode) { this.waybillCode = waybillCode; } } }
true
9a17ba88468f79f81296140ce27534fb2e653b52
Java
Donggyeom/https-github.com-hrnoh-graduate_proj-EccessManagementApplication
/app/src/main/java/ng/grad_proj/eccessmanagementapplication/Activity/TabFragment3.java
UTF-8
3,307
2.1875
2
[]
no_license
package ng.grad_proj.eccessmanagementapplication.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.content.SharedPreferencesCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import com.google.gson.Gson; import java.util.List; import java.util.concurrent.ExecutionException; import ng.grad_proj.eccessmanagementapplication.Network.PullDoorlockList; import ng.grad_proj.eccessmanagementapplication.R; import ng.grad_proj.eccessmanagementapplication.VO.DoorlockVO; /** * Created by KimDonggyeom on 2017-06-12. */ public class TabFragment3 extends Fragment { private List<DoorlockVO> doorlockList; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.tab3, container, false); // 도어락 리스트 가져오기 PullDoorlockList pullDoorlockList = new PullDoorlockList(); try { pullDoorlockList.execute("").get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } doorlockList = pullDoorlockList.getDoorlockList(); String[] doorlockListData = new String[doorlockList.size()]; // 공유 객체 저장 SharedPreferences dList = getActivity().getSharedPreferences("dList", Context.MODE_PRIVATE); final SharedPreferences.Editor editor = dList.edit(); Gson gson = new Gson(); for (int i=0; i<doorlockList.size(); i++) { // 리스트 아이템 설정 doorlockListData[i] = doorlockList.get(i).toListData(); // 공유데이터 설정 editor.putString("doorlockItem" + i, gson.toJson(doorlockList.get(i))); } editor.commit(); // 리스트뷰 세팅 ListView doorlockListView = (ListView)view.findViewById(R.id.doorlockListView); ArrayAdapter<String> dAdapter = new ArrayAdapter<String>(view.getContext(), android.R.layout.simple_list_item_1, doorlockListData); doorlockListView.setAdapter(dAdapter); // 아이템 클릭 리스너 doorlockListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { editor.putInt("doorlockClicked", position); editor.commit(); startActivity(new Intent(view.getContext(), DoorlockDetailActivity.class)); } }); // 도어락 등록 버튼 리스너 Button addBtn = (Button) view.findViewById(R.id.doorlockAddBtn); addBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(v.getContext(), AddDoorlockActivity.class)); } }); return view; } }
true
1f48de48daedefa5b681337ae62991a7891a0ebf
Java
wenliangwei555/-
/BaiseeOA/.svn/pristine/de/deabce11d855bed23d736f25e02368f4b2e02cd2.svn-base
UTF-8
752
2.1875
2
[]
no_license
package cn.baisee.oa.service.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.baisee.oa.dao.baisee.BaiseeClassroomMapper; import cn.baisee.oa.model.course.BaiseeClassroom; import cn.baisee.oa.service.BaiseeClassroomService; @Service public class BaiseeClassroomServiceImpl implements BaiseeClassroomService { @Autowired private BaiseeClassroomMapper classroomMapper; @Override public List<BaiseeClassroom> selectClassroomList(String userType) { Map<String, Object> map = new HashMap<String, Object>(); map.put("roomType", userType); return classroomMapper.selectClassroomList( map); } }
true
b7994c2ea179d94d42e92efd79593b5b054c42af
Java
uno1bruno2/BrunoJava
/Taxes/src/main/java/main/Main.java
UTF-8
372
2.671875
3
[]
no_license
package main; public class Main { public void percentage(int n) { int ntax = 0; if (n > 0 && n < 15000) { ntax = 0; } else if (n > 14999 && n < 20000) { ntax = n * 0.1; } else if (n > 19999 && n < 30000) { ntax = n * 0.15; } else if (n > 29999 && n < 45000) { ntax = n * 0.2; } else { ntax = n * 0.25; } } }
true
c5e9f12f9e6c088fa66d32a7769e038c03bc5c8d
Java
AndresSal/Distribuidas
/Jaccard_Tanimoto/src/jaccard_tanimoto/Hilo.java
UTF-8
4,364
3.296875
3
[]
no_license
package jaccard_tanimoto; import static jaccard_tanimoto.Quimicos.T; import java.util.ArrayList; import java.util.Map; import java.util.TreeMap; /** * * @author joselimaico andressalazar */ public class Hilo extends Thread implements Runnable { //Creacción de ArrayList para el manejo de los caracteres de la formula que se evalua en cada iteracción. ArrayList<Character> caracteres = new ArrayList<>(); //Creacción de 2 treemaps para la comparación de caracteres entre dos formulas. TreeMap<Character, Integer> mapa_a = new TreeMap<>(); TreeMap<Character, Integer> mapa_b = new TreeMap<>(); //formulas que recibirá la funcion que calcula el coeficiente JT. String a,b; public Hilo(String a,String b) { this.a=a; this.b=b; } @Override public void run() { T(a,b); } //funcion que recibe como entrada dos strings y calcula el coeficiente Jaccard-Tanimoto public synchronized void T(String a, String b) { int Na = 0, Nb = 0, Nc = 0; //llamada a las funciones contaCaracteres y Comparacion_Formulas Na=contarCaracteres(a, mapa_a); Nb=contarCaracteres(b, mapa_b); Nc=Comparacion_Formulas(mapa_a, mapa_b); //limpieza de los mapas A y B. mapa_a.clear(); mapa_b.clear(); T=(float)Nc/(Na+Nb-Nc); } //funcion que recibe como argumento dos treemaps y devuelve el número de elementos en común. public int Comparacion_Formulas(TreeMap<Character,Integer> A, TreeMap <Character,Integer> B) { //variable que almacenará el número de caracteres en común. int comunes = 0; for (Map.Entry<Character, Integer> mA : A.entrySet()) { //loop de cada elemento del treemap A. for (Map.Entry<Character, Integer> mB : B.entrySet()) { //loop de cada elemento del treemap B if (mA.getKey().equals(mB.getKey())) { //en caso de que las llaves del elemento actual de ambas treemaps coincidan if (mA.getValue() <= mB.getValue() ) { //el valor menor será añadido a la variable comunes += mA.getValue(); } else { comunes += mB.getValue(); } } } } return comunes; } //funcion que recibe como parámetros una fórmula y un treemap con todos los caracteres que se hayan contado, retorna el total de caracteres del treemap. public int contarCaracteres(String formula,TreeMap<Character,Integer> tabla) { int cont; //variable que contabilizará el número de caracteres de la formula. for (int i = 0; i < formula.length(); i++) { //almacenar todos los caracteres de la formula en un ArrayList caracteres.add(formula.charAt(i)); } //recorrido de cada caracter de la formula for (char expresion : caracteres) { cont = 0; switch (expresion) { //en caso de ser una @, se añade en la tabla el caracter y el valor de 1 y termina la iteracción. case '@': tabla.put(expresion, 1); break; default: //para el caso en que no sea @ se vuelve a comparar cada uno de los caracteres del ArrayList for(int i=0;i<caracteres.size();i++){ if (expresion==caracteres.get(i)) { // si existe coincidencia se aumenta el contador cont++; } } //al final colocar el caracter junto con el valor del contador en el treemap. tabla.put(expresion, cont); break; } } //ahora sumará el total de caracteres que tendrá el treemap generado cont=0; for(Map.Entry<Character,Integer> t:tabla.entrySet()){ cont+=t.getValue(); } caracteres.clear(); //retorno del total de caracteres encontrados en la fórmula.} return cont; } }
true
edd1a15093c323315d950ad1334df6459822337b
Java
buhti/esup-covoiturage
/src/main/java/org/esupportail/covoiturage/web/form/DateTimeField.java
UTF-8
1,155
2.984375
3
[]
no_license
package org.esupportail.covoiturage.web.form; import javax.validation.Valid; import org.joda.time.DateTime; import org.joda.time.LocalTime; public class DateTimeField extends DateField { @Valid private TimeField timeField; /** * Construteur. */ public DateTimeField() { this(new DateTime()); } /** * Construteur. * * @param date Valeur par défaut */ public DateTimeField(DateTime date) { super(date); timeField = new TimeField(new LocalTime(date.getHourOfDay(), date.getMinuteOfHour())); } /** * Retourne le champ horaire. * * @return */ public String getTime() { return timeField.getTime(); } public void setTime(String time) { timeField.setTime(time); } /** * Retourne la date et l'horaire sous forme d'un objet manipulable. * * @return date et horaire */ @Override public DateTime toDateTime() { LocalTime time = timeField.toLocalTime(); return new DateTime(getYear(), getMonth(), getDay(), time.hourOfDay().get(), time.minuteOfHour().get()); } }
true
f5d56674e9fe164dc10b523e37b6c69c321714f2
Java
KeiSakam/pokemon-java
/ToyShop.java
SHIFT_JIS
2,062
3.6875
4
[]
no_license
//main()Ƃ\bhĂNXׂẴvȌo_ //RXgN^gƁACX^XݒƓɃtB[hɏlݒł悤ɂȂB //ShopKeeper͎q\̃NXAsuzuki(CX^X)ϐ()(car1̂킩₷)B //suzukiɂ́AShopKeeperƂÕNXĂB //suzukiƂϐɁAShopKeeperNX琶CX^XB public class ToyShop{ public static void main(String[] args){ //new͗\BꉞZqB ShopKeeper suzuki =new ShopKeeper(""); //ԑ匳̃NXŃCX^X쐬B CarToy car1= new CarToy("C001",500);//RXgN^̂ PatrolCarToy patrolCar1= new PatrolCarToy("P001",600);//utB[h́vlݒ肪łB TrainToy train1= new TrainToy("T001",700); //tB[h͋̓Iɂ͊{`́uϐvNX́uϐvȂ̂ //lA̒lق̕ϐɑ≉ZȂǂɎgB //i`FbN̎s //newōCX^Xugāv\bhtB[hupv@ //CX^XĂϐsuzukipă\bhcheckPrices //uCX^Xϐ.\bh()vƂB //CX^X̕ϐƂĎ󂯓n //checkPrice\bhShopKeeperNXĂяoB //NX̑ɃNX琶CX^XĂϐsuzukiĂяoB suzuki.checkPrice(car1,patrolCar1,train1); //f̎s suzuki.doDemo(car1,patrolCar1,train1); } }
true
441713088aded82ce66aea6a72982263a2c99fd5
Java
jiandun/MyLeetCode
/src/com/algorithms/array/LargestRectangleInHistogram.java
UTF-8
141
2.03125
2
[]
no_license
package com.algorithms.array; public class LargestRectangleInHistogram { public int largestRectangleArea(int[] heights) { return 0; } }
true
5a5b8fec6e1271bddf90ef80875fc1d663bf629e
Java
litangtang/hhyz
/src/com/hhyzoa/model/Trade.java
UTF-8
5,251
2.609375
3
[]
no_license
package com.hhyzoa.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Transient; /** * 原料往来 * @author lizhibin * */ @Entity(name="Trade") public class Trade { private Integer id ; //主键 private Date date ; //日期 private String abst ; //摘要 private Integer packages ; //件数 private Double amount ; //数量 private Double price ; //单价 private Double carriage ; //送货金额 private Double payment ; //付款金额 //欠别人即为贷,别人欠自己则为借 //对于原料往来,送货金额-付款金额,余额为正则为2贷,为负则为1即借 //对于销售往来,贷款金额-收款金额,余额为正则为1即借,为负则为2即贷 private Integer isLoan ; //借贷标志 1为借 2为贷0为平 private String isLoanStr ; //借贷标志字符串 private Double balance ; //余额 private String verify ; //核对情况 private String remark ; //备注 private Integer flag ; //1为原料往来 2为销售往来 与client.type一一对应 private Integer level ; //每增加一笔来往,level+1,针对某个客户,从1开始 private Client client; //客户 /********************************************************* * 累计功能计算方法 * 不存库,遍历查询结果动态计算并赋值 * * ******************************************************* */ private Integer packageAccu ; //件数累计 private Double amountAccu; //数量累计 private Double balanceAccu ; //余额累计 private String packageAccuStr; //件数累计,取消科学计数法展示 private String amountAccuStr; //数量累计,取消科学计数法展示 private String balanceAccuStr ; //余额累计,取消科学计数法展示 @ManyToOne //@JoinColumn(name="CLIENT_ID") public Client getClient() { return client; } public void setClient(Client client) { this.client = client; } @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Column public Integer getPackages() { return packages; } public void setPackages(Integer packages) { this.packages = packages; } @Column public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } @Column public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } @Column public Double getCarriage() { return carriage; } public void setCarriage(Double carriage) { this.carriage = carriage; } @Column public Double getPayment() { return payment; } public void setPayment(Double payment) { this.payment = payment; } @Column(name="IS_LOAN") public Integer getIsLoan() { return isLoan; } public void setIsLoan(Integer isLoan) { this.isLoan = isLoan; } @Column public Double getBalance() { return balance; } public void setBalance(Double balance) { this.balance = balance; } @Column public String getVerify() { return verify; } public void setVerify(String verify) { this.verify = verify; } @Column public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } @Column public String getAbst() { return abst; } public void setAbst(String abst) { this.abst = abst; } @Column public Integer getFlag() { return flag; } public void setFlag(Integer flag) { this.flag = flag; } public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } @Transient public String getIsLoanStr() { return isLoanStr; } public void setIsLoanStr(String isLoanStr) { this.isLoanStr = isLoanStr; } @Transient public Integer getPackageAccu() { return packageAccu; } public void setPackageAccu(Integer packageAccu) { this.packageAccu = packageAccu; } @Transient public Double getAmountAccu() { return amountAccu; } public void setAmountAccu(Double amountAccu) { this.amountAccu = amountAccu; } @Transient public Double getBalanceAccu() { return balanceAccu; } public void setBalanceAccu(Double balanceAccu) { this.balanceAccu = balanceAccu; } @Transient public String getPackageAccuStr() { return packageAccuStr; } public void setPackageAccuStr(String packageAccuStr) { this.packageAccuStr = packageAccuStr; } @Transient public String getAmountAccuStr() { return amountAccuStr; } public void setAmountAccuStr(String amountAccuStr) { this.amountAccuStr = amountAccuStr; } @Transient public String getBalanceAccuStr() { return balanceAccuStr; } public void setBalanceAccuStr(String balanceAccuStr) { this.balanceAccuStr = balanceAccuStr; } }
true
e333774596c5fed007d470e9933ac3fbb0532d9e
Java
nhungnguyen123/ThucTapAndroid
/ThucTap/app/src/main/java/com/uiapp/thuctap/mvp/main/garden/gardenclient/presenter/GardenClientPresenter.java
UTF-8
1,671
1.914063
2
[]
no_license
package com.uiapp.thuctap.mvp.main.garden.gardenclient.presenter; import com.uiapp.thuctap.base.presenter.BasePresenter; import com.uiapp.thuctap.interactor.api.ApiManager; import com.uiapp.thuctap.interactor.api.network.ApiCallback; import com.uiapp.thuctap.interactor.api.network.RestError; import com.uiapp.thuctap.interactor.api.response.garden.AllGardenResponse; import com.uiapp.thuctap.interactor.prefer.PreferManager; import com.uiapp.thuctap.model.Garden; import com.uiapp.thuctap.mvp.main.garden.gardenclient.view.IGardenClientView; import com.uiapp.thuctap.utils.LogUtils; import java.util.ArrayList; import java.util.List; /** * Created by hongnhung on 7/31/16. */ public class GardenClientPresenter extends BasePresenter<IGardenClientView> implements IGardenClientPresenter { public List<Garden> listGarden = new ArrayList<>(); public List<Garden> mLisetAllGardenUser = new ArrayList<>(); public GardenClientPresenter(ApiManager apiManager, PreferManager preferManager) { super(apiManager, preferManager); } @Override public void getAllGardenClient(String userId) { getApiManager().getAllGardenClient(userId, new ApiCallback<AllGardenResponse>() { @Override public void success(AllGardenResponse res) { listGarden.clear(); listGarden.addAll(res.getList()); LogUtils.logE("size",res.getList().size()+""); getView().getAllGardenSuccess(); } @Override public void failure(RestError error) { getView().getAllGardenError(error.message); } }); } }
true
ca0c6e196cf97fd69913bbfb3494cad5a2db8994
Java
amarnath29993/Product-ManagementApp
/src/main/java/com/product/jpa/CountryJpa1.java
UTF-8
210
1.617188
2
[]
no_license
package com.product.jpa; import org.springframework.data.jpa.repository.JpaRepository; import com.product.model.Country1; public interface CountryJpa1 extends JpaRepository<Country1, Integer>{ }
true
edf220c78a046d6afc1e986e5e0f418a29e6cd4d
Java
k0pernicus/TP_Licence_Master_Info
/Master/S2/CAR_TP1/test/FTPServer/User/UserTest.java
UTF-8
691
2.734375
3
[]
no_license
package FTPServer.User; import static org.junit.Assert.*; import org.junit.Test; public class UserTest { @Test public void test() { User user1 = new User("Grutier", "magruemalife"); //Nom correspondant assertTrue("Grutier".equals(user1.getUsername())); //Mot de passe correspondant assertTrue("magruemalife".equals(user1.getPasswd())); //Format du toString() correspondant assertTrue("User: Grutier".equals(user1.toString())); //Méthode de vérification de l'égalité entre deux User correspondant User user2 = new User("Grutier", "magruemalife"); assertTrue(user1.equals(user2)); } }
true
ce90ce98be6023bcdea5d3eb391ff27fb34d53b4
Java
SteveJonNunez/FPVDrone
/sharedclasses/src/main/java/com/golshadi/orientationSensor/utils/AppConstants.java
UTF-8
218
1.632813
2
[ "Apache-2.0" ]
permissive
package com.golshadi.orientationSensor.utils; public class AppConstants { public final static String AZIMTUH = "azimuth"; public final static String PITCH = "pitch"; public final static String ROLL = "roll"; }
true
518e3b51e8e1e89c41739a80d85574da3580c34d
Java
nmorel/GenerateGwtRfProxy
/plugin/src/com/github/generategwtrfproxy/wizards/GenProxyWizardPage.java
UTF-8
17,234
1.71875
2
[]
no_license
package com.github.generategwtrfproxy.wizards; import com.github.generategwtrfproxy.beans.Method; import com.github.generategwtrfproxy.visitors.MethodVisitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.ui.dialogs.FilteredTypesSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.viewers.CheckStateChangedEvent; import org.eclipse.jface.viewers.CheckboxTableViewer; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ICheckStateListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; import java.util.ArrayList; import java.util.List; public class GenProxyWizardPage extends NewTypeWizardPage { private class MethodProvider implements IStructuredContentProvider { @Override public void dispose() { } @Override public Object[] getElements(Object inputElement) { return new Object[] {inputElement}; } @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } } private static final String PAGE_NAME = "GenProxyWizardPage"; private IType proxyFor; private Text proxyForText; private IStatus fLocatorStatus = new StatusInfo(); private IType locator; private Text locatorText; private IStatus fProxyForStatus = new StatusInfo(); private Button annotProxyFor; private Button annotProxyForName; private Button entityProxy; private Button valueProxy; private CheckboxTableViewer methodsTable; protected GenProxyWizardPage() { super(false, PAGE_NAME); setTitle("Generate Proxy"); setDescription("Generate an EntityProxy/ValueProxy for the selected class"); } public void createControl(Composite parent) { initializeDialogUnits(parent); Composite container = new Composite(parent, SWT.NULL); container.setFont(parent.getFont()); int nbColumns = 4; GridLayout layout = new GridLayout(); layout.numColumns = nbColumns; layout.verticalSpacing = 5; container.setLayout(layout); createProxyForControls(container, nbColumns); createSeparator(container, nbColumns); createContainerControls(container, nbColumns); createPackageControls(container, nbColumns); createTypeNameControls(container, nbColumns); createSeparator(container, nbColumns); createAnnotationTypeControls(container, nbColumns); createLocatorControls(container, nbColumns); createProxyTypeControls(container, nbColumns); createGettersSettersSelectionControls(container, nbColumns); setControl(container); setFocus(); setDefaultValues(); Dialog.applyDialogFont(container); } public String getLocator() { return locatorText.getText(); } public IType getProxyFor() { return proxyFor; } public List<Method> getSelectedMethods() { if (null != methodsTable) { List<Method> methods = new ArrayList<Method>(); for (Object obj : methodsTable.getCheckedElements()) { methods.add((Method) obj); } return methods; } return null; } public boolean isAnnotProxyFor() { return annotProxyFor.getSelection(); } public boolean isEntityProxy() { return entityProxy.getSelection(); } public void setLocator(IType locator) { this.locator = locator; } public void setProxyFor(IType proxyFor) { this.proxyFor = proxyFor; } @Override protected void handleFieldChanged(String fieldName) { doStatusUpdate(); super.handleFieldChanged(fieldName); } private IType chooseLocatorFor() { FilteredTypesSelectionDialog dialog = new FilteredTypesSelectionDialog( getShell(), false, getWizard().getContainer(), SearchEngine.createWorkspaceScope(), IJavaSearchConstants.CLASS); dialog.setTitle("Locator selection"); dialog.setMessage("Select the locator"); if (dialog.open() == Window.OK) { return (IType) dialog.getFirstResult(); } return null; } private IType chooseProxyFor() { FilteredTypesSelectionDialog dialog = new FilteredTypesSelectionDialog( getShell(), false, getWizard().getContainer(), SearchEngine.createWorkspaceScope(), IJavaSearchConstants.CLASS); dialog.setTitle("ProxyFor selection"); dialog.setMessage("Select the class to proxy"); if (dialog.open() == Window.OK) { return (IType) dialog.getFirstResult(); } return null; } private void createAnnotationTypeControls(Composite container, int nbColumns) { Label label = new Label(container, SWT.NULL); label.setText("Annotation type:"); GridData gd = new GridData(GridData.FILL); gd.horizontalSpan = nbColumns - 1; GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.verticalSpacing = 5; Composite checks = new Composite(container, SWT.NULL); checks.setLayoutData(gd); checks.setLayout(layout); annotProxyFor = new Button(checks, SWT.RADIO); annotProxyFor.setText("ProxyFor"); annotProxyForName = new Button(checks, SWT.RADIO); annotProxyForName.setText("ProxyForName"); } private void createGettersSettersSelectionControls(Composite container, int nbColumns) { Label label = new Label(container, SWT.NULL); label.setText("Methods:"); label.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); methodsTable = CheckboxTableViewer.newCheckList(container, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); methodsTable.setLabelProvider(new LabelProvider()); methodsTable.setContentProvider(new MethodProvider()); methodsTable.setSelection(new StructuredSelection(), true); Table table = methodsTable.getTable(); GridData gd = new GridData(); gd.horizontalAlignment = GridData.FILL; gd.horizontalSpan = nbColumns - 2; gd.heightHint = 300; table.setLayoutData(gd); TableLayout layout = new TableLayout(); layout.addColumnData(new ColumnWeightData(100, false)); table.setLayout(layout); table.setHeaderVisible(false); TableColumn columnName = new TableColumn(table, SWT.LEFT); columnName.setText("Name"); Composite buttons = new Composite(container, SWT.NONE); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 1; buttons.setLayout(gridLayout); buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); Button selectAllMethods = new Button(buttons, SWT.PUSH); selectAllMethods.setText("Select All"); selectAllMethods.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); selectAllMethods.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent e) { methodsTable.setAllChecked(true); } @Override public void widgetSelected(SelectionEvent e) { methodsTable.setAllChecked(true); } }); Button deselectAllMethods = new Button(buttons, SWT.PUSH); deselectAllMethods.setText("Deselect All"); deselectAllMethods.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); deselectAllMethods.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent e) { methodsTable.setAllChecked(false); onMethodsChange(); } @Override public void widgetSelected(SelectionEvent e) { methodsTable.setAllChecked(false); onMethodsChange(); } }); Button selectGetters = new Button(buttons, SWT.PUSH); selectGetters.setText("Select Getters"); selectGetters.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); selectGetters.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent e) { selectGetterOrSetter(true); onMethodsChange(); } @Override public void widgetSelected(SelectionEvent e) { selectGetterOrSetter(true); onMethodsChange(); } }); Button selectSetters = new Button(buttons, SWT.PUSH); selectSetters.setText("Select Setters"); selectSetters.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); selectSetters.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent e) { selectGetterOrSetter(false); onMethodsChange(); } @Override public void widgetSelected(SelectionEvent e) { selectGetterOrSetter(false); onMethodsChange(); } }); methodsTable.addCheckStateListener(new ICheckStateListener() { @Override public void checkStateChanged(CheckStateChangedEvent event) { onMethodsChange(); } }); } private void createLocatorControls(Composite container, int nbColumns) { Label label = new Label(container, SWT.NULL); label.setText("Locator:"); GridData gd = new GridData(); gd.horizontalAlignment = GridData.FILL; gd.horizontalSpan = nbColumns - 2; locatorText = new Text(container, SWT.BORDER | SWT.SINGLE); locatorText.setLayoutData(gd); locatorText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { fLocatorStatus = locatorChanged(); doStatusUpdate(); } }); Button browse = new Button(container, SWT.PUSH); browse.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browse.setText("Browse..."); browse.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent e) { locator = chooseLocatorFor(); if (null != locator) { locatorText.setText(locator.getFullyQualifiedName('.')); } } @Override public void widgetSelected(SelectionEvent e) { locator = chooseLocatorFor(); if (null != locator) { locatorText.setText(locator.getFullyQualifiedName('.')); } } }); fLocatorStatus = locatorChanged(); doStatusUpdate(); } private void createProxyForControls(Composite container, int nbColumns) { Label label = new Label(container, SWT.NULL); label.setText("Proxy for:"); GridData gd = new GridData(); gd.horizontalAlignment = GridData.FILL; gd.horizontalSpan = nbColumns - 2; proxyForText = new Text(container, SWT.BORDER | SWT.SINGLE); proxyForText.setLayoutData(gd); proxyForText.setEditable(false); proxyForText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { fProxyForStatus = proxyForChanged(); doStatusUpdate(); } }); Button browse = new Button(container, SWT.PUSH); browse.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); browse.setText("Browse..."); browse.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent e) { proxyFor = chooseProxyFor(); if (null != proxyFor) { proxyForText.setText(proxyFor.getFullyQualifiedName('.')); } } @Override public void widgetSelected(SelectionEvent e) { proxyFor = chooseProxyFor(); if (null != proxyFor) { proxyForText.setText(proxyFor.getFullyQualifiedName('.')); } } }); fProxyForStatus = proxyForChanged(); doStatusUpdate(); } private void createProxyTypeControls(Composite container, int nbColumns) { Label label = new Label(container, SWT.NULL); label.setText("Proxy type:"); GridData gd = new GridData(GridData.FILL); gd.horizontalSpan = nbColumns - 1; GridLayout layout = new GridLayout(); layout.numColumns = 2; layout.verticalSpacing = 5; Composite checks = new Composite(container, SWT.NULL); checks.setLayoutData(gd); checks.setLayout(layout); entityProxy = new Button(checks, SWT.RADIO); entityProxy.setText("EntityProxy"); valueProxy = new Button(checks, SWT.RADIO); valueProxy.setText("ValueProxy"); } // ------ validation -------- private void doStatusUpdate() { // status of all used components IStatus[] status = new IStatus[] { fProxyForStatus, fLocatorStatus, fContainerStatus, fPackageStatus, fTypeNameStatus}; // the mode severe status will be displayed and the OK button // enabled/disabled. updateStatus(status); } private IStatus locatorChanged() { StatusInfo status = new StatusInfo(); if (locatorText.getText().isEmpty()) { return status; } if (null == locator) { status.setWarning("Cannot test if the locator is correct"); return status; } if (locator.getFullyQualifiedName().equals(locatorText.getText())) { // selection from dialogBox try { ITypeHierarchy hierarchy = locator.newSupertypeHierarchy(new NullProgressMonitor()); IType[] superclasses = hierarchy.getAllClasses(); for (IType superclass : superclasses) { if (superclass.getFullyQualifiedName('.').equals( "com.google.web.bindery.requestfactory.shared.Locator")) { return status; } } } catch (JavaModelException e) { e.printStackTrace(); } status.setError("The selected locator does not extend the class Locator"); return status; } // locator directly written inside the text input locator = null; status.setWarning("Cannot test if the locator is correct"); return status; } private void onMethodsChange() { getWizard().getContainer().updateButtons(); } private CompilationUnit parse(ICompilationUnit unit) { ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setSource(unit); parser.setResolveBindings(true); return (CompilationUnit) parser.createAST(null); // parse } private IStatus proxyForChanged() { StatusInfo status = new StatusInfo(); if (null == proxyFor) { status.setError("You must select a class to proxy"); return status; } if (null == getPackageFragmentRoot()) { initContainerPage(proxyFor); } if (null == getPackageFragment() || getPackageFragment().isDefaultPackage()) { initTypePage(proxyFor); } if (getTypeName().isEmpty()) { setTypeName(proxyFor.getElementName() + "Proxy", true); } if (null != methodsTable) { // removing the previous methods Object[] elements = new Object[methodsTable.getTable().getItemCount()]; for (int i = 0; i < methodsTable.getTable().getItemCount(); i++) { elements[i] = methodsTable.getElementAt(i); } methodsTable.remove(elements); // parse the new proxyFor to find the getter/setter and add them to the // table CompilationUnit parse = parse(proxyFor.getCompilationUnit()); MethodVisitor visitor = new MethodVisitor(); parse.accept(visitor); for (Method method : visitor.getMethods()) { methodsTable.add(method); } methodsTable.setAllChecked(true); } return status; } private void selectGetterOrSetter(boolean getters) { for (int i = 0; i < methodsTable.getTable().getItemCount(); i++) { Method method = (Method) methodsTable.getElementAt(i); if (method.isGetter()) { methodsTable.setChecked(method, getters); } else { methodsTable.setChecked(method, !getters); } } } private void setDefaultValues() { annotProxyFor.setSelection(true); entityProxy.setSelection(true); if (null != proxyFor) { proxyForText.setText(proxyFor.getFullyQualifiedName('.')); } if (null != locator) { locatorText.setText(locator.getFullyQualifiedName('.')); } fProxyForStatus = proxyForChanged(); fLocatorStatus = locatorChanged(); doStatusUpdate(); } }
true
2ff7c0acea62451ebbf13d88b0132ebd8b965930
Java
yusufnazir/framework_parent
/framework.core.vaadinflow/src/main/java/software/simple/solutions/framework/core/web/view/PersonInformationView.java
UTF-8
3,694
2.125
2
[]
no_license
package software.simple.solutions.framework.core.web.view; import com.vaadin.flow.component.icon.Icon; import com.vaadin.flow.router.Route; import software.simple.solutions.framework.core.components.filter.CStringIntervalLayout; import software.simple.solutions.framework.core.constants.ReferenceKey; import software.simple.solutions.framework.core.entities.Person; import software.simple.solutions.framework.core.entities.PersonInformation; import software.simple.solutions.framework.core.properties.PersonInformationProperty; import software.simple.solutions.framework.core.service.facade.PersonInformationServiceFacade; import software.simple.solutions.framework.core.valueobjects.PersonInformationVO; import software.simple.solutions.framework.core.web.BasicTemplate; import software.simple.solutions.framework.core.web.FilterView; import software.simple.solutions.framework.core.web.flow.MainView; import software.simple.solutions.framework.core.web.routing.Routes; import software.simple.solutions.framework.core.web.view.forms.PersonInformationForm; @Route(value = Routes.PERSON_INFORMATION, layout = MainView.class) public class PersonInformationView extends BasicTemplate<PersonInformation> { private static final long serialVersionUID = 6503015064562511801L; public PersonInformationView() { setEntityClass(PersonInformation.class); setServiceClass(PersonInformationServiceFacade.class); setFilterClass(Filter.class); setFormClass(PersonInformationForm.class); setParentReferenceKey(ReferenceKey.PERSON_INFORMATION); setEditRoute(Routes.PERSON_INFORMATION_EDIT); } @Override public void setUpCustomColumns() { addContainerProperty(PersonInformation::getPerson, PersonInformationProperty.PERSON); addContainerProperty(PersonInformation::getPrimaryEmail, PersonInformationProperty.PRIMARY_EMAIL); addContainerProperty(PersonInformation::getPrimaryContactNumber, PersonInformationProperty.PRIMARY_CONTACT_NUMBER); } /** * Filter implementation * * @author yusuf * */ public class Filter extends FilterView { private static final long serialVersionUID = 117780868467918033L; private CStringIntervalLayout firstNameFld; private CStringIntervalLayout lastNameFld; private CStringIntervalLayout emailFld; private CStringIntervalLayout contactNumberFld; @Override public void executeBuild() { firstNameFld = addField(CStringIntervalLayout.class, PersonInformationProperty.PERSON_FIRST_NAME, 0, 0); lastNameFld = addField(CStringIntervalLayout.class, PersonInformationProperty.PERSON_LAST_NAME, 0, 1); emailFld = addField(CStringIntervalLayout.class, PersonInformationProperty.EMAIL, 1, 0); contactNumberFld = addField(CStringIntervalLayout.class, PersonInformationProperty.CONTACT_NUMBER, 1, 1); Person person = getIfParentEntity(Person.class); if (person != null) { firstNameFld.setValue(person.getFirstName()); firstNameFld.setReadOnly(true); lastNameFld.setValue(person.getLastName()); lastNameFld.setReadOnly(true); } } @Override public Object getCriteria() { PersonInformationVO vo = new PersonInformationVO(); vo.setPersonFirstNameInterval(firstNameFld.getValue()); vo.setPersonLastNameInterval(lastNameFld.getValue()); vo.setEmailInterval(emailFld.getValue()); vo.setContactNumberInterval(contactNumberFld.getValue()); Person person = getIfParentEntity(Person.class); if (person != null) { vo.setPersonId(person.getId()); } return vo; } } @Override public Icon getIcon() { // TODO Auto-generated method stub return null; } }
true
4f557953d7bfa8f309a0dcfe24b94fd70a6526b6
Java
Bhargavbala/EmployeePojo
/src/main/java/com/api/employee/EmployeeDetails/EmployeeController.java
UTF-8
1,009
2.46875
2
[]
no_license
package com.api.employee.EmployeeDetails; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class EmployeeController { @Autowired private EmployeeService employeeService; @GetMapping("/employees") public List<Employee> getEmployees(){ return this.employeeService.getAllEmployees(); } @GetMapping("/employees/{id}") public Employee getEmployee(@PathVariable("id") int id){ return EmployeeService.getEmployeeById(id); } @PostMapping("/employees") public Employee addEmployee(@RequestBody Employee employee){ Employee employee0 = this.employeeService.addEmployee(employee); return employee0; } @PutMapping("/employees/{id}") public Employee updateEmployee(@RequestBody Employee employee, @PathVariable("id") int id) { this.employeeService.updateEmpoloyee(employee, id); return employee; } }
true
1b2363a42985e2ab8faadd9ef0fe024354838b5b
Java
e-xxkun/Code_P
/Java/IDEA/ch-02/src/test/java/com/orange/MyTest.java
UTF-8
660
2.234375
2
[]
no_license
package com.orange; import com.orange.service.SomeService; import com.orange.service.impl.SomeServiceImpl; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { @Test public void test01(){ SomeService service = new SomeServiceImpl(); service.doSome(); } @Test public void test02(){ String config = "beans.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(config); SomeService service1 = (SomeService) ac.getBean("service1"); service1.doSome(); } }
true
77c5a4167fba69e49092f041c15347de0c3657cf
Java
jalerson/backhoe
/src/br/ufrn/ppgsc/backhoe/miner/CodeContributionMiner.java
UTF-8
11,925
1.820313
2
[]
no_license
package br.ufrn.ppgsc.backhoe.miner; import java.sql.Date; import java.util.ArrayList; import java.util.List; import br.ufrn.ppgsc.backhoe.exceptions.MissingParameterException; import br.ufrn.ppgsc.backhoe.persistence.model.ChangedPath; import br.ufrn.ppgsc.backhoe.persistence.model.Commit; import br.ufrn.ppgsc.backhoe.persistence.model.Metric; import br.ufrn.ppgsc.backhoe.persistence.model.MetricType; import br.ufrn.ppgsc.backhoe.repository.code.CodeRepository; import br.ufrn.ppgsc.backhoe.repository.task.TaskRepository; import br.ufrn.ppgsc.backhoe.util.CodeRepositoryUtil; import br.ufrn.ppgsc.backhoe.vo.ConfigurationMining; import br.ufrn.ppgsc.backhoe.vo.wrapper.ClassWrapper; import br.ufrn.ppgsc.backhoe.vo.wrapper.MethodWrapper; import difflib.Delta; import difflib.DiffUtils; import difflib.Patch; public class CodeContributionMiner extends AbstractMiner { private final String minerSlug = "codeContributionMiner"; private MetricType addedLOCMetricType; private MetricType changedLOCMetricType; private MetricType deletedLOCMetricType; private MetricType addedMethodsMetricType; private MetricType changedMethodsMetricType; private List<Commit> specificCommitsToMining; public CodeContributionMiner(Integer system, CodeRepository codeRepository, TaskRepository taskRepository, Date startDate, Date endDate, List<String> developers, List<String> ignoredPaths) { super(system, codeRepository, taskRepository, startDate, endDate, developers, ignoredPaths); } @Override public boolean setupMinerSpecific() throws MissingParameterException { System.out.println("========================================================="); System.out.println("CODE CONTRIBUTION MINING: "+ConfigurationMining.getSystemName(system).toUpperCase()+ " TEAM"); System.out.println("---------------------------------------------------------"); this.addedLOCMetricType = metricTypeDao.findBySlug("loc:added"); if(this.addedLOCMetricType == null) { this.addedLOCMetricType = new MetricType("Added LOC", "loc:added"); metricTypeDao.save(this.addedLOCMetricType); } this.changedLOCMetricType = metricTypeDao.findBySlug("loc:changed"); if(this.changedLOCMetricType == null) { this.changedLOCMetricType = new MetricType("Changed LOC", "loc:changed"); metricTypeDao.save(this.changedLOCMetricType); } this.deletedLOCMetricType = metricTypeDao.findBySlug("loc:deleted"); if(this.deletedLOCMetricType == null) { this.deletedLOCMetricType = new MetricType("Deleted LOC", "loc:deleted"); metricTypeDao.save(this.deletedLOCMetricType); } this.addedMethodsMetricType = metricTypeDao.findBySlug("methods:added"); if(this.addedMethodsMetricType == null) { this.addedMethodsMetricType = new MetricType("Added Methods", "methods:added"); metricTypeDao.save(this.addedMethodsMetricType); } this.changedMethodsMetricType = metricTypeDao.findBySlug("methods:changed"); if(this.changedMethodsMetricType == null) { this.changedMethodsMetricType = new MetricType("Changed Methods", "methods:changed"); metricTypeDao.save(this.changedMethodsMetricType); } return codeRepository.connect(); } @Override public void execute() { List<Commit> commits = null; System.out.println("\n---------------------------------------------------------"); System.out.println("BACKHOE - CALCULATE CODE CONTRIBUTION METRICS"); System.out.println("---------------------------------------------------------"); if(specificCommitsToMining != null){ commits = specificCommitsToMining; }else{ if(developers == null) { commits = codeRepository.findCommitsByTimeRange(startDate, endDate, true, ignoredPaths); } else { commits = codeRepository.findCommitsByTimeRangeAndDevelopers(startDate, endDate, developers, true, ignoredPaths); } } calculateCodeContributionMetricsToCommits(commits); System.out.println("\n---------------------------------------------------------"); System.out.println("THE CODE CONTRIBUTION METRICS WERE CALCULATED!"); System.out.println("========================================================="); } private void calculateCodeContributionMetricsToCommits(List<Commit> commits){ int processedCommits = 0; if(!commits.isEmpty()) System.out.println("\n>> BACKHOE IS CALCULATING METRICS TO FOUNDED COMMITS ... "); else System.out.println("\n>> NO COMMIT WAS FOUNDED!"); for (Commit commit : commits) { System.out.println("\n---------------------------------------------------------"); System.out.println("REVISION #"+((commit.getRevision().length() <= 7)? commit.getRevision(): commit.getRevision().subSequence(0, 7))+ " - [" + ++processedCommits + "]/[" + commits.size() + "]"); List<ChangedPath> changedPaths = changedPathDao.getChangedPathByCommitRevision(commit.getRevision()); for (ChangedPath changedPath : changedPaths) { if(changedPath.getChangeType().equals('D')) continue; if(!(changedPath.getPath().toLowerCase().contains(".java"))) continue; // Verifica se ja foram executados metricas de contribuicao para o changedpath informado if(metricDao.existsMetric(changedPath.getId(), this.minerSlug)) continue; System.out.println(">>> Path: "+changedPath.getPath()); String currentContent = changedPath.getContent(); if(changedPath.getChangeType().equals('A')){ ClassWrapper newClass = new ClassWrapper(currentContent); List<String> lines = CodeRepositoryUtil.getContentByLines(currentContent); Integer added = 0; for (String line : lines) { if(CodeRepositoryUtil.isComment(line)) continue; added++; } Integer addedMethods = newClass.getMethods().size(); Metric addedLocMetric = new Metric(); addedLocMetric.setObjectId(changedPath.getId()); addedLocMetric.setObjectType("ChangedPath"); addedLocMetric.setValue(added.floatValue()); addedLocMetric.setType(addedLOCMetricType); addedLocMetric.setMinerSlug(this.minerSlug); metricDao.save(addedLocMetric); Metric addedMethodsMetric = new Metric(); addedMethodsMetric.setObjectId(changedPath.getId()); addedMethodsMetric.setObjectType("ChangedPath"); addedMethodsMetric.setValue(addedMethods.floatValue()); addedMethodsMetric.setType(addedMethodsMetricType); addedMethodsMetric.setMinerSlug(this.minerSlug); metricDao.save(addedMethodsMetric); } else{ System.out.print(">>> It's looking for path revisions ... "); List<String> fileRevisions = codeRepository.getFileRevisions(changedPath.getPath(), null, changedPath.getCommit().getRevision()); System.out.println("Done! "+fileRevisions.size()+" revisions were founded!"); String previousRevision = CodeRepositoryUtil.getPreviousRevision(changedPath.getCommit().getRevision(), fileRevisions); String previousContent = null; previousContent = codeRepository.getFileContent(changedPath.getPath(), previousRevision); if(currentContent == null || previousContent == null) continue; calculateLOCMetrics(changedPath, previousContent, currentContent); calculateMethodMetrics(changedPath, previousContent, currentContent); } } System.out.println("---------------------------------------------------------"); } } private void calculateMethodMetrics(ChangedPath changedPath, String previousContent, String currentContent) { ClassWrapper previousClass = new ClassWrapper(previousContent); ClassWrapper currentClass = new ClassWrapper(currentContent); Integer addedMethods = 0; Integer changedMethods = 0; ArrayList<MethodWrapper> previousMethods = (ArrayList<MethodWrapper>) previousClass.getMethods(); ArrayList<MethodWrapper> currentMethods = (ArrayList<MethodWrapper>) currentClass.getMethods(); for (MethodWrapper currentMethod : currentMethods) { if(!previousMethods.contains(currentMethod)) { addedMethods++; } } Metric addedMethodsMetric = new Metric(); addedMethodsMetric.setObjectId(changedPath.getId()); addedMethodsMetric.setObjectType("ChangedPath"); addedMethodsMetric.setValue(addedMethods.floatValue()); addedMethodsMetric.setType(addedMethodsMetricType); addedMethodsMetric.setMinerSlug(this.minerSlug); metricDao.save(addedMethodsMetric); for(MethodWrapper currentMethod : currentMethods) { MethodWrapper correspondingPreviousMethod = null; for(MethodWrapper previousMethod : previousMethods) { if(previousMethod.equals(currentMethod)) { correspondingPreviousMethod = previousMethod; break; } } if(correspondingPreviousMethod == null) { continue; } List<String> previousMethodBody = CodeRepositoryUtil.getContentByLines(correspondingPreviousMethod.toString()); List<String> currentMethodBody = CodeRepositoryUtil.getContentByLines(currentMethod.toString()); Patch<String> patch = DiffUtils.diff(previousMethodBody, currentMethodBody); List<Delta<String>> deltas = patch.getDeltas(); if(deltas.size() > 0) { changedMethods++; } } Metric changedMethodsMetric = new Metric(); changedMethodsMetric.setObjectId(changedPath.getId()); changedMethodsMetric.setObjectType("ChangedPath"); changedMethodsMetric.setValue(changedMethods.floatValue()); changedMethodsMetric.setType(changedMethodsMetricType); changedMethodsMetric.setMinerSlug(this.minerSlug); metricDao.save(changedMethodsMetric); } private void calculateLOCMetrics(ChangedPath changedPath, String previousContent, String currentContent) { Integer added = 0; Integer deleted = 0; Integer changed = 0; Patch<String> patch = DiffUtils.diff(CodeRepositoryUtil.getContentByLines(previousContent), CodeRepositoryUtil.getContentByLines(currentContent)); List<Delta<String>> deltas = patch.getDeltas(); for (Delta<String> delta : deltas) { switch(delta.getType()) { case DELETE: List<String> deletedLines = (List<String>) delta.getOriginal().getLines(); for (String line : deletedLines) { if(CodeRepositoryUtil.isComment(line)) { continue; } deleted++; } break; case CHANGE: List<String> changedLines = (List<String>) delta.getRevised().getLines(); for (String line : changedLines) { if(CodeRepositoryUtil.isComment(line)) { continue; } changed++; } break; case INSERT: List<String> addedLines = (List<String>) delta.getRevised().getLines(); for (String line : addedLines) { if(CodeRepositoryUtil.isComment(line)) { continue; } added++; } break; } } Metric addedLocMetric = new Metric(); addedLocMetric.setObjectId(changedPath.getId()); addedLocMetric.setObjectType("ChangedPath"); addedLocMetric.setValue(added.floatValue()); addedLocMetric.setType(addedLOCMetricType); addedLocMetric.setMinerSlug(this.minerSlug); metricDao.save(addedLocMetric); Metric changedLocMetric = new Metric(); changedLocMetric.setObjectId(changedPath.getId()); changedLocMetric.setObjectType("ChangedPath"); changedLocMetric.setValue(changed.floatValue()); changedLocMetric.setType(changedLOCMetricType); changedLocMetric.setMinerSlug(this.minerSlug); metricDao.save(changedLocMetric); Metric deletedLocMetric = new Metric(); deletedLocMetric.setObjectId(changedPath.getId()); deletedLocMetric.setObjectType("ChangedPath"); deletedLocMetric.setValue(deleted.floatValue()); deletedLocMetric.setType(deletedLOCMetricType); deletedLocMetric.setMinerSlug(this.minerSlug); metricDao.save(deletedLocMetric); } public List<Commit> getSpecificCommitsToMining() { return specificCommitsToMining; } public void setSpecificCommitsToMining(List<Commit> specificCommitsToMining) { this.specificCommitsToMining = specificCommitsToMining; } }
true
d8de227b5a5fc882977fa795c99aa96fdc35004a
Java
Zouhairhajji/Financial_Opportunities_Detection
/5_web_app/src/main/java/fr/template/services/UserService.java
UTF-8
5,307
2.0625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package fr.template.services; import fr.template.libraries.HashGeneratorInterface; import fr.template.libraries.IdenticonGenerator; import fr.template.libraries.MessageDigestHashGenerator; import fr.template.models.authentification.Role; import fr.template.models.authentification.User; import fr.template.repositories.RoleRepository; import fr.template.repositories.UserRepository; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.sql.Timestamp; import java.text.MessageFormat; import java.util.List; import java.util.Optional; import java.util.function.Function; import javax.imageio.ImageIO; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCrypt; import org.springframework.stereotype.Service; /** * * @author fqlh0717 */ @Service public class UserService implements UserDetailsService { @Autowired private UserRepository userRepository; @Autowired private RoleRepository roleRepository; @Override @Transactional public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Optional<User> user = this.userRepository.findUserByUsername(username); if (user.isPresent()) { return user.get(); } else { throw new UsernameNotFoundException(MessageFormat.format("User:[{0}] not found", username)); } } @Transactional public void registerUser(User user) throws Exception { String genPw = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt(10)); Function<String, String> identiconGenerator = x -> { try { if (x == null || x.trim().equalsIgnoreCase("")) { throw new Exception("not data found, default identicon ganna be assigned"); } HashGeneratorInterface hashGenerator = new MessageDigestHashGenerator("MD5"); BufferedImage bImage = IdenticonGenerator.generate(x, hashGenerator); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bImage, "jpg", baos); baos.flush(); byte[] imageInByteArray = baos.toByteArray(); baos.close(); return javax.xml.bind.DatatypeConverter.printBase64Binary(imageInByteArray); } catch (Exception e) { return "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAyADIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDgqK67+xdP/wCff/x9v8a5zVII7fUZYol2ouMDOewNI8+dGUFdlSitfQ7K3vPP8+Pft24+YjGc+n0q3qml2dvp0ssUO11xg7ie4HrQCoyceY52iiuu/sXT/wDn3/8AH2/xoFTpuexyNFdd/Yun/wDPv/4+3+NFBp9WmZ//AAkv/Tp/5E/+tR/Zv9sf6f53k+b/AAbd2Mcdcj0rBrotL1Szt9Oiilm2uucjaT3J9KAhPndqj0I/+Re/6ePP/wCAbdv5560f2l/bH+geT5Pm/wAe7djHPTA9Kg1y9t7zyPIk37d2flIxnHr9Kp6XPHb6jFLK21Fzk4z2IoBztLkT900/+Ea/6e//ACH/APXo/wCEl/6dP/In/wBatD+2tP8A+fj/AMcb/CuRoHUkqf8ADZvf8JL/ANOn/kT/AOtRWDRQZ+3qdwoorrtF/wCQRB/wL/0I0Cp0+d2ORore8S/8uv8AwP8ApVDRf+QvB/wL/wBBNASp2nyFCiu9rgqB1aXs7ahRRRQZBXXaL/yCIP8AgX/oRoooOjDfGZ/iX/l1/wCB/wBKoaL/AMheD/gX/oJoooCf8b7jrq4KiimViugUUUUjlP/Z"; } }; user.setPassword(genPw); user.setEnabled(false); user.setIdenticon(identiconGenerator.apply(user.getUsername())); user.setDateCreation(new Timestamp(System.currentTimeMillis())); List<Role> defaultRoles = this.roleRepository.findDefaultRoles(); if (defaultRoles == null || defaultRoles.isEmpty()) { throw new Exception("No default groupe found"); } user.setRoles(defaultRoles); this.userRepository.save(user); } @Transactional public List<Role> getAllRoles() { return this.roleRepository.findAll(); } @Transactional public Role findRole(Long idRole) { return this.roleRepository.findOne(idRole); } @Transactional public List<User> getAllUsers() { return this.userRepository.findAll(); } @Transactional public long countUsers() { return this.userRepository.count(); } @Transactional public long countRoles() { return this.roleRepository.count(); } @Transactional public Role updateRole(Role role) { return this.roleRepository.save(role); } @Transactional public Role saveRole(Role formRole) { formRole.setDateCreation(new Timestamp(System.currentTimeMillis())); return this.roleRepository.save(formRole); } @Transactional public void deleteRole(Long idRole) { this.roleRepository.delete(idRole); } @Transactional public User findUserById(Long idUser) { return this.userRepository.findOne(idUser); } @Transactional public void updateUser(User userForm) { this.userRepository.save(userForm); } @org.springframework.transaction.annotation.Transactional public void lockUser(Long idUser) { this.userRepository.setLockFor(idUser); } /** * * @param idUser */ @org.springframework.transaction.annotation.Transactional public User unlockUser(Long idUser) { this.userRepository.setUnlockFor(idUser); User user = this.userRepository.findOne(idUser); return user; } @Transactional public void deleteUser(Long idUser) { User user = this.userRepository.findOne(idUser); this.userRepository.delete(user); } }
true
972c8e19dc79ec04b84b7b8332b09489f8ea1874
Java
stevewen/ihmc-open-robotics-software
/valkyrie/src/main/java/us/ihmc/valkyrie/simulation/ValkyrieDataFileNamespaceRenamer.java
UTF-8
3,175
2.390625
2
[ "Apache-2.0" ]
permissive
package us.ihmc.valkyrie.simulation; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import us.ihmc.yoVariables.registry.NameSpaceRenamer; import us.ihmc.yoVariables.registry.YoVariableRegistry; import us.ihmc.simulationconstructionset.Robot; import us.ihmc.simulationconstructionset.SimulationConstructionSet; public class ValkyrieDataFileNamespaceRenamer { public ValkyrieDataFileNamespaceRenamer() { SimulationConstructionSet scs = new SimulationConstructionSet(new Robot("null")); YoVariableRegistry rootRegistry = scs.getRootRegistry(); NameSpaceRenamer valkyrieNameSpaceRenamer = new ValkyrieNameSpaceRenamer(); ChangeNamespacesToMatchSimButton changeNamespacesToMatchSimButton = new ChangeNamespacesToMatchSimButton("ChangeValkyrieNamespaces", rootRegistry, valkyrieNameSpaceRenamer); scs.addButton(changeNamespacesToMatchSimButton); NameSpaceRenamer stepprNameSpaceRenamer = new StepprNameSpaceRenamer(); ChangeNamespacesToMatchSimButton changeStepprNamespacesToMatchSimButton = new ChangeNamespacesToMatchSimButton("ChangeStepprNamespaces", rootRegistry, stepprNameSpaceRenamer); scs.addButton(changeStepprNamespacesToMatchSimButton); scs.startOnAThread(); } private class ChangeNamespacesToMatchSimButton extends JButton implements ActionListener { private static final long serialVersionUID = -6919907212022890245L; private final YoVariableRegistry rootRegistry; private final NameSpaceRenamer nameSpaceRenamer; public ChangeNamespacesToMatchSimButton(String name, YoVariableRegistry rootRegistry, NameSpaceRenamer nameSpaceRenamer) { super(name); this.rootRegistry = rootRegistry; this.nameSpaceRenamer = nameSpaceRenamer; this.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { rootRegistry.recursivelyChangeNameSpaces(nameSpaceRenamer); } } private class StepprNameSpaceRenamer implements NameSpaceRenamer { @Override public String changeNamespaceString(String nameSpaceString) { String newNameSpaceString = nameSpaceString.replaceAll("loggedmain", "bono.DRCSimulation"); if (newNameSpaceString.startsWith("bono.")) newNameSpaceString = "root." + newNameSpaceString; return newNameSpaceString; } } private class ValkyrieNameSpaceRenamer implements NameSpaceRenamer { @Override public String changeNamespaceString(String nameSpaceString) { String newNameSpaceString = nameSpaceString.replaceAll("loggedmain", "valkyrie.DRCSimulation"); newNameSpaceString = newNameSpaceString.replaceAll("ValkyrieRosControlSensorReader", "SensorReaderFactory.DRCPerfectSensorReader"); if (newNameSpaceString.startsWith("valkyrie.")) newNameSpaceString = "root." + newNameSpaceString; return newNameSpaceString; } } public static void main(String[] args) { new ValkyrieDataFileNamespaceRenamer(); } }
true
938e9c132c420e9b3702d8a2fafc3bcc29106cbd
Java
pengzhetech/design_patterns
/factory-method/src/main/java/com/design/factoty/method/AbstractHumanFactory.java
UTF-8
300
2.53125
3
[ "MIT" ]
permissive
package com.design.factoty.method; /** * @author pengzhe * @date 2018/10/16 19:03 */ public abstract class AbstractHumanFactory { /** * createHuman * * @param clazz * @param <T> * @return */ public abstract <T extends Human> T createHuman(Class<T> clazz); }
true
48b1cec04b484e1aa4c987d2e816fb1db1d90133
Java
AARaven/JavaForAutomation
/src/ObjectBasics/OptionalTurtle/DemoTurtleGraphics.java
UTF-8
6,407
3.703125
4
[]
no_license
package ObjectBasics.OptionalTurtle; import JavaFundamentals.Utils; import java.io.IOException; import java.util.InputMismatchException; public class DemoTurtleGraphics { private void showTitleMenu() { System.out.println( "\f\n*********************************************" + "\n* 1 - Play with turtle. *" + "\n* 2 - Exit. *" + "\n*********************************************" + "\n" ); } public static void main( String[] args ) throws Exception { DemoTurtleGraphics demo = new DemoTurtleGraphics(); Utils utils = new Utils(); TurtleGraphics turtle; while ( true ) { demo.showTitleMenu(); switch ( utils.getScan().next() ) { case ( "1" ): System.out.println( "\n'1' - to start the game with default properties. " + "\n'2' - to change the game board." ); switch ( utils.getScan().next() ) { case ( "1" ): turtle = new TurtleGraphics(); turtle.clearBoard(); break; case ( "2" ): System.out.println( "\nConfigure your board: " + "\nFor example: 20 20 . x o" ); turtle = new TurtleGraphics( utils.getScan().nextInt(), utils.getScan().nextInt(), utils.getScan().next().charAt( 0 ), utils.getScan().next().charAt( 0 ), utils.getScan().next().charAt( 0 ) ); turtle.clearBoard(); break; default: turtle = new TurtleGraphics(); turtle.clearBoard(); } while ( true ) { try { turtle.showTurtle(); turtle.showBoard(); System.out.println( "\nChoose the description of movement and the number of " + "steps: " + "\nFor example: 'r 5' - to go 5 steps to the right." + "\n'c' - to clean a board and start again." + "\n'exit' - exit from the program" + "\n" ); switch ( utils.getScan().next() ) { case ( "u" ): turtle.setDirection( Direction.UP ); turtle.getDirection().move( turtle, utils.getScan().nextInt() ); break; case ( "d" ): turtle.setDirection( Direction.DOWN ); turtle.getDirection().move( turtle, utils.getScan().nextInt() ); break; case ( "l" ): turtle.setDirection( Direction.LEFT ); turtle.getDirection().move( turtle, utils.getScan().nextInt() ); break; case ( "r" ): turtle.setDirection( Direction.RIGHT ); turtle.getDirection().move( turtle, utils.getScan().nextInt() ); break; case ( "c" ): turtle.setDirection( Direction.CLEAR ); turtle.getDirection().clearBoard( turtle ); break; case ( "exit" ): System.out.print( "\nExiting ..." + "\n" ); System.exit( 0 ); break; default: System.out.println( "\nIncorrect input ... " + "\nPlease, press 'Enter' to continue ..." + "\n" ); System.in.read(); } } catch ( IOException | InputMismatchException e ) { System.out.printf( "\nIncorrect input ... %s " + "\nPlease, press 'Enter' to continue ... " + "\n", e.getMessage() ); } } case ( "2" ): System.out.print( "\nExiting ..." + "\n" ); System.exit( 0 ); break; default: System.out.println( "\nIncorrect input ... " + "\nPlease, press 'Enter' to continue ..." + "\n" ); System.in.read(); } } } }
true
d7ac5a46c9303ffc6af850769f92db1545075f71
Java
xtaticzero/COB
/ControlObligaciones/ControlObligaciones/src/main/java/mx/gob/sat/siat/cob/seguimiento/dao/stdcob/impl/mapper/BitacoraSeguimientoMapper.java
UTF-8
798
2.125
2
[]
no_license
package mx.gob.sat.siat.cob.seguimiento.dao.stdcob.impl.mapper; import java.sql.ResultSet; import java.sql.SQLException; import mx.gob.sat.siat.cob.seguimiento.dto.stdcob.BitacoraSeguimiento; import org.springframework.jdbc.core.RowMapper; public class BitacoraSeguimientoMapper implements RowMapper{ public BitacoraSeguimientoMapper() { super(); } @Override public Object mapRow(ResultSet resultSet, int i) throws SQLException { BitacoraSeguimiento bitacora=new BitacoraSeguimiento(); bitacora.setFechaMovimiento(resultSet.getDate("fechamovimiento")); bitacora.setIdEstadoDocumento(resultSet.getInt("idestadodocto")); bitacora.setNumeroControl(resultSet.getString("numerocontrol")); return bitacora; } }
true
f960a2d68c8f3ce46f80568cca8f536575d02def
Java
sicef-hakaton-2/open-systems-and-security-lab-foi-oss
/android-application/app/src/main/java/party/sicef/borderless/ui/activity/CardsActivity.java
UTF-8
3,222
2.203125
2
[]
no_license
package party.sicef.borderless.ui.activity; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import party.sicef.borderless.R; import party.sicef.borderless.ui.base.DrawerActivity; import party.sicef.borderless.ui.fragment.CardAcceptedFragment; import party.sicef.borderless.ui.fragment.CardNeedsFragment; import party.sicef.borderless.ui.fragment.CardRequestedFragment; import party.sicef.borderless.ui.util.NonSwipeableViewPager; /** * Created by Andro on 11/14/2015. */ public class CardsActivity extends DrawerActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); inflateActivityLayout(R.layout.activity_cards); // remove shadow from toolbar if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { findViewById(R.id.appbar_layout).setElevation(0); } PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager()); NonSwipeableViewPager pager = (NonSwipeableViewPager) findViewById(R.id.viewpager); pager.setSwipe(false); pager.setAdapter(adapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout); tabLayout.setupWithViewPager(pager); } public Location getCurrentLocation() { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // create criteria for location to get best location provider Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setAltitudeRequired(false); criteria.setSpeedAccuracy(Criteria.NO_REQUIREMENT); // get best provider for given criteria and use it to get current location String provider = lm.getBestProvider(criteria, true); return lm.getLastKnownLocation(provider); } public class PagerAdapter extends FragmentStatePagerAdapter { public PagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case 0: return new CardNeedsFragment (); case 1: return new CardAcceptedFragment(); default: return null; } } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return getString(R.string.fragment_needs_title); case 1: return getString(R.string.fragment_accepted_title); default: // error return null; } } @Override public int getCount() { return 2; } } }
true
9e836dd1e00dd3ac5be276dc08d80f89b021d990
Java
IT-likanglin/workspace
/src/main/java/com/chlian/trade/controller/InviteCodePurchaseRecordConrtoller.java
UTF-8
4,129
2.375
2
[]
no_license
package com.chlian.trade.controller; import com.chlian.trade.domain.InviteCodePurchaseRecord; import com.chlian.trade.domain.RestResult; import com.chlian.trade.service.IInviteCodePurchaseRecordService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping(value = "/inviteCodePurchase") public class InviteCodePurchaseRecordConrtoller extends BaseController{ @Autowired private IInviteCodePurchaseRecordService iInviteCodePurchaseRecordService; @RequestMapping(value = "", method = RequestMethod.GET) public RestResult<?> findAll () { try { List<InviteCodePurchaseRecord> list = iInviteCodePurchaseRecordService.findAll(); return new RestResult<>().success(list); } catch (Exception e) { logger.error("查询出错,详细信息:" + e.getMessage()); } return new RestResult<>().error("数据查询出错"); } @RequestMapping(value = "/{code}", method = RequestMethod.GET) public RestResult<?> findByCode(@PathVariable(value = "code") String code) { try { InviteCodePurchaseRecord inviteCodePurchaseRecord = iInviteCodePurchaseRecordService.findByCode(code); return new RestResult<>().success(inviteCodePurchaseRecord); } catch (Exception e) { logger.error("数据查询失败,详细信息:" + e.getMessage()); } return new RestResult<>().error("数据查询失败"); } @RequestMapping(value = "/page/{page}/{size}", method = RequestMethod.GET) public RestResult findAllByPage(@PathVariable(value = "page") String page, @PathVariable(value = "size") String size) { if (StringUtils.isEmpty(page)) { page = "1"; } if (StringUtils.isEmpty(size)) { size = "10"; } try { List<InviteCodePurchaseRecord> list = iInviteCodePurchaseRecordService.findAllByPage(Integer.parseInt(page), Integer.parseInt(size)); return new RestResult<>().success(list); } catch (Exception e) { logger.error("数据查询失败,详细信息:" + e.getMessage()); } return new RestResult<>().error("数据查询失败"); } @RequestMapping(value = "/{code}", method = RequestMethod.DELETE) public RestResult<?> deleteByCode(@PathVariable(value = "code") String code) { try { iInviteCodePurchaseRecordService.deleteByCode(code); return new RestResult<>().success("删除成功"); } catch (Exception e) { logger.error("删除失败,详细信息:" + e.getMessage()); } return new RestResult<>().error("删除失败"); } @RequestMapping(value = "", method = RequestMethod.POST) public RestResult<?> addInviteCodePurchaseRecord(InviteCodePurchaseRecord inviteCodePurchaseRecord) { try { iInviteCodePurchaseRecordService.addRefund(inviteCodePurchaseRecord); return new RestResult<>().success("新增成功"); } catch (Exception e) { logger.error("新增失败,详细信息:" + e.getMessage()); } return new RestResult<>().error("新增失败"); } @RequestMapping(value = "/{code}", method = RequestMethod.PUT) public RestResult updateInviteCodePurchaseRecord(@PathVariable(value = "code") String code, InviteCodePurchaseRecord inviteCodePurchaseRecord) { try { iInviteCodePurchaseRecordService.updateRefund(code, inviteCodePurchaseRecord); return new RestResult<>().success("修改成功"); } catch (Exception e) { logger.error("修改失败,详细信息:" + e.getMessage()); } return new RestResult<>().error("修改失败"); } }
true
446daa8b64ebcf968074b759c2c89b6121bcf549
Java
Swapna-Niit/mavencode
/CarsProject/src/main/java/com/hexaware/factory/CarDAO.java
UTF-8
1,004
2.515625
3
[]
no_license
package com.hexaware.factory; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.Mapper; import java.sql.Date; import java.util.List; import com.hexaware.model.Car; import com.hexaware.persistance.CarMapper; public interface CarDAO { @SqlQuery("Select * from cars") @Mapper(CarMapper.class) List<Car> show(); @SqlUpdate("Insert into Cars (id, name, price, pdate)" + " values (:cid ,:cname,:cprice, :cpdate)") int insertCar(@Bind("cid") int id,@Bind("cname") String cname, @Bind("cprice")int cprice, @Bind("cpdate") Date scpdate); @SqlQuery("Select * from Cars where id = :carId") @Mapper(CarMapper.class) Car showCar(@Bind("carId") int carId); @SqlUpdate("Update Cars Set price = :newPrice where ID = :carId") @Mapper(CarMapper.class) int updateCarPrice(@Bind("carId") int carId, @Bind("newPrice") int newPrice); }
true
120750ee1a3f8076a319c0e36eae9d2fc79d0c36
Java
kenji1984/video-streaming-rest-api
/src/main/java/com/streaming/videos/controller/MainController.java
UTF-8
1,139
2.28125
2
[]
no_license
package com.streaming.videos.controller; import java.util.List; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import com.streaming.videos.model.VideoFile; import com.streaming.videos.model.VideoImageMapper; @Controller public class MainController { @Value("${video.path}") private String videoPath; @GetMapping({"/", "/home"}) public String home(Model model) { VideoImageMapper mapper = VideoImageMapper.getInstance(); System.out.println(videoPath); mapper.initialize(videoPath); List<VideoFile> videos = mapper.listVideos(); videos.sort((a, b) -> a.getName().compareTo(b.getName())); model.addAttribute("videos", videos); return "index"; } @GetMapping("/videos/play/{name}") public String play(Model model, @PathVariable("name") String name) { VideoImageMapper mapper = VideoImageMapper.getInstance(); model.addAttribute("NOW_PLAYING", mapper.findVideo(name)); return "play"; } }
true
6f0cfaba41582bedbb82a6cc80d429108d40ec27
Java
carlosangulom/EstructuraDeDatos
/EstructuraDatosOtro/src/ListaDoble.java
UTF-8
1,446
3.40625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author SB-D1 */ public class ListaDoble { private NodoString inicio, fin; public ListaDoble() { inicio=fin=null; } public void mostrar(){for(NodoString i=inicio;i!=null;i=i.getSig())System.out.print(i); } public void insertar(String d){ NodoString t=new NodoString(d); if(inicio==null)inicio=fin=new NodoString(d);//Lista vacía else{ if(d.compareToIgnoreCase(inicio.getDato())<0){//Insertar a la izquierda inicio.setAnt(t); t.setSig(inicio); inicio=t; }else if(d.compareToIgnoreCase(fin.getDato())>0){//Insertar al final fin.setSig(t); t.setAnt(fin); fin=t; } else{ for(NodoString i=inicio.getSig(); i!=fin; i=i.getSig()){//Insertar en medio if(d.compareToIgnoreCase(i.getDato())<0){ i.getAnt().setSig(t); t.setAnt(i.getAnt());t.setSig(i); i.setAnt(t); } } } } }//insertar public static void main(String[] arg){ ListaDoble i=new ListaDoble(); i.insertar("Sergio"); i.insertar("Paola");i.insertar("Will"); i.insertar("Ramón"); i.mostrar(); } }
true
a1b94c2e1c620c649633a05c5f664158639a336e
Java
dayezi12138/app-component
/project_xf/src/main/java/com/zh/xfz/dagger/module/fragment/CompanyMemberListModule.java
UTF-8
1,056
2.046875
2
[]
no_license
package com.zh.xfz.dagger.module.fragment; import com.zh.xfz.business.fragment.CompanyMemberListFragment; import core.app.zh.com.core.annotation.FragmentScope; import core.app.zh.com.core.base.BaseActivity; import core.app.zh.com.core.base.BaseView; import core.app.zh.com.core.base.MyBaseModel; import dagger.Module; import dagger.Provides; /** * author : dayezi * data :2019/12/24 * description: */ @Module public class CompanyMemberListModule { @FragmentScope @Provides public BaseActivity activity(CompanyMemberListFragment fragment) { return fragment.getMyActivity(); } @FragmentScope @Provides public MyBaseModel baseModel(CompanyMemberListFragment fragment) { return new MyBaseModel(fragment.getMyActivity().getApplication()) { @Override public BaseView getBaseView() { return fragment; } @Override public BaseActivity getMyActivity() { return fragment.getMyActivity(); } }; } }
true
dfd75b48b490156e597da07ae50ff8b361fe93d2
Java
AndreasSchmidt79/TheGame
/src/drawing/button/TextButton.java
UTF-8
1,010
2.53125
3
[]
no_license
package drawing.button; import drawing.Position; import drawing.SpriteElement; import drawing.TextureFilepath; import game.UserAction; public class TextButton extends AbstractButton { private static final int SPRITEELEMENT_WIDTH = 300; private static final int SPRITEELEMENT_HEIGHT = 63; public TextButton(UserAction action, Position pos, int width, int height, String text) { super(action, pos, width, height); spriteElementDefault = new SpriteElement(new Position(0,0), SPRITEELEMENT_WIDTH, SPRITEELEMENT_HEIGHT); spriteElementClicked = new SpriteElement(new Position(0,78), SPRITEELEMENT_WIDTH, SPRITEELEMENT_HEIGHT); spriteElementHover = new SpriteElement(new Position(0,156), SPRITEELEMENT_WIDTH, SPRITEELEMENT_HEIGHT); spriteElementInactive = new SpriteElement(new Position(0,234), SPRITEELEMENT_WIDTH, SPRITEELEMENT_HEIGHT); setText(text); setSpriteFilePath(TextureFilepath.UI_TEXT_BUTTON); setButtonDefault(); } }
true
78c5db10e69458113551b231a07b871982dad6ef
Java
Milstein/yelp-graph
/src/main/java/be/datablend/yelp/model/Business.java
UTF-8
2,929
2.6875
3
[]
no_license
package be.datablend.yelp.model; import java.util.*; /** * User: dsuvee (datablend.be) * Date: 28/11/13 */ public class Business { private String id; private String name; private String city; private Set<String> categories; private Map<String,Long> checkIns; private Business() { } public static Builder builder() { return new Builder(); } public String getId() { return id; } public Set<String> getCategories() { return categories; } public Map<String, Long> getCheckIns() { return checkIns; } public long getNumberOfCheckIns() { long numberOfCheckIns = 0; for (Long value : checkIns.values()) { numberOfCheckIns = numberOfCheckIns + value; } return numberOfCheckIns; } public Long getCheckIn(String checkInKey) { return checkIns.get(checkInKey); } public String getCity() { return city; } public String getName() { return name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Business business = (Business) o; if (id != null ? !id.equals(business.id) : business.id != null) return false; return true; } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } public static class Builder { private String id; private String name; private String city; private Set<String> categories = new HashSet<String>(); private Map<String,Long> checkIns = new LinkedHashMap<String, java.lang.Long>(); private Builder() { // Pre-initialize checkins for (int i = 0; i < 24; i++) { for (int j = 0; j < 7; j++) { checkIns.put(i + "-" + j, 0L); } } } public Builder setId(String id) { this.id = id; return this; } public Builder setName(String name) { this.name = name; return this; } public Builder setCity(String city) { this.city = city; return this; } public Builder addCategory(String category) { this.categories.add(category); return this; } public Builder addCheckIn(String checkInKey, long numberOfCheckIns) { this.checkIns.put(checkInKey, numberOfCheckIns); return this; } public Business build() { final Business business = new Business(); business.id = id; business.name = name; business.city = city; business.categories = categories; business.checkIns = checkIns; return business; } } }
true
9bde9e58160b87b0112f6b36fad0568f7a6a6c79
Java
Hanmourang/Gobblin
/gobblin-core/src/main/java/gobblin/source/extractor/watermark/WatermarkPredicate.java
UTF-8
2,993
2.203125
2
[ "Apache-2.0", "BSD-3-Clause", "xpp", "MIT" ]
permissive
/* * Copyright (C) 2014-2015 LinkedIn Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the * License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. */ package gobblin.source.extractor.watermark; import gobblin.source.extractor.extract.QueryBasedExtractor; import java.util.HashMap; import org.apache.commons.lang.StringUtils; public class WatermarkPredicate { private static final String DEFAULT_WATERMARK_VALUE_FORMAT = "yyyyMMddHHmmss"; private static final long DEFAULT_WATERMARK_VALUE = -1; private String watermarkColumn; private WatermarkType watermarkType; private Watermark watermark; public WatermarkPredicate(WatermarkType watermarkType) { this(null, watermarkType); } public WatermarkPredicate(String watermarkColumn, WatermarkType watermarkType) { super(); this.watermarkColumn = watermarkColumn; this.watermarkType = watermarkType; switch (watermarkType) { case TIMESTAMP: this.watermark = new TimestampWatermark(watermarkColumn, DEFAULT_WATERMARK_VALUE_FORMAT); break; case DATE: this.watermark = new DateWatermark(watermarkColumn, DEFAULT_WATERMARK_VALUE_FORMAT); break; case HOUR: this.watermark = new HourWatermark(watermarkColumn, DEFAULT_WATERMARK_VALUE_FORMAT); break; case SIMPLE: this.watermark = new SimpleWatermark(watermarkColumn, DEFAULT_WATERMARK_VALUE_FORMAT); break; default: this.watermark = new SimpleWatermark(watermarkColumn, DEFAULT_WATERMARK_VALUE_FORMAT); break; } } public Predicate getPredicate(QueryBasedExtractor extractor, long watermarkValue, String operator, Predicate.PredicateType type) { String condition = ""; if (watermarkValue != DEFAULT_WATERMARK_VALUE) { condition = this.watermark.getWatermarkCondition(extractor, watermarkValue, operator); } if (StringUtils.isBlank(watermarkColumn) || condition.equals("")) { return null; } return new Predicate(this.watermarkColumn, watermarkValue, condition, this.getWatermarkSourceFormat(extractor), type); } public String getWatermarkSourceFormat(QueryBasedExtractor extractor) { return extractor.getWatermarkSourceFormat(this.watermarkType); } public HashMap<Long, Long> getPartitions(long lowWatermarkValue, long highWatermarkValue, int partitionInterval, int maxIntervals) { return this.watermark.getIntervals(lowWatermarkValue, highWatermarkValue, partitionInterval, maxIntervals); } public int getDeltaNumForNextWatermark() { return this.watermark.getDeltaNumForNextWatermark(); } }
true
25919c5d0caa8cf67b25b31be3dc88a39dbb457a
Java
xSke/CoreServer
/src/mikera/vectorz/ops/Product.java
UTF-8
2,373
2.8125
3
[]
no_license
/* * Decompiled with CFR 0_129. */ package mikera.vectorz.ops; import mikera.vectorz.Op; import mikera.vectorz.ops.ALinearOp; import mikera.vectorz.ops.Constant; import mikera.vectorz.ops.Linear; import mikera.vectorz.ops.Quadratic; public final class Product extends Op { public final Op a; public final Op b; private Product(Op a, Op b) { this.a = a; this.b = b; } private static Op tryOptimisedCreate(Op a, Op b) { if (a instanceof Constant) { return Linear.create(((Constant)a).value, 0.0).compose(b); } if (a instanceof ALinearOp && b instanceof ALinearOp) { ALinearOp la = (ALinearOp)a; ALinearOp lb = (ALinearOp)b; double a1 = la.getFactor(); double a2 = la.getConstant(); double b1 = lb.getFactor(); double b2 = lb.getConstant(); return Quadratic.create(a1 * b1, a1 * b2 + b1 * a2, b2 * a2); } return null; } public static Op create(Op a, Op b) { Op t1 = Product.tryOptimisedCreate(a, b); if (t1 != null) { return t1; } Op t2 = Product.tryOptimisedCreate(b, a); if (t2 != null) { return t2; } return new Product(a, b); } @Override public double apply(double x) { return this.a.apply(x) * this.b.apply(x); } @Override public double averageValue() { return this.a.averageValue() * this.b.averageValue(); } @Override public boolean hasDerivative() { return this.a.hasDerivative() && this.b.hasDerivative(); } @Override public boolean hasDerivativeForOutput() { return false; } @Override public double derivative(double x) { double ay = this.a.apply(x); double by = this.b.apply(x); return this.a.derivative(x) * by + this.b.derivative(x) * ay; } @Override public Op getDerivativeOp() { Op da = this.a.getDerivativeOp(); Op db = this.b.getDerivativeOp(); return da.product(this.b).sum(db.product(this.a)); } @Override public boolean isStochastic() { return this.a.isStochastic() || this.b.isStochastic(); } @Override public String toString() { return "Product(" + this.a + "," + this.b + ")"; } }
true
87044fcb9862983b65c1301ec5e08df050980f56
Java
gabriel-roque/ia-buscas
/src/estrategiasDeBusca/cega/BuscaEmProfundidadeLimitada.java
ISO-8859-1
2,708
3.28125
3
[]
no_license
package estrategiasDeBusca.cega; import java.util.Collections; import java.util.List; import espacoDeEstados.Estado; /** * Esta classe implementa uma estratgia de busca cega conhecida como "Busca em * Profundidade", que caracterstica por explorar o espao se aprofundando no * ramo atual antes de faz-lo noutra ramificao. * * @author Leandro C. Fernandes * */ public class BuscaEmProfundidadeLimitada extends BuscaEmProfundidade { private int limite; /** * Construtor padro. */ public BuscaEmProfundidadeLimitada() { this(null,null,10); } /** * Cria uma nova instncia de Busca em Profundidade, definindo os estados * inicial e objetivo para o processo, alm do limite de aprofundamento. * @param estadoInicial estado inicial de busca. * @param estadoMeta estado que contm os objetivos da busca. * @param nivelLimite nvel mximo de aprofundamento da rvore. */ public BuscaEmProfundidadeLimitada(Estado<?> estadoInicial, Estado<?> estadoMeta, int nivelLimite) { super(estadoInicial,estadoMeta); super.nomeDaEstrategia = "Busca em Profundidade Limitada (at " + limite + " nveis)"; this.limite = nivelLimite; } /** * Retorna o nvel mximo de aprofundamento definido para o processo de busca. * @param limite nvel mximo de aprofundamento da rvore. */ public int getLimite() { return limite; } /** * Define o nvel mximo de aprofundamento que um ramo ser explorado. * @param limite nvel mximo de aprofundamento da rvore. */ public void setLimite(int limite) { this.limite = limite; } /** * Implementa efetivamente a estratgia de busca, iniciando a explorao do * espao a partir do estado inicial e seguindo nvel a nvel no ramo atual * at alcanar um estado que atenda os objetivos ou no tenha sucessor. * Ao trmino, o caminho correspondente a soluo ter sido armazenado no * atributo caminho. */ @SuppressWarnings("unchecked") @Override public void buscar() { Estado<?> eCorrente = eInicial; while ((eCorrente != null) && (!eCorrente.equals(eObjetivo))) { if (eCorrente.getNivel() < limite) for (Estado<?> estado : (List<Estado<?>>) eCorrente.getSucessores()) eAbertos.push(estado); eCorrente = eAbertos.pop(); } // Se o lao foi encerrado por um estado vlido ... if (eCorrente != null) { // ento construmos o caminho da soluo (da folha at a raiz) caminho.add(eCorrente); while (eCorrente.getAncestral() != null) { eCorrente = eCorrente.getAncestral(); caminho.add(eCorrente); } Collections.reverse(caminho); } } }
true
c05d6e24638f795f8cc4c1ffd64840d473669bf1
Java
kaoz36/RespaldoUniat
/AndroidStudioProjects/Respaldos/Eduscore 2015-04-15/app/src/main/java/com/uniat/eduscore/LoginActivity.java
UTF-8
647
1.9375
2
[]
no_license
package com.uniat.eduscore; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.university3dmx.eduscore.R; public class LoginActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); } public void onClickLogin(View view){ Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish(); } public void onClickSalir(View view){ finish(); } }
true
bf3abca60de5e481a0e4960a43645930785a0fed
Java
rheiser/jBGG
/jBGG/src/main/java/org/kerf/bgg/jaxb/Guild.java
UTF-8
3,625
1.976563
2
[ "Apache-2.0" ]
permissive
/** Copyright 2013 Rob Heiser 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.kerf.bgg.jaxb; import java.io.Serializable; import java.net.URL; import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.kerf.bgg.jaxb.adapter.LongDateAdapter; import org.kerf.bgg.jaxb.adapter.URLAdapter; import org.kerf.bgg.type.GuildCategory; @XmlRootElement(name = "guild") @XmlAccessorType(XmlAccessType.FIELD) public class Guild implements Serializable { @XmlAttribute String id; @XmlAttribute String name; @XmlAttribute @XmlJavaTypeAdapter(LongDateAdapter.class) Date created; @XmlAttribute(name = "termsofuse") URL termsOfUse; @XmlElement GuildCategory category; @XmlElement @XmlJavaTypeAdapter(URLAdapter.class) URL website; @XmlElement String manager; @XmlElement String description; @XmlElement Location location; @XmlElement String error; public String toString() { String retval = "GUILD: "; retval += " | ID: " + getId(); retval += " | Name: " + getName(); retval += " | Created: " + getCreated(); retval += " | Terms of Use: " + getTermsOfUse(); retval += " | Category: " + getCategory(); retval += " | Website: " + getWebsite(); retval += " | Manager: " + getManager(); retval += " | Description: " + getDescription(); retval += " | Location: " + getLocation(); return retval; } public GuildCategory getCategory() { return category; } public Date getCreated() { return created; } public String getDescription() { return description; } public String getId() { return id; } public Location getLocation() { return location; } public String getManager() { return manager; } public String getName() { return name; } public URL getTermsOfUse() { return termsOfUse; } public URL getWebsite() { return website; } public void setCategory(GuildCategory category) { this.category = category; } public void setCreated(Date created) { this.created = created; } public void setDescription(String description) { this.description = description; } public void setId(String id) { this.id = id; } public void setLocation(Location location) { this.location = location; } public void setManager(String manager) { this.manager = manager; } public void setName(String name) { this.name = name; } public void setTermsOfUse(URL termsOfUse) { this.termsOfUse = termsOfUse; } public void setWebsite(URL website) { this.website = website; } public String getError() { return error; } public void setError(String error) { this.error = error; } }
true
62b4ad107c04419136eda8877be4583807089175
Java
hakankar/Hoopoe
/app/src/main/java/karyagdi/hakan/hoopoe/MainActivity.java
UTF-8
895
2.03125
2
[]
no_license
package karyagdi.hakan.hoopoe; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Opinion op = new Opinion(37,"deneme37","denek",null); Opinion op2 = new Opinion(36,"deneme36","denek",null); op.save(getApplicationContext()); op2.save(getApplicationContext()); List<Opinion> all = Opinion.getAllEntities(Opinion.class,getApplicationContext()); Log.v("KAYIT ADEDI::: ",String.valueOf(all.size())); Log.v("KAYIT ID::: ",String.valueOf(all.get(0).getOpinionDesc())); Log.v("KAYIT ID::: ",String.valueOf(all.get(1).getOpinionDesc())); } }
true
40e476261f9659aefc4bbb8af1e988d1f976c993
Java
borisovdenis-kb/epam-task-7
/src/main/java/ru/intodayer/duplicatemodels/DuplicateBook.java
UTF-8
2,375
2.953125
3
[]
no_license
package ru.intodayer.duplicatemodels; import ru.intodayer.models.Author; import ru.intodayer.models.Book; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class DuplicateBook extends UniqueObject { private String title; private LocalDate publishDate; private List<DuplicateAuthor> authors = new ArrayList<>(); public DuplicateBook() { } public DuplicateBook(Book book) { this.title = book.getTitle(); this.publishDate = book.getPublishDate(); } public DuplicateAuthor addAuthor(Author author) { DuplicateAuthor newAuthor = new DuplicateAuthor(author); authors.add(newAuthor); return newAuthor; } public void setTitle(String title) { this.title = title; } public void setPublishDate(LocalDate publishDate) { this.publishDate = publishDate; } public void setAuthors(List<DuplicateAuthor> authors) { this.authors = authors; } public List<DuplicateAuthor> getAuthors() { return authors; } private Author[] castObjectArrayToAuthorArray(Object[] objects) { Author[] authors = new Author[objects.length]; for (int i = 0; i < objects.length; i++) { authors[i] = (Author) objects[i]; } return authors; } public Book getBookFromThis() { Object[] objects = this.authors .stream() .map((a) -> a.getAuthorFromThis()) .collect(Collectors.toList()).toArray(); return new Book( this.title, this.publishDate, castObjectArrayToAuthorArray(objects) ); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DuplicateBook)) return false; DuplicateBook that = (DuplicateBook) o; if (!title.equals(that.title)) return false; if (!publishDate.equals(that.publishDate)) return false; return authors.equals(that.authors); } @Override public int hashCode() { int result = title.hashCode(); result = 31 * result + publishDate.hashCode(); result = 31 * result + authors.hashCode(); return result; } @Override public String toString() { return title; } }
true
103fa6cd9180f8156d7ac99ce475f6b8145bf96e
Java
solarce/android-sync
/test/src/org/mozilla/android/sync/test/helpers/DefaultSessionCreationDelegate.java
UTF-8
1,517
2.203125
2
[]
no_license
/* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ package org.mozilla.android.sync.test.helpers; import org.mozilla.gecko.sync.repositories.RepositorySession; import org.mozilla.gecko.sync.repositories.delegates.RepositorySessionCreationDelegate; public class DefaultSessionCreationDelegate extends DefaultDelegate implements RepositorySessionCreationDelegate { @Override public void onSessionCreateFailed(Exception ex) { performNotify("Session creation failed", ex); } @Override public void onSessionCreated(RepositorySession session) { performNotify("Should not have been created.", null); } @Override public RepositorySessionCreationDelegate deferredCreationDelegate() { final RepositorySessionCreationDelegate self = this; return new RepositorySessionCreationDelegate() { @Override public void onSessionCreated(final RepositorySession session) { new Thread(new Runnable() { @Override public void run() { self.onSessionCreated(session); } }).start(); } @Override public void onSessionCreateFailed(final Exception ex) { new Thread(new Runnable() { @Override public void run() { self.onSessionCreateFailed(ex); } }).start(); } @Override public RepositorySessionCreationDelegate deferredCreationDelegate() { return this; } }; } }
true