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
80a0cfc8d00fe2f687a6c1dba0be5e6bd52ed02d
Java
mki366/moff_Back
/src/main/java/bit/com/a/controller/MemberController.java
UTF-8
3,774
2.34375
2
[]
no_license
package bit.com.a.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import bit.com.a.dto.MemberDto; import bit.com.a.service.MemberService; @RestController public class MemberController { @Autowired MemberService service; @RequestMapping(value = "/idcheck", method = RequestMethod.POST) public String idcheck(String id) { System.out.println("MemberConroller idcheck()"); boolean b = service.idCheck(id); if(b == true) { return "NO"; }else { return "YES"; } } @RequestMapping(value = "/signup", method = RequestMethod.POST) public String signup(MemberDto dto) { System.out.println("MemberController signup()"); System.out.println("메머추가ㅏㅏㅏㅏㅏㅏㅏㅏ"+dto.toString()); boolean b = service.addmember(dto); if(b) { return "YES"; }else { return "NO"; } } @RequestMapping(value = "/snsCheck", method = RequestMethod.POST) public String snsCheck(String email) { System.out.println("MemberConroller snsCheck()"); boolean b = service.snsCheck(email); if(b == true) { return "NO"; }else { return "YES"; } } @RequestMapping(value = "/snsSignup", method = RequestMethod.POST) public MemberDto snsSignup(MemberDto dto) { System.out.println("MemberController snsSignup()"); service.addmember(dto); return service.login(new MemberDto( dto.getId(), dto.getPwd(), null, null, null, null, null, null)); } @RequestMapping(value = "/googleLogin", method = RequestMethod.POST) public String googleLogin(MemberDto dto) { System.out.println("MemberController signup()"); System.out.println("메머추가ㅏㅏㅏㅏㅏㅏㅏㅏ"+dto.toString()); boolean b = service.addmember(dto); if(b) { return "YES"; }else { return "NO"; } } @RequestMapping(value = "/login", method = RequestMethod.POST) public MemberDto login(String id, String pwd) { System.err.println(id+ "/" + pwd); System.out.println("MemberController login()"); MemberDto dto = service.login(new MemberDto(id, pwd, null, null, null, null, null, null)); System.out.println("로그인 정보:" + dto.toString()); return dto; } @RequestMapping(value = "/personalUpdate", method = RequestMethod.POST) public MemberDto personalUpdate(MemberDto dto) { System.out.println("MemberController personalUpdate()"); MemberDto mem = null; boolean b = service.personalUpdate(dto); if(b) { mem = service.getMem(dto); } return mem; } @RequestMapping(value = "/contactUpdate", method = RequestMethod.POST) public MemberDto contactUpdate(MemberDto dto) { System.out.println("MemberController contactUpdate()"); MemberDto mem = null; boolean b = service.contactUpdate(dto); if(b) { mem = service.getMem(dto); } return mem; } @RequestMapping(value = "/pwdUpdate", method = RequestMethod.POST) public MemberDto pwdUpdate(MemberDto dto) { System.out.println("MemberController pwdUpdate()"); MemberDto mem = null; boolean b = service.pwdUpdate(dto); if(b) { mem = service.getMem(dto); } return mem; } @RequestMapping(value = "/addressUpdate", method = RequestMethod.POST) public MemberDto addressUpdate(MemberDto dto) { System.out.println("MemberController addressUpdate()"); MemberDto mem = null; boolean b = service.addressUpdate(dto); if(b) { mem = service.getMem(dto); } return mem; } @RequestMapping(value = "/byebye", method = RequestMethod.POST) public void byebye(MemberDto dto) { System.out.println("MemberController byebye()"); service.byebye(dto); } }
true
bacb61d6ee28add6800769135074a5f6c147ea68
Java
whynotmatt/GithubBrowser
/app/src/main/java/com/mjohnston/githubbrowser/fragment/WebFragment.java
UTF-8
2,734
2.1875
2
[]
no_license
package com.mjohnston.githubbrowser.fragment; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import com.mjohnston.githubbrowser.R; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by mattjohnston on 4/15/17. */ public class WebFragment extends BaseFragment { public static final String URL = "url"; public static final String FRAGMENT_TAG = "web"; @BindView(R.id.webView) WebView webView; protected String url; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null && getArguments().containsKey(URL)) { url = getArguments().getString(URL); } } @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_web, container, false); ButterKnife.bind(this, rootView); if (webView != null && url != null) { webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new InternalWebViewClient()); webView.loadUrl(url); } return rootView; } @OnClick(R.id.closeBtn) protected void clickedClose() { FragmentManager fragmentManager = getFragmentManager(); fragmentManager.popBackStack(); } public boolean interceptBackPressed() { // see if the back button should navigate the history of the webview if (webView.canGoBack()) { webView.goBack(); return true; } else { return false; } } // custom web view client to handle redirects inside the web view protected class InternalWebViewClient extends WebViewClient { @SuppressWarnings("deprecation") @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return false; } @TargetApi(Build.VERSION_CODES.N) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { String url = request.getUrl().toString(); shouldOverrideUrlLoading(view, url); return false; } } }
true
8b748e545a9740a20e572b14925aa5166467c100
Java
sumanD/hotel-automation-controller
/src/main/java/com/sahaj/hms/domain/equipment/Light.java
UTF-8
1,645
3.125
3
[]
no_license
package com.sahaj.hms.domain.equipment; import com.sahaj.hms.common.Builder; import com.sahaj.hms.domain.enums.EquipmentState; import com.sahaj.hms.domain.enums.EquipmentType; /** * Represents a Light {@link Light}, an electrical Light equipment. * <p> * This class is a sub-class of Equipment {@link Equipment} class. */ public class Light extends Equipment { private static final EquipmentType equipmentType = EquipmentType.LIGHT; private Light(EquipmentState equipmentState, PowerConsumption powerConsumption) { super(equipmentState, powerConsumption, equipmentType); } public static class LightBuilder implements Builder<Light> { private EquipmentState equipmentState; private PowerConsumption powerConsumption; public LightBuilder(final EquipmentState equipmentState, final PowerConsumption powerConsumption) { this.equipmentState = equipmentState; this.powerConsumption = powerConsumption; } @Override public Light construct() { return new Light(this.equipmentState, this.powerConsumption); } } public void switchOn() { this.equipmentState = EquipmentState.ON; } public void switchOff(){ this.equipmentState = EquipmentState.OFF; } /** * This method returns the power consumed by Light at a particular moment * @return Power consumed */ public Integer getConsumedPower() { if (this.equipmentState == EquipmentState.ON) { return this.powerConsumption.getUnitValue(); } else { return 0; } } }
true
e88a1f46378272dfcbf5b00213977fd727c8b5c1
Java
chenzibin/shiro
/shiro-trigger/src/main/java/shiro/trigger/TriggerAction.java
UTF-8
974
2.328125
2
[]
no_license
package shiro.trigger; /** * 触发器动作 */ public class TriggerAction { /*动作类型*/ private String type; /*是否可用*/ private boolean enable; private String[] acceptor; private String webhook; private String text; public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isEnable() { return enable; } public void setEnable(boolean enable) { this.enable = enable; } public String getWebhook() { return webhook; } public void setWebhook(String webhook) { this.webhook = webhook; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String[] getAcceptor() { return acceptor; } public void setAcceptor(String[] acceptor) { this.acceptor = acceptor; } }
true
a7e25f7f6d13bea7a56c3cfa82f44cebf2ca095d
Java
rvidalth/loja
/src/main/java/Controllers/CadastroDeProjetos.java
UTF-8
1,031
2.6875
3
[]
no_license
package Controllers; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import Dao.PessoaDao; import Model.Pessoa; import Model.Projeto; import Services.JPAUtil; public class CadastroDeProjetos { public static void main (String []args) { EntityManager em = JPAUtil.getEntityManager(); Projeto projeto1 = new Projeto(); Projeto projeto2 = new Projeto(); Pessoa pessoa1 = new Pessoa (); Pessoa pessoa2 = new Pessoa (); pessoa1.setNome("Rodrigo"); pessoa2.setNome("Marcelo"); List<Projeto> projetos = new ArrayList<Projeto> (); PessoaDao pessoaDao = new PessoaDao(em); projeto1.setNome("SysJava"); projeto2.setNome("Hibernate"); projetos.add(projeto1); projetos.add(projeto2); pessoa1.setProjetos(projetos); pessoa2.setProjetos(projetos); em.getTransaction().begin(); pessoaDao.cadastrar(pessoa1); pessoaDao.cadastrar(pessoa2); em.flush(); em.getTransaction().commit(); em.close(); } }
true
522bc516c4d5e5ef0025dc8ec6e88ff599ceb9c6
Java
cha63506/CompSecurity
/Music-Audio/shazam_source/src/com/google/a/f/c.java
UTF-8
11,621
1.539063
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.google.a.f; import com.google.a.a.g; import com.google.a.a.h; import com.google.a.c.ad; import com.google.a.c.aj; import com.google.a.c.ao; import com.google.a.c.ap; import com.google.a.c.aq; import com.google.a.c.aw; import com.google.a.c.bk; import com.google.a.c.r; import com.google.a.c.u; import java.io.Serializable; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.Set; // Referenced classes of package com.google.a.f: // a, b, e, d public abstract class com.google.a.f.c extends com.google.a.f.a implements Serializable { private static final class a extends com.google.a.f.c { a(Type type) { super(type, (byte)0); } } private static abstract class b { static final b a = new b() { final Class a(Object obj) { return com.google.a.f.c.c(((com.google.a.f.c)obj).a); } final Iterable b(Object obj) { obj = (com.google.a.f.c)obj; if (((com.google.a.f.c) (obj)).a instanceof TypeVariable) { return com.google.a.f.c.a(((TypeVariable)((com.google.a.f.c) (obj)).a).getBounds()); } if (((com.google.a.f.c) (obj)).a instanceof WildcardType) { return com.google.a.f.c.a(((WildcardType)((com.google.a.f.c) (obj)).a).getUpperBounds()); } com.google.a.c.ad.a a1 = ad.g(); Type atype[] = com.google.a.f.c.c(((com.google.a.f.c) (obj)).a).getGenericInterfaces(); int j = atype.length; for (int i = 0; i < j; i++) { a1.c(((com.google.a.f.c) (obj)).a(atype[i])); } return a1.a(); } final Object c(Object obj) { obj = (com.google.a.f.c)obj; if (((com.google.a.f.c) (obj)).a instanceof TypeVariable) { return com.google.a.f.c.b(((TypeVariable)((com.google.a.f.c) (obj)).a).getBounds()[0]); } if (((com.google.a.f.c) (obj)).a instanceof WildcardType) { return com.google.a.f.c.b(((WildcardType)((com.google.a.f.c) (obj)).a).getUpperBounds()[0]); } Type type = com.google.a.f.c.c(((com.google.a.f.c) (obj)).a).getGenericSuperclass(); if (type == null) { return null; } else { return ((com.google.a.f.c) (obj)).a(type); } } }; static final b b = new b() { final volatile Class a(Object obj) { return (Class)obj; } final Iterable b(Object obj) { return Arrays.asList(((Class)obj).getInterfaces()); } final Object c(Object obj) { return ((Class)obj).getSuperclass(); } }; private int a(Object obj, Map map) { Object obj1 = (Integer)map.get(this); if (obj1 != null) { return ((Integer) (obj1)).intValue(); } int i; if (a(obj).isInterface()) { i = 1; } else { i = 0; } for (obj1 = b(obj).iterator(); ((Iterator) (obj1)).hasNext();) { i = Math.max(i, a(((Iterator) (obj1)).next(), map)); } obj1 = c(obj); int j = i; if (obj1 != null) { j = Math.max(i, a(obj1, map)); } map.put(obj, Integer.valueOf(j + 1)); return j + 1; } final ad a(Iterable iterable) { java.util.HashMap hashmap = aq.a(); for (iterable = iterable.iterator(); iterable.hasNext(); a(iterable.next(), ((Map) (hashmap)))) { } aw aw1 = new aw(aw.b().a(), hashmap) { final Comparator a; final Map b; public final int compare(Object obj, Object obj1) { return a.compare(b.get(obj), b.get(obj1)); } { a = comparator; b = map; super(); } }; iterable = hashmap.keySet(); int j; if (iterable instanceof Collection) { iterable = (Collection)iterable; } else { Iterator iterator = iterable.iterator(); iterable = new ArrayList(); ap.a(iterable, iterator); } iterable = ((Iterable) ((Object[])iterable.toArray())); j = iterable.length; for (int i = 0; i < j; i++) { g.a(iterable[i]); } Arrays.sort(iterable, aw1); return ad.b(iterable); } abstract Class a(Object obj); abstract Iterable b(Object obj); abstract Object c(Object obj); private b() { } b(byte byte0) { this(); } } private static abstract class c extends Enum implements h { public static final c a; public static final c b; private static final c c[]; public static c valueOf(String s) { return (c)Enum.valueOf(com/google/a/f/c$c, s); } public static c[] values() { return (c[])c.clone(); } static { a = new c("IGNORE_TYPE_VARIABLE_OR_WILDCARD") { public final volatile boolean a(Object obj) { obj = (com.google.a.f.c)obj; return !(((com.google.a.f.c) (obj)).a instanceof TypeVariable) && !(((com.google.a.f.c) (obj)).a instanceof WildcardType); } }; b = new c("INTERFACE_ONLY") { public final boolean a(Object obj) { return com.google.a.f.c.c(((com.google.a.f.c)obj).a).isInterface(); } }; c = (new c[] { a, b }); } private c(String s, int i) { super(s, i); } c(String s, int i, byte byte0) { this(s, i); } } public final class d extends u implements Serializable { final com.google.a.f.c a; private transient aj b; protected final Collection a() { return c(); } protected final Object b() { return c(); } protected final Set c() { aj aj1 = b; Object obj = aj1; if (aj1 == null) { obj = r.a(b.a.a(ad.a(a))); c c1 = c.a; obj = aj.a(r.a(ao.a(((r) (obj)).a, c1)).a); b = ((aj) (obj)); } return ((Set) (obj)); } public final Set d() { return aj.a(b.b.a(com.google.a.f.c.d(a.a))); } d() { a = com.google.a.f.c.this; super(); } } final Type a; private transient com.google.a.f.b b; protected com.google.a.f.c() { a = a(); boolean flag; if (!(a instanceof TypeVariable)) { flag = true; } else { flag = false; } g.b(flag, "Cannot construct a TypeToken for a type variable.\nYou probably meant to call new TypeToken<%s>(getClass()) that can resolve the type variable for you.\nIf you do need to create a TypeToken of a type variable, please use TypeToken.of() instead.", new Object[] { a }); } private com.google.a.f.c(Type type) { a = (Type)g.a(type); } com.google.a.f.c(Type type, byte byte0) { this(type); } static ad a(Type atype[]) { com.google.a.c.ad.a a1 = ad.g(); int j = atype.length; for (int i = 0; i < j; i++) { com.google.a.f.c c1 = e(atype[i]); if (c(c1.a).isInterface()) { a1.c(c1); } } return a1.a(); } public static com.google.a.f.c a(Class class1) { return new a(class1); } static com.google.a.f.c b(Type type) { com.google.a.f.c c1 = e(type); type = c1; if (c(c1.a).isInterface()) { type = null; } return type; } static Class c(Type type) { return (Class)d(type).a().next(); } static aj d(Type type) { g.a(type); com.google.a.c.aj.a a1 = aj.h(); (new com.google.a.f.d(a1) { final com.google.a.c.aj.a a; final void a(Class class1) { a.c(class1); } final void a(GenericArrayType genericarraytype) { a.c(com.google.a.f.e.a(com.google.a.f.c.c(genericarraytype.getGenericComponentType()))); } final void a(ParameterizedType parameterizedtype) { a.c((Class)parameterizedtype.getRawType()); } final void a(TypeVariable typevariable) { a(typevariable.getBounds()); } final void a(WildcardType wildcardtype) { a(wildcardtype.getUpperBounds()); } { a = a1; super(); } }).a(new Type[] { type }); return a1.a(); } private static com.google.a.f.c e(Type type) { return new a(type); } final com.google.a.f.c a(Type type) { g.a(type); com.google.a.f.b b2 = b; com.google.a.f.b b1 = b2; if (b2 == null) { Object obj = a; b1 = new com.google.a.f.b(); obj = com.google.a.f.b.a.a(((Type) (obj))); b1 = new com.google.a.f.b(b1.a.a(((Map) (obj)))); b = b1; } type = e(b1.a(type)); type.b = b; return type; } public final d b() { return new d(); } public boolean equals(Object obj) { if (obj instanceof com.google.a.f.c) { obj = (com.google.a.f.c)obj; return a.equals(((com.google.a.f.c) (obj)).a); } else { return false; } } public int hashCode() { return a.hashCode(); } public String toString() { return com.google.a.f.e.b(a); } }
true
a2809fe19060c839a16df870c19fe423a8b5174a
Java
fansmigo/cloud-demo
/cloud-provider/src/main/java/com/cloud/cloudprovider/controller/ProviderController.java
UTF-8
368
1.9375
2
[]
no_license
package com.cloud.cloudprovider.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 服务端 */ @RestController public class ProviderController { @RequestMapping("/sayhello") public String sayHello(){ return "我是来自provider服务端,你好呀!"; } }
true
4c2a9812a9727811f6df1fed19398236644be820
Java
15271091213/aliyun-openapi-java-sdk
/aliyun-java-sdk-cms/src/main/java/com/aliyuncs/cms/transform/v20170301/GetMyGroupsResponseUnmarshaller.java
UTF-8
2,630
1.671875
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyuncs.cms.transform.v20170301; import java.util.ArrayList; import java.util.List; import com.aliyuncs.cms.model.v20170301.GetMyGroupsResponse; import com.aliyuncs.cms.model.v20170301.GetMyGroupsResponse.Group; import com.aliyuncs.cms.model.v20170301.GetMyGroupsResponse.Group.ContactGroup; import com.aliyuncs.transform.UnmarshallerContext; public class GetMyGroupsResponseUnmarshaller { public static GetMyGroupsResponse unmarshall(GetMyGroupsResponse getMyGroupsResponse, UnmarshallerContext context) { getMyGroupsResponse.setRequestId(context.stringValue("GetMyGroupsResponse.RequestId")); getMyGroupsResponse.setSuccess(context.booleanValue("GetMyGroupsResponse.Success")); getMyGroupsResponse.setErrorCode(context.integerValue("GetMyGroupsResponse.ErrorCode")); getMyGroupsResponse.setErrorMessage(context.stringValue("GetMyGroupsResponse.ErrorMessage")); Group group = new Group(); group.setGroupId(context.longValue("GetMyGroupsResponse.Group.GroupId")); group.setGroupName(context.stringValue("GetMyGroupsResponse.Group.GroupName")); group.setServiceId(context.longValue("GetMyGroupsResponse.Group.ServiceId")); group.setBindUrl(context.stringValue("GetMyGroupsResponse.Group.BindUrl")); group.setType(context.stringValue("GetMyGroupsResponse.Group.Type")); List<ContactGroup> contactGroups = new ArrayList<ContactGroup>(); for (int i = 0; i < context.lengthValue("GetMyGroupsResponse.Group.ContactGroups.Length"); i++) { ContactGroup contactGroup = new ContactGroup(); contactGroup.setName(context.stringValue("GetMyGroupsResponse.Group.ContactGroups["+ i +"].Name")); contactGroups.add(contactGroup); } group.setContactGroups(contactGroups); getMyGroupsResponse.setGroup(group); return getMyGroupsResponse; } }
true
fbc252fb6d9e550e7404bc774644cff42335eab2
Java
Simple-Stark/SpringBoot-Activiti
/src/main/java/com/wrh/basis/BasisApplication.java
UTF-8
585
1.742188
2
[]
no_license
package com.wrh.basis; import org.activiti.spring.boot.SecurityAutoConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * 项目启动类 * * @author Simple * @date 2020-11-11 */ @SpringBootApplication(exclude = {SecurityAutoConfiguration.class, org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class}) public class BasisApplication { public static void main(String[] args) { SpringApplication.run(BasisApplication.class, args); } }
true
8ec9c0e02275c22f976ec434df232e55ce2d0e94
Java
haoranwang4/comp250
/HeapSort.java
UTF-8
1,421
3.734375
4
[]
no_license
package 堆排序; import java.util.Arrays; public class HeapSort { public static void main(String[] args) { int[]arr = {9,6,8,7,0,1,10,4,2}; heapSort(arr); System.out.println(Arrays.toString(arr)); } public static void heapSort(int[] arr){ //开始位置为最后一个非叶子节点 int start = (arr.length-2)/2; //把输入数组变成一个大顶堆 for(int i =start;i>=0;i--){ maxHeap(arr,arr.length,i); } // for(int j =arr.length-1;j>0;j--){ int temp = arr[0]; arr[0]=arr[j]; arr[j] = temp; maxHeap(arr,j,0); } } public static void maxHeap(int[] arr,int size,int index){ //左子节点 int leftNode = 2*index+1; //右子节点 int rightNode = 2*index+2; //和两个子节点分别对比找出最大的节点 int max = index; if(leftNode<size&&arr[leftNode]>arr[max]) {max = leftNode;} if(rightNode<size&&arr[rightNode]>arr[max]) {max = rightNode;} //交换位置 if(max != index){ int temp = arr[index]; arr[index] = arr[max]; arr[max]=temp; //交换位置后可能会破坏之前排好的堆,所以之前的排好的堆需要重新调整 maxHeap(arr,size,max); } } }
true
bcb1f4b375b3a5c2596e68cf2548a8885080b400
Java
wangkekekexili/YYDict
/src/util/dict/MerriamWebster.java
UTF-8
2,701
2.484375
2
[]
no_license
package util.dict; import java.io.File; import java.net.URL; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import util.Resources; import util.SearchResult; /** * A helper class for Merriam-Webster API. * * @author kewang * */ public class MerriamWebster { public static final String COLLEGIATE_BASE_URL = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/"; public static final String COLLEGIATE_AUDIO_BASE_URL = "http://media.merriam-webster.com/soundc11/"; public static SearchResult search(String word) { word = word.replaceAll(Pattern.quote(" "), "+"); String contentUrl = COLLEGIATE_BASE_URL + word + "?key=7a996464-b5ff-42e4-a2b3-3df2554fee55"; int numberOfExamples = 0; try { // get the whole word result Document document = Jsoup.connect(contentUrl) .ignoreContentType(true).get(); StringBuilder exampleSentencesBuilder = new StringBuilder(); exampleSentencesBuilder.append("Merriam Webster Examples\n"); // get examples sentences (dt -> vi) Elements dts = document.getElementsByTag("dt"); for (Element dt : dts) { Elements vis = dt.getElementsByTag("vi"); for (Element vi : vis) { numberOfExamples++; exampleSentencesBuilder.append(numberOfExamples); exampleSentencesBuilder.append(": "); exampleSentencesBuilder.append(vi.text()); exampleSentencesBuilder.append("\n"); } } exampleSentencesBuilder.append("\n\n"); // get audio file name from the result String wavFileName = null; try { wavFileName = document.getElementsByTag("wav").get(0).text(); // construct a URL for the audio String subDirectory = null; if (Character.isDigit(wavFileName.charAt(0))) { subDirectory = "number"; } else if (wavFileName.startsWith("bix")) { subDirectory = "bix"; } else if (wavFileName.startsWith("gg")) { subDirectory = "gg"; } else { subDirectory = wavFileName.substring(0, 1); } String wavUrl = COLLEGIATE_AUDIO_BASE_URL + subDirectory + "/" + wavFileName; // download audio FileUtils.copyURLToFile(new URL(wavUrl), new File(Resources.getAudioLocationToSave(wavFileName))); } catch (Exception e) {} if (numberOfExamples == 0) { return new SearchResult( false, exampleSentencesBuilder.toString(), wavFileName); } else { return new SearchResult( true, exampleSentencesBuilder.toString(), wavFileName); } } catch (Exception e) { } return new SearchResult(false, ""); } }
true
3937ded34e40427c0ffe1ed716e2815436f9742a
Java
annastakanova/U_01-cycles
/Task13b.java
UTF-8
419
3.46875
3
[]
no_license
//Составить таблицу значений функции y = 5 - x2/2 на отрезке [-5; 5] с шагом 0.5. public class Task13b { public static void main(String[] args){ double y; double a = 0.5 ; for (double x=-5; x<= 5; x += a) { y = 5 - Math.pow(x, 2)/2; System.out.print("значение функции = " + y + "\n"); } } }
true
d1698439164536c2fe97b4e7d896de318dbd21f7
Java
Aabhas99/Cart
/Cart/src/order/Create_order.java
UTF-8
3,010
2.921875
3
[]
no_license
package order; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; 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 Create_order extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { //Calling the getWriter() method to print html content on the webpage PrintWriter pw=res.getWriter(); //Making the database connection Class.forName("com.mysql.jdbc.Driver"); Connection co=DriverManager.getConnection("jdbc:mysql://localhost:3306/cart", "root", "abcd"); Statement st=co.createStatement(); //Fetching email and password from the request String email=req.getParameter("email"); String password=req.getParameter("password"); //Validating the user details ResultSet r=st.executeQuery("select email from account where email='"+email+"' and password='"+password+"'"); //In case of wrong Credentials if(!r.next()) { pw.print("Invalid details"); } //In case of correct credentials else { //Creating session for the user HttpSession session=req.getSession(); session.setAttribute("email",email); //Fetching inventory items r=st.executeQuery("select * from inventory"); pw.println("<!DOCTYPE html>\r\n" + "<html>\r\n" + "<body>"); //Displaying the inventory items while(r.next()) { int id=r.getInt(1); int quantity=r.getInt(3); String name=r.getString(2); //If the quantity of any item is zero it will not be displayed if(quantity==0)continue; pw.println("<p>"+name+"</p>"); //User can enter the quantity of the product he wants to buy //Html validation takes care that the quantity entered is within the range //After buying the items Order_done page opens pw.println("<br><form action='http://localhost:8888/Cart/order_done' method='post'"+ ">Enter Quantity: <input type='number' id='quantity' name='quantity' min='1' max='"+quantity+"'>" + "<input type='hidden' name='id' value='"+id+"'>" + "<input type='hidden' name='email' value='"+email+"'><br>" + "<input type='submit' value='Buy'>"+ "</form><br>"); } //Logout button pw.println("<br><br><form action='http://localhost:8888/Cart/logout' method='post'"+ "><input type='submit' value='Logout'>"+ "</form>"); pw.println("</body>\r\n" + "</html>"); } } catch(Exception e) { //In case of any error res.getWriter().print("Error"); } } }
true
632bf5cc7ef54eedfa033db2ac0ae21c3997d626
Java
Briliantmahathir1/program-java-menggunakan-stack
/Balanced_symbol.java
UTF-8
1,040
3.265625
3
[]
no_license
import java.util.Scanner; /* * 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. */ /** * * @Briliant Mahathir */ public class Balanced_symbol { public static void main(String[] args) { Stack_generic<String> stack = new Stack_generic<>(25); String rumus = "f(x)=(2x+y)-(3+(2x-x)+20)" ; Scanner balanced = new Scanner(rumus); System.out.println("f(x)=(2x+y)-(3+(2x-x)+20)"); balanced.useDelimiter(""); for (int i = 0; i < 25; i++) { String symbol = balanced.next(); if(symbol.equals("(")) { stack.push("("); } else if (symbol.equals(")")) { stack.pop(); } } if(stack.isEmpty()) { System.out.println("valid"); } else { System.out.println("tidak valid"); } } }
true
0242d6964fc29776ee2ded4bcf3e17fb72ebb51f
Java
callnirajgupta/CucumberSelenium
/src/test/java/com/automation/action/TestRunner2.java
UTF-8
2,142
1.820313
2
[]
no_license
/* private static final Logger LOGGER = LogManager.getLogger(CommonUtil.class); public static WebConnector webConnector = WebConnector.getInstance(); public WebConnector webConnector=WebConnector.getInstance(); WebDriver driver=webConnector.getDriver();*/ package com.automation.action; import java.text.SimpleDateFormat; import java.util.Date; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; //import org.junit.runner.RunWith; //import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import com.github.mkolisnyk.cucumber.runner.ExtendedCucumber; import com.github.mkolisnyk.cucumber.runner.ExtendedCucumberOptions; import com.github.mkolisnyk.cucumber.runner.ExtendedParallelCucumber; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(features = ".", tags = { "@AddToCart,@LoginAndLogout_ExamplesParameters" }, plugin = { "pretty", "html:target1/cucumber-html-report", "json:target1/cucumber.json", "junit:target1/cucumber.xml"}, glue = { "com.automation" } ) public class TestRunner2 { @BeforeClass public static void beforeClass(){ //For BeforeClass annotation static is compulsory because JVM calls it directly if(System.getProperty("Browser")==null){ System.setProperty("Browser", "chrome"); } if(System.getProperty("headless")==null){ System.setProperty("headless","no"); } if(System.getProperty("ENV")==null){ System.setProperty("ENV", "SIT"); } if(System.getProperty("ExecuteOn")==null){ System.setProperty("ExecuteOn", "null"); } if(System.getProperty("Remote")==null){ System.setProperty("Remote", "yes"); } //for one time driver object initialization //SeleniumUtil.initializeSeleniumConnector(); //SeleniumUtil.getInstance(); SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh-mm-ss"); System.setProperty("currentdate", dateFormat.format(new Date())); //SeleniumUtil.cleanFolder(1, "Logs");//delete all except todays } @AfterClass public static void afterClass(){ } }
true
6125446c8a4f8e6a9cb944c7e4831556634a5704
Java
huyugui1979/TestAudioAndroid
/src/com/example/testaudioandroid/AudioPlayer.java
UTF-8
1,983
2.5625
3
[]
no_license
package com.example.testaudioandroid; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.util.Log; public class AudioPlayer implements Runnable { byte[] data; AudioTrack mAudioTrack; private volatile boolean isRunning; private final Object mutex = new Object(); private static AudioPlayer instance; private AudioPlayer (){ int minBufSize = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,AudioFormat.ENCODING_PCM_16BIT); mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufSize, AudioTrack.MODE_STREAM); } public static AudioPlayer getInstance() { if (instance == null) { instance = new AudioPlayer(); } return instance; } public int getPrimePlaySize(){ int minBufSize = AudioTrack.getMinBufferSize(8000, 1, 8); return minBufSize * 2; } public void stop(){ setRunning(false); } public void setRunning(boolean isRunning) { synchronized (mutex) { this.isRunning = isRunning; if (this.isRunning) { mutex.notify(); } } } public boolean isRunning() { synchronized (mutex) { return isRunning; } } @Override public void run() { // TODO Auto-generated method stub int minBufSize = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,AudioFormat.ENCODING_PCM_16BIT); BufferQueue queue = new BufferQueue(minBufSize*2); byte[] temp = new byte[minBufSize]; byte[] data = new byte[320]; while (this.isRunning) { VoiceSession.getInstance().GetData(data); queue.append(data,0,320); if(queue.getCount()>=minBufSize) { queue.read(temp,0,minBufSize); mAudioTrack.write(temp, 0,minBufSize); mAudioTrack.play(); } } mAudioTrack.stop(); } }
true
278c354fb0de6ac73a194f1460ddfc001af4b122
Java
xyfigo/gtl_for_java
/src/main/java/gtl/spark/java/example/C03/TransformationOperation.java
UTF-8
10,235
3.40625
3
[]
no_license
package gtl.spark.java.example.C03; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.FlatMapFunction; import org.apache.spark.api.java.function.Function; import org.apache.spark.api.java.function.Function2; import org.apache.spark.api.java.function.VoidFunction; import scala.Tuple2; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * transformation操作实战 */ public class TransformationOperation { public static void main(String[] args) { mapTest(); filterTest(); flatMapTest(); groupByKeyTest(); reduceByKeyTest(); sortByKeyTest(); joinTest(); } /** * map * 将集合中的元素都乘以2 */ private static void mapTest() { SparkConf conf = new SparkConf() .setAppName("map") .setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); JavaRDD<Integer> numberRDD = sc.parallelize(numbers); JavaRDD<Integer> multipleNumberRDD = numberRDD.map(new Function<Integer, Integer>() { private static final long serialVersionUID = 1L; @Override public Integer call(Integer arg0) throws Exception { return arg0 * 2; } }); multipleNumberRDD.foreach(new VoidFunction<Integer>() { @Override public void call(Integer arg0) throws Exception { // TODO Auto-generated method stub System.out.print(arg0 + " "); } }); sc.close(); } /** * filter算子案例: * 过滤集合中的偶数 */ private static void filterTest() { SparkConf conf = new SparkConf() .setAppName("filter") .setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); JavaRDD<Integer> numberRDD = sc.parallelize(numbers); //filter算子传入的也是Function,call方法的返回值是Boolean //每一个初始RDD中的元素都会传入call方法,如果想在新的RDD中保留该元素则返回true,否则返回false JavaRDD<Integer> evenNumberRDD = numberRDD.filter(new Function<Integer, Boolean>() { private static final long serialVersionUID = 1L; @Override public Boolean call(Integer arg0) throws Exception { // TODO Auto-generated method stub return arg0 % 2 == 0; } }); evenNumberRDD.foreach(new VoidFunction<Integer>() { private static final long serialVersionUID = 1L; @Override public void call(Integer arg0) throws Exception { System.out.println(arg0); } }); sc.close(); } /** * flatMap算zi * 拆分一行文本的单词 */ private static void flatMapTest() { SparkConf conf = new SparkConf() .setAppName("faltMap") .setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); List<String> lineList = Arrays.asList("hello you", "hello me", "hello world"); JavaRDD<String> lines = sc.parallelize(lineList); /* * 对RDD执行flatMap算子将每一行文本拆分为多个单词 * flatMap其实就是接收原始RDD中的每个元素,并进行各种处理返回多个元素,即封装在Iterable中 * 新的RDD中,即封装了所有的新元素,所以新的RDD大小一定大于原始的RDD */ JavaRDD<String> words = lines.flatMap(new FlatMapFunction<String, String>() { private static final long serialVersionUID = 1L; @Override public Iterator<String> call(String arg0) throws Exception { // TODO Auto-generated method stub return Arrays.asList(arg0.split(" ")).iterator(); } }); words.foreach(new VoidFunction<String>() { private static final long serialVersionUID = 1L; @Override public void call(String arg0) throws Exception { // TODO Auto-generated method stub System.out.println(arg0); } }); sc.close(); } /** * groupByKey算子 * 案例:按照班级对成绩进行分组 */ private static void groupByKeyTest() { SparkConf conf = new SparkConf() .setAppName("groupByKey") .setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); List<Tuple2<String, Integer>> scores = Arrays.asList( new Tuple2<String, Integer>("class1", 80), new Tuple2<String, Integer>("class2", 75), new Tuple2<String, Integer>("class1", 90), new Tuple2<String, Integer>("class2", 65)); //创建JavaPairRDD JavaPairRDD<String, Integer> scoresRDD = sc.parallelizePairs(scores); JavaPairRDD<String, Iterable<Integer>> groupScores = scoresRDD.groupByKey(); groupScores.foreach(new VoidFunction<Tuple2<String, Iterable<Integer>>>() { @Override public void call(Tuple2<String, Iterable<Integer>> arg0) throws Exception { // TODO Auto-generated method stub System.out.println("class:" + arg0._1); Iterator<Integer> it = arg0._2.iterator(); while (it.hasNext()) { System.out.println(it.next()); } System.out.println("===================================="); } }); sc.close(); } /** * reduceByKey算子 * 案例:求各个班级总分 */ private static void reduceByKeyTest() { SparkConf conf = new SparkConf() .setAppName("reduceByKey") .setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); List<Tuple2<String, Integer>> scores = Arrays.asList( new Tuple2<String, Integer>("class1", 80), new Tuple2<String, Integer>("class2", 75), new Tuple2<String, Integer>("class1", 90), new Tuple2<String, Integer>("class2", 65)); JavaPairRDD<String, Integer> scoresRDD = sc.parallelizePairs(scores); JavaPairRDD<String, Integer> totalScores = scoresRDD.reduceByKey(new Function2<Integer, Integer, Integer>() { private static final long serialVersionUID = 1L; @Override public Integer call(Integer arg0, Integer arg1) throws Exception { // TODO Auto-generated method stub return arg0 + arg1; } }); totalScores.foreach(new VoidFunction<Tuple2<String, Integer>>() { @Override public void call(Tuple2<String, Integer> arg0) throws Exception { // TODO Auto-generated method stub System.out.println(arg0._1 + " : " + arg0._2); } }); sc.close(); } /** * sortByKey算子 * 案例:对学生成绩进行排序 */ private static void sortByKeyTest() { SparkConf conf = new SparkConf() .setAppName("sortByKey") .setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); List<Tuple2<Integer, String>> scores = Arrays.asList( new Tuple2<Integer, String>(10, "leo"), new Tuple2<Integer, String>(100, "ksc"), new Tuple2<Integer, String>(99, "my"), new Tuple2<Integer, String>(80, "jack")); JavaPairRDD<Integer, String> scoresRDD = sc.parallelizePairs(scores); //默认true升序,false降序 JavaPairRDD<Integer, String> sortedRDD = scoresRDD.sortByKey(); sortedRDD.foreach(new VoidFunction<Tuple2<Integer, String>>() { @Override public void call(Tuple2<Integer, String> arg0) throws Exception { System.out.println(arg0._1 + ": " + arg0._2); } }); sc.close(); } /** * join * 案例:打印学生成绩 */ private static void joinTest() { SparkConf conf = new SparkConf() .setAppName("joinandCogroup") .setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); List<Tuple2<Integer, String>> studentsList = Arrays.asList( new Tuple2<Integer, String>(1, "leo"), new Tuple2<Integer, String>(2, "jack"), new Tuple2<Integer, String>(3, "tom")); List<Tuple2<Integer, Integer>> scoresList = Arrays.asList( new Tuple2<Integer, Integer>(1, 100), new Tuple2<Integer, Integer>(2, 90), new Tuple2<Integer, Integer>(3, 60)); //并行化两个集合 JavaPairRDD<Integer, String> studentsRDD = sc.parallelizePairs(studentsList); JavaPairRDD<Integer, Integer> scoresRDD = sc.parallelizePairs(scoresList); //使用join算子关联两个RDD JavaPairRDD<Integer, Tuple2<String, Integer>> studentscores = studentsRDD.join(scoresRDD); studentscores.foreach(new VoidFunction<Tuple2<Integer, Tuple2<String, Integer>>>() { @Override public void call(Tuple2<Integer, Tuple2<String, Integer>> arg0) throws Exception { // TODO Auto-generated method stub System.out.println("student id : " + arg0._1); System.out.println("student name: " + arg0._2._1); System.out.println("student score: " + arg0._2._2); System.out.println("=========================================="); } }); } }
true
d8cff07afbe8c09d6775b94ffd47ab791c4034d3
Java
fianaz/ArithmeticOMania
/app/src/main/java/ifsb/arithmetico/AdditionPanelFragment.java
UTF-8
7,977
2.3125
2
[]
no_license
package ifsb.arithmetico; import android.app.Activity; import android.graphics.Paint; import android.os.Bundle; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.GridLayout; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import ifsb.arithmetico.R; import ifsb.arithmetico.core.AdditionQuestion; import ifsb.arithmetico.core.Question; public class AdditionPanelFragment extends QuestionPanelFragment { private GridLayout carryRow; private GridLayout numberTable; private GridLayout answerRow; private TextView tv_addop; private int col; private AdditionQuestion q; private OnQuestionPanelListener mListener; public static AdditionPanelFragment newInstance() { AdditionPanelFragment fragment = new AdditionPanelFragment(); return fragment; } public AdditionPanelFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return doit(inflater, container); // return view; } public View doit(LayoutInflater inflater, ViewGroup container) { View view = inflater.inflate(R.layout.fragment_addition_panel, container, false); carryRow = (GridLayout) view.findViewById(R.id.carryRow); numberTable = (GridLayout) view.findViewById(R.id.numberTable); answerRow = (GridLayout) view.findViewById(R.id.answerRow); tv_addop = (TextView) view.findViewById(R.id.tv_addop); if (UserSettings.leftKeypadEnabled()) { RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) carryRow.getLayoutParams(); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); carryRow.setLayoutParams(params); params = (RelativeLayout.LayoutParams) numberTable.getLayoutParams(); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); numberTable.setLayoutParams(params); params = (RelativeLayout.LayoutParams) answerRow.getLayoutParams(); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 0); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); answerRow.setLayoutParams(params); } return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnQuestionPanelListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void postQuestion(Question question) { carryRow.removeAllViews(); answerRow.removeAllViews(); numberTable.removeAllViews(); q = (AdditionQuestion) question; col = 0; int stdTextSize = UserSettings.getQuestionTextSize(); Paint paint = new Paint(); paint.setTextSize(stdTextSize); float stdMinWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, paint.measureText("0"), getResources().getDisplayMetrics()); paint.setTextSize(stdTextSize/2); float carryMinWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, paint.measureText("000"), getResources().getDisplayMetrics()); float tvMinWidth = (stdMinWidth > carryMinWidth) ? stdMinWidth : carryMinWidth; int numCols = q.getAnswerLength(); carryRow.setRowCount(1); carryRow.setColumnCount(numCols); TextView tv = null; int i=0; for (; i < numCols; i++) { tv = addCell(carryRow, 0, i, (int) tvMinWidth, stdTextSize / 2); tv.setTextColor(getResources().getColor(R.color.questionpanel_normal_text)); tv.setBackgroundColor(getResources().getColor(R.color.questionpanel_normal_bg)); } tv.setText("0"); answerRow.setRowCount(1); answerRow.setColumnCount(numCols); for (i=0; i < numCols; i++) { tv = addCell(answerRow, 0, i, (int) tvMinWidth, stdTextSize); tv.setTextColor(getResources().getColor(R.color.questionpanel_answer_text)); tv.setBackgroundColor(getResources().getColor(R.color.questionpanel_answer_bg)); } numberTable.setRowCount(q.getNumberCount()); numberTable.setColumnCount(numCols+1); for (int k=0; k < q.getNumberCount(); k++) { ArrayList<Integer> num = q.getDigitsNum(k); for (i=0; i < numCols; i++) { tv = addCell(numberTable, k, numCols-i-1,(int) tvMinWidth, stdTextSize); tv.setTextColor(getResources().getColor(R.color.questionpanel_normal_text)); tv.setBackgroundColor(getResources().getColor(R.color.questionpanel_normal_bg)); if (i < num.size()) tv.setText("" + num.get(i)); } } RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tv_addop.getLayoutParams(); params.addRule((UserSettings.leftKeypadEnabled()) ? RelativeLayout.LEFT_OF : RelativeLayout.RIGHT_OF, R.id.numberTable); params.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.numberTable); tv_addop.setTextSize(UserSettings.getQuestionTextSize()); tv_addop.setLayoutParams(params); highlightColumn(0); Hints.show(getActivity(), Hints.NUMERICPAD, Hints.SKIPQUESTION, Hints.BACKHOME1); } public void highlightColumn(int col) { TextView tv; for (int j=0; j < q.getAnswerLength(); j++) { (tv = getCarryTextView(j)).setTextColor((j == col) ? getResources().getColor(R.color.questionpanel_highlight_text) : getResources().getColor(R.color.questionpanel_normal_text)); tv.setBackgroundColor((j == col) ? getResources().getColor(R.color.questionpanel_highlight_bg) : getResources().getColor(R.color.questionpanel_normal_bg)); } for (int k=0; k < q.getNumberCount(); k++) for (int j=0; j < q.getAnswerLength(); j++) { (tv = getNumberTextView(k, j)).setTextColor((j == col) ? getResources().getColor(R.color.questionpanel_highlight_text) : getResources().getColor(R.color.questionpanel_normal_text)); tv.setBackgroundColor((j == col) ? getResources().getColor(R.color.questionpanel_highlight_bg) : getResources().getColor(R.color.questionpanel_normal_bg)); } } private TextView getNumberTextView(int row, int col) { return (TextView) numberTable.getChildAt(row*q.getAnswerLength()+col); } private TextView getCarryTextView(int col) { return (TextView) carryRow.getChildAt(carryRow.getColumnCount()-col-1); } private TextView getAnswerTextView(int col) { return (TextView) answerRow.getChildAt(answerRow.getColumnCount()-col-1); } @Override public void endSession() { } @Override public void correctResponse() { getAnswerTextView(col).setText(""+q.getDigitAns(col)); col++; if (!q.done(col)) getCarryTextView(col).setText(""+q.getCarry(col)); highlightColumn(col); } @Override public void wrongResponse() { // col = -1; } @Override public boolean checkAnswer(int answer) { return q.checkAnswer(col, answer); } @Override public boolean questionDone() { return q.done(col); } }
true
28a02569f697a00aaff435e67b550690272abcc1
Java
iTzMarcus/Old-UHC
/src/com/leontg77/uhc/Runnables.java
ISO-8859-13
9,265
2.46875
2
[]
no_license
package com.leontg77.uhc; import org.bukkit.Achievement; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Difficulty; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitRunnable; import com.leontg77.uhc.util.ArrayUtil; import com.leontg77.uhc.util.PlayersUtil; /** * The runnable class for all the runnables * @author LeonTG77 */ public class Runnables extends BukkitRunnable { public static int timeToStart; /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code>run</code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public void run() { if (timeToStart > 0 && timeToStart <= 3) { for (Player online : PlayersUtil.getPlayers()) { online.sendMessage(Main.prefix() + "UHC is starting in 6" + String.valueOf(timeToStart) + "7."); online.playSound(online.getLocation(), Sound.SUCCESSFUL_HIT, 1, 0); } } if (timeToStart == 1) { Main.stopCountdown(); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Main.plugin, new Runnable() { public void run() { for (Player online : PlayersUtil.getPlayers()) { online.playSound(online.getLocation(), Sound.SUCCESSFUL_HIT, 1, 1); if (ArrayUtil.spectating.contains(online.getName())) { Spectator.getManager().set(online, false); } online.setAllowFlight(false); online.setFlying(false); online.setHealth(20.0); online.setFireTicks(0); online.setSaturation(20); online.setLevel(0); online.setExp(0); if (!ArrayUtil.spectating.contains(online.getName())) { online.showPlayer(online); } online.awardAchievement(Achievement.OPEN_INVENTORY); online.setFoodLevel(20); online.getInventory().clear(); online.getInventory().setArmorContents(null); online.setItemOnCursor(new ItemStack (Material.AIR)); if (online.getGameMode() != GameMode.SURVIVAL) { online.setGameMode(GameMode.SURVIVAL); } for (PotionEffect effect : online.getActivePotionEffects()) { online.removePotionEffect(effect.getType()); } online.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 250, 100)); online.addPotionEffect(new PotionEffect(PotionEffectType.SATURATION, 6000, 100)); online.sendMessage(Main.prefix() + "UHC has now started, Good luck!"); online.sendMessage(Main.prefix() + "PvP will be enabled in 6" + Settings.getInstance().getData().getInt("game.pvp") + " 7mins in."); online.sendMessage(Main.prefix() + "Meetup at 6" + Settings.getInstance().getData().getInt("game.meetup") + " 7mins in."); online.sendMessage(Main.prefix() + "Remember to read the match post: " + Settings.getInstance().getData().getString("match.post")); online.sendMessage(Main.prefix() + "/helpop questions."); } GameState.setState(GameState.INGAME); Scoreboards.getManager().setScore("alPvE", 1); Scoreboards.getManager().setScore("alPvE", 0); Scoreboards.getManager().setScore("blMeetup", Integer.parseInt("-" + Settings.getInstance().getData().getInt("game.meetup"))); Scoreboards.getManager().setScore("blPvP", Integer.parseInt("-" + Settings.getInstance().getData().getInt("game.pvp"))); Scoreboards.getManager().setScore("blFinal heal", -1); for (World world : Bukkit.getWorlds()) { world.setTime(0); world.setDifficulty(Difficulty.HARD); world.setPVP(false); for (Entity mobs : world.getEntities()) { if (mobs.getType() == EntityType.BLAZE || mobs.getType() == EntityType.CAVE_SPIDER || mobs.getType() == EntityType.CREEPER || mobs.getType() == EntityType.ENDERMAN || mobs.getType() == EntityType.ZOMBIE || mobs.getType() == EntityType.WITCH || mobs.getType() == EntityType.WITHER || mobs.getType() == EntityType.DROPPED_ITEM || mobs.getType() == EntityType.GHAST || mobs.getType() == EntityType.GIANT || mobs.getType() == EntityType.MAGMA_CUBE || mobs.getType() == EntityType.DROPPED_ITEM || mobs.getType() == EntityType.SKELETON || mobs.getType() == EntityType.SPIDER || mobs.getType() == EntityType.SLIME || mobs.getType() == EntityType.SILVERFISH || mobs.getType() == EntityType.SKELETON || mobs.getType() == EntityType.EXPERIENCE_ORB) { mobs.remove(); } } } } }, 20); Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(Main.plugin, new Runnable() { public void run() { if (Scoreboards.getManager().getScoreType("blFinal heal") != null) { if ((Scoreboards.getManager().getScore("blFinal heal") + 1) == 0) { Scoreboards.getManager().resetScore("blFinal heal"); for (Player online : PlayersUtil.getPlayers()) { online.sendMessage(Main.prefix() + "6lFinal heal!"); online.playSound(online.getLocation(), Sound.NOTE_PLING, 1, 0); online.setHealth(20.0); online.setFireTicks(0); online.setFoodLevel(20); online.setSaturation(20); } } else { if ((Scoreboards.getManager().getScore("blFinal heal") + 1) < 0) { Scoreboards.getManager().setScore("blFinal heal", Scoreboards.getManager().getScore("blFinal heal") + 1); } } } if (Scoreboards.getManager().getScoreType("blPvP") != null) { if ((Scoreboards.getManager().getScore("blPvP") + 1) == 0) { Scoreboards.getManager().resetScore("blPvP"); for (Player online : PlayersUtil.getPlayers()) { online.sendMessage(Main.prefix() + "PvP is now enabled, Good luck everyone."); online.playSound(online.getLocation(), Sound.NOTE_PLING, 1, 0); } for (World world : Bukkit.getWorlds()) { world.setPVP(true); world.setPVP(true); world.setPVP(true); world.setPVP(true); world.setPVP(true); world.setPVP(true); world.setPVP(true); world.setPVP(true); } } else { if ((Scoreboards.getManager().getScore("blPvP") + 1) < 0) { Scoreboards.getManager().setScore("blPvP", Scoreboards.getManager().getScore("blPvP") + 1); } if (Scoreboards.getManager().getScore("blPvP") == -5) { Bukkit.broadcastMessage(Main.prefix() + "5 minutes to pvp, do 6/stalk 7if you think you're being stalked."); for (Player online : PlayersUtil.getPlayers()) { online.playSound(online.getLocation(), Sound.NOTE_PLING, 1, 0); } } if (Scoreboards.getManager().getScore("blPvP") == -1) { Bukkit.broadcastMessage(Main.prefix() + "1 minute to pvp, do 6/stalk 7if you think you're being stalked."); for (Player online : PlayersUtil.getPlayers()) { online.playSound(online.getLocation(), Sound.NOTE_PLING, 1, 0); } } } } if (Scoreboards.getManager().getScoreType("blMeetup") != null) { if ((Scoreboards.getManager().getScore("blMeetup") + 1) == 0) { Scoreboards.getManager().resetScore("blMeetup"); for (Player online : PlayersUtil.getPlayers()) { online.sendMessage(ChatColor.DARK_GRAY + "=============================================="); online.sendMessage(ChatColor.GREEN + " Meetup has started, start headding to 0,0."); online.sendMessage(ChatColor.GREEN + " Only stop for a fight, nothing else."); online.sendMessage(ChatColor.DARK_GRAY + "=============================================="); online.playSound(online.getLocation(), Sound.WITHER_DEATH, 1, 0); } } else { if ((Scoreboards.getManager().getScore("blMeetup") + 1) < 0) { Scoreboards.getManager().setScore("blMeetup", Scoreboards.getManager().getScore("blMeetup") + 1); } if (Scoreboards.getManager().getScore("blMeetup") == -1) { Bukkit.broadcastMessage(Main.prefix() + "1 minute to meetup, Pack your stuff and get ready to head to 0,0."); for (Player online : PlayersUtil.getPlayers()) { online.playSound(online.getLocation(), Sound.NOTE_PLING, 1, 0); } } } } } }, 1200, 1200); Bukkit.getServer().getScheduler().runTaskLater(Main.plugin, new Runnable() { public void run() { try { Bukkit.getPlayer(Settings.getInstance().getData().getString("game.host")).chat("/gamerule doMobSpawning true"); } catch (Exception e) {} } }, 3600); } timeToStart -=1; } }
true
d5d251750d1494a8ee9486a687215a1f569fbb85
Java
christopherscotini/gamaset_projects
/tradeline/tradeline/src/main/java/br/com/gamaset/tradeline/view/utils/FacesUtils.java
UTF-8
1,533
2.4375
2
[]
no_license
package br.com.gamaset.tradeline.view.utils; import java.util.Locale; import java.util.ResourceBundle; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; public final class FacesUtils { private FacesUtils() { super(); } public static void addMessageInclusaoSucesso() { addInfoMessage(getMsgs("generico.mensagem.inclusosucesso").concat(".")); } public static void addMessageAlteracaoSucesso() { addInfoMessage(getMsgs("generico.mensagem.alteracaosucesso").concat(".")); } public static void addMessageExclusaoSucesso() { addInfoMessage(getMsgs("generico.mensagem.exclusaosucesso").concat(".")); } public static void addErrorMessage(String msg) { addMessage(FacesMessage.SEVERITY_ERROR, msg); } public static void addInfoMessage(String msg) { addMessage(FacesMessage.SEVERITY_INFO, msg); } private static void addMessage(FacesMessage.Severity severity, String msg) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(severity, msg, msg)); } private static String getMsgs(String messageId) { FacesContext facesContext = FacesContext.getCurrentInstance(); String msg = ""; Locale locale = facesContext.getViewRoot().getLocale(); ResourceBundle bundle = ResourceBundle.getBundle("br.com.gamaset.diaryboard.view.bundle.Messages", locale); try { msg = bundle.getString(messageId); } catch (Exception e) { } return msg; } }
true
16492dadb0493219fc0620971cb481fda7cc4db3
Java
honglu11/webstore
/CPRG-111/hr/hr/src/main/java/ca/sait/hr/server/pages/ListEmployees.java
UTF-8
2,617
2.875
3
[]
no_license
package ca.sait.hr.server.pages; import java.util.List; import ca.sait.hr.dao.EmployeeDAO; import ca.sait.hr.dao.EmployeeDAOFactory; import ca.sait.hr.model.Employee; import ca.sait.utils.WebPageUtil; /** * URL = http://localhost:16000/list * * this will display all the employees that have been * added to the database */ public class ListEmployees implements WebPage { final EmployeeDAO employeeDAO = EmployeeDAOFactory.createInstance(); private String buildPageHead() { final StringBuilder html = new StringBuilder(); html.append("<html>"); html.append("<head>"); html.append("<style>").append("table, th, td {").append("border: 1px solid black;").append("border-collapse: collapse;}"); html.append("th, td {").append("padding: 5px;}").append("th {").append("text-align: left; }").append("</style>"); html.append("</head>"); return html.toString(); } private String buildPageBody() { final StringBuilder html = new StringBuilder(); html.append("<body>").append("All Employees List!").append("<br><br>"); final List<Employee> employeeList = getEmployeeList(); html.append("<table style='width:100%'>").append("<caption>Employee List</caption>"); html.append("<tr><th>").append("Oid").append("</th>"); html.append("<th>").append(WebPageUtil.FIRSTNAME).append("</th>"); html.append("<th>").append(WebPageUtil.LASTNAME).append("</th>"); html.append("<th>").append(WebPageUtil.BIRTHDAY).append("</th>"); html.append("<th>").append(WebPageUtil.SALARY).append("</th></tr>"); for( final Employee emp : employeeList) { html.append("<tr><td>").append(emp.getOid().toString()).append("</td>"); html.append("<td>").append(emp.getFirstName()).append("</td>"); html.append("<td>").append(emp.getLastName()).append("</td>"); html.append("<td>").append(emp.getBirthdate().toString()).append("</td>"); html.append("<td>").append(emp.getSalary().toString()).append("</td></tr>"); } html.append("</table>").append("<br>"); html.append("<br>").append("<a href= 'http://localhost:16000/'>Welcome Employee</a><br>"); html.append("</body>"); return html.toString(); } private String buildPageBottom() { final StringBuilder html = new StringBuilder(); html.append("</html>"); return html.toString(); } @Override() public String buildPage() { final StringBuilder html = new StringBuilder(); return html.append(buildPageHead()).append(buildPageBody()).append(buildPageBottom()).toString(); } public List<Employee> getEmployeeList() { final List<Employee> all = employeeDAO.findAll(); return all; } }
true
71c69b9051d3f3f1aea8bf8e1aba8b161155b1a7
Java
crate/crate
/server/src/main/java/io/crate/metadata/functions/SignatureBinder.java
UTF-8
26,651
1.796875
2
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
/* * Licensed to Crate.io GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.metadata.functions; import static io.crate.metadata.functions.TypeVariableConstraint.typeVariableOfAnyType; import static io.crate.types.TypeCompatibility.getCommonType; import static java.lang.String.format; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toMap; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.jetbrains.annotations.Nullable; import org.apache.logging.log4j.Logger; import org.elasticsearch.common.logging.Loggers; import io.crate.common.collections.Lists2; import io.crate.types.BitStringType; import io.crate.types.DataType; import io.crate.types.DataTypes; import io.crate.types.ParameterTypeSignature; import io.crate.types.TypeSignature; import io.crate.types.UndefinedType; /** * Determines whether, and how, a callsite matches a generic function signature. * Which is equivalent to finding assignments for the variables in the generic signature, * such that all of the function's declared parameters are super types of the corresponding * arguments, and also satisfy the declared constraints (such as a given type parameter must * be of the same type or not) */ public class SignatureBinder { // 4 is chosen arbitrarily here. This limit is set to avoid having infinite loops in iterative solving. private static final int SOLVE_ITERATION_LIMIT = 4; private static final Logger LOGGER = Loggers.getLogger(SignatureBinder.class); public static SignatureBinder withPrecedenceOnly(Signature declaredSignature) { return new SignatureBinder(declaredSignature, CoercionType.PRECEDENCE_ONLY); } private final Signature declaredSignature; private final CoercionType coercionType; private final Map<String, TypeVariableConstraint> typeVariableConstraints; /** * Types where we should ignore precision details while signature matching. * This is done because functions are registered without precision details. * * E.g. `foo(text)` should also match on `foo(x)` where `x` has `varchar(10)` **/ private static final Set<String> ALLOW_BASENAME_MATCH = Set.of( DataTypes.NUMERIC.getName(), DataTypes.STRING.getName(), DataTypes.CHARACTER.getName(), BitStringType.NAME ); public SignatureBinder(Signature declaredSignature, CoercionType coercionType) { this.declaredSignature = declaredSignature; this.coercionType = coercionType; this.typeVariableConstraints = declaredSignature.getBindingInfo().getTypeVariableConstraints().stream() .collect(toMap(TypeVariableConstraint::getName, identity())); } @Nullable public BoundSignature bind(List<DataType<?>> actualArgumentTypes) { BoundVariables boundVariables = bindVariables(actualArgumentTypes); if (boundVariables == null) { return null; } int arity = actualArgumentTypes.size(); List<TypeSignature> argumentSignatures; var bindingInfo = declaredSignature.getBindingInfo(); assert bindingInfo != null : "Expecting the signature's binding info to be not null"; if (bindingInfo.isVariableArity()) { argumentSignatures = expandVarargFormalTypeSignature( declaredSignature.getArgumentTypes(), bindingInfo.getVariableArityGroup(), typeVariableConstraints, arity); if (argumentSignatures == null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Size of argument types does not match a multiple of the defined variable arguments"); } return null; } } else { if (declaredSignature.getArgumentTypes().size() != arity) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Size of argument types does not match given arity"); } return null; } argumentSignatures = declaredSignature.getArgumentTypes(); } List<TypeSignature> boundArgumentSignatures = applyBoundVariables(argumentSignatures, boundVariables); TypeSignature boundReturnTypeSignature = applyBoundVariables(declaredSignature.getReturnType(), boundVariables); return new BoundSignature( Lists2.map(boundArgumentSignatures, TypeSignature::createType), boundReturnTypeSignature.createType() ); } @Nullable public BoundVariables bindVariables(List<DataType<?>> actualArgumentTypes) { ArrayList<TypeConstraintSolver> constraintSolvers = new ArrayList<>(); if (!appendConstraintSolversForArguments(constraintSolvers, actualArgumentTypes)) { return null; } return iterativeSolve(Collections.unmodifiableList(constraintSolvers)); } private static List<TypeSignature> applyBoundVariables(List<TypeSignature> typeSignatures, BoundVariables boundVariables) { ArrayList<TypeSignature> builder = new ArrayList<>(); for (TypeSignature typeSignature : typeSignatures) { builder.add(applyBoundVariables(typeSignature, boundVariables)); } return Collections.unmodifiableList(builder); } private static TypeSignature applyBoundVariables(TypeSignature typeSignature, BoundVariables boundVariables) { String baseType = typeSignature.getBaseTypeName(); if (boundVariables.containsTypeVariable(baseType)) { if (typeSignature.getParameters().isEmpty() == false) { throw new IllegalStateException("Type parameters cannot have parameters"); } var boundTS = boundVariables.getTypeVariable(baseType).getTypeSignature(); if (typeSignature instanceof ParameterTypeSignature p) { return new ParameterTypeSignature(p.unescapedParameterName(), boundTS); } return boundTS; } List<TypeSignature> parameters = Lists2.map( typeSignature.getParameters(), typeSignatureParameter -> applyBoundVariables(typeSignatureParameter, boundVariables)); if (typeSignature instanceof ParameterTypeSignature p) { return new ParameterTypeSignature( p.unescapedParameterName(), new TypeSignature(baseType, parameters) ); } return new TypeSignature(baseType, parameters); } private boolean appendConstraintSolversForArguments(List<TypeConstraintSolver> resultBuilder, List<DataType<?>> argumentTypes) { var declaredBindingInfo = declaredSignature.getBindingInfo(); assert declaredBindingInfo != null : "Expecting the signature's binding info to be not null"; boolean variableArity = declaredBindingInfo.isVariableArity(); List<TypeSignature> formalTypeSignatures = declaredSignature.getArgumentTypes(); if (variableArity) { int variableGroupCount = declaredBindingInfo.getVariableArityGroup().size(); int variableArgumentCount = variableGroupCount > 0 ? variableGroupCount : 1; if (argumentTypes.size() <= formalTypeSignatures.size() - variableArgumentCount) { if (LOGGER.isTraceEnabled()) { LOGGER.trace( "Given signature size {} is not smaller than minimum variableArity of formal signature size {}", argumentTypes.size(), formalTypeSignatures.size() - variableArgumentCount); } return false; } formalTypeSignatures = expandVarargFormalTypeSignature( formalTypeSignatures, declaredBindingInfo.getVariableArityGroup(), typeVariableConstraints, argumentTypes.size()); if (formalTypeSignatures == null) { // var args expanding detected a no-match return false; } } if (formalTypeSignatures.size() != argumentTypes.size()) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Given signature size {} does not match formal signature size {}", argumentTypes.size(), formalTypeSignatures.size()); } return false; } for (int i = 0; i < formalTypeSignatures.size(); i++) { appendTypeRelationshipConstraintSolver(resultBuilder, formalTypeSignatures.get(i), argumentTypes.get(i), coercionType); } return appendConstraintSolvers(resultBuilder, formalTypeSignatures, argumentTypes, coercionType); } private boolean appendConstraintSolvers(List<TypeConstraintSolver> resultBuilder, List<? extends TypeSignature> formalTypeSignatures, List<DataType<?>> actualArgumentTypes, CoercionType coercionType) { if (formalTypeSignatures.size() != actualArgumentTypes.size()) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Given signature size {} does not match formal signature size {}", actualArgumentTypes.size(), formalTypeSignatures.size()); } return false; } for (int i = 0; i < formalTypeSignatures.size(); i++) { if (!appendConstraintSolvers(resultBuilder, formalTypeSignatures.get(i), actualArgumentTypes.get(i), coercionType)) { return false; } } return true; } private boolean appendConstraintSolvers(List<TypeConstraintSolver> resultBuilder, TypeSignature formalTypeSignature, DataType<?> actualType, CoercionType coercionType) { if (formalTypeSignature.getParameters().isEmpty()) { TypeVariableConstraint typeVariableConstraint = typeVariableConstraints.get(formalTypeSignature.getBaseTypeName()); if (typeVariableConstraint == null) { return true; } resultBuilder.add(new TypeParameterSolver(formalTypeSignature.getBaseTypeName(), actualType)); return true; } List<DataType<?>> actualTypeParameters; if (UndefinedType.ID == actualType.id()) { actualTypeParameters = Collections.nCopies(formalTypeSignature.getParameters().size(), UndefinedType.INSTANCE); } else { actualTypeParameters = actualType.getTypeParameters(); } return appendConstraintSolvers( resultBuilder, Collections.unmodifiableList(formalTypeSignature.getParameters()), actualTypeParameters, coercionType); } private void appendTypeRelationshipConstraintSolver(List<TypeConstraintSolver> resultBuilder, TypeSignature formalTypeSignature, DataType<?> actualType, CoercionType coercionType) { Set<String> typeVariables = typeVariablesOf(formalTypeSignature); resultBuilder.add(new TypeRelationshipConstraintSolver( formalTypeSignature, typeVariables, actualType, coercionType)); } private Set<String> typeVariablesOf(TypeSignature typeSignature) { if (typeVariableConstraints.containsKey(typeSignature.getBaseTypeName())) { return Set.of(typeSignature.getBaseTypeName()); } HashSet<String> variables = new HashSet<>(); for (TypeSignature parameter : typeSignature.getParameters()) { variables.addAll(typeVariablesOf(parameter)); } return variables; } @Nullable private BoundVariables iterativeSolve(List<TypeConstraintSolver> constraints) { BoundVariables.Builder boundVariablesBuilder = BoundVariables.builder(); for (int i = 0; true; i++) { if (i == SOLVE_ITERATION_LIMIT) { throw new IllegalStateException(format( Locale.ENGLISH, "SignatureBinder.iterativeSolve does not converge after %d iterations.", SOLVE_ITERATION_LIMIT)); } SolverReturnStatusMerger statusMerger = new SolverReturnStatusMerger(); for (TypeConstraintSolver constraint : constraints) { var constraintStatus = constraint.update(boundVariablesBuilder); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Status after updating constraint={}: {}", constraint, constraintStatus); } statusMerger.add(constraintStatus); if (statusMerger.getCurrent() == SolverReturnStatus.UNSOLVABLE) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Status merger resulted in UNSOLVABLE state"); } return null; } } switch (statusMerger.getCurrent()) { case UNCHANGED_SATISFIED: break; case UNCHANGED_NOT_SATISFIED: return null; case CHANGED: continue; default: case UNSOLVABLE: throw new UnsupportedOperationException("Signature binding unsolvable"); } break; } BoundVariables boundVariables = boundVariablesBuilder.build(); if (!allTypeVariablesBound(boundVariables)) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Not all variables are bound. Defined variables={}, bound={}", typeVariableConstraints, boundVariables); } return null; } return boundVariables; } private boolean allTypeVariablesBound(BoundVariables boundVariables) { return boundVariables.getTypeVariableNames().equals(typeVariableConstraints.keySet()); } @Nullable private static List<TypeSignature> expandVarargFormalTypeSignature(List<TypeSignature> formalTypeSignatures, List<TypeSignature> variableArityGroup, Map<String, TypeVariableConstraint> typeVariableConstraints, int actualArity) { int variableArityGroupCount = variableArityGroup.size(); if (variableArityGroupCount > 0 && actualArity % variableArityGroupCount != 0) { // no match return null; } int arityCountIncludedInsideFormalSignature = variableArityGroupCount == 0 ? 1 : variableArityGroupCount; int variableArityArgumentsCount = actualArity - formalTypeSignatures.size() + arityCountIncludedInsideFormalSignature; if (variableArityArgumentsCount == 0) { return formalTypeSignatures.subList(0, formalTypeSignatures.size() - arityCountIncludedInsideFormalSignature); } if (variableArityArgumentsCount == arityCountIncludedInsideFormalSignature) { return formalTypeSignatures; } if (variableArityArgumentsCount > arityCountIncludedInsideFormalSignature && formalTypeSignatures.isEmpty()) { throw new IllegalArgumentException("Found variable argument(s) but list of formal type signatures is empty"); } ArrayList<TypeSignature> builder = new ArrayList<>(formalTypeSignatures); if (variableArityGroup.isEmpty()) { TypeSignature lastTypeSignature = formalTypeSignatures.get(formalTypeSignatures.size() - 1); for (int i = 1; i < variableArityArgumentsCount; i++) { addVarArgTypeSignature(lastTypeSignature, typeVariableConstraints, builder, i); } } else { for (int i = 0; i < variableArityArgumentsCount - formalTypeSignatures.size(); ) { i += variableArityGroupCount; for (var typeSignature : variableArityGroup) { addVarArgTypeSignature(typeSignature, typeVariableConstraints, builder, i); } } } return Collections.unmodifiableList(builder); } private static void addVarArgTypeSignature(TypeSignature typeSignature, Map<String, TypeVariableConstraint> typeVariableConstraints, List<TypeSignature> builder, int actualArity) { TypeVariableConstraint typeVariableConstraint = resolveTypeVariableConstraint( typeSignature, typeVariableConstraints ); if (typeVariableConstraint != null && typeVariableConstraint.isAnyAllowed()) { // Type variables defaults to be bound to the same type. // To support independent variable type arguments, each vararg must be bound to a dedicated type variable. var newConstraintName = "_generated_" + typeVariableConstraint + actualArity; var newTypeSignature = replaceTypeVariable( typeSignature, typeVariableConstraint.getName(), newConstraintName ); typeVariableConstraints.put(newConstraintName, typeVariableOfAnyType(newConstraintName)); builder.add(newTypeSignature); } else { builder.add(typeSignature); } } @Nullable private static TypeVariableConstraint resolveTypeVariableConstraint( TypeSignature signature, Map<String, TypeVariableConstraint> constraints) { if (signature.getParameters().isEmpty()) { return constraints.get(signature.getBaseTypeName()); } else { for (var parameterSignature : signature.getParameters()) { var constraint = resolveTypeVariableConstraint(parameterSignature, constraints); if (constraint != null) { return constraint; } } return null; } } private static TypeSignature replaceTypeVariable(TypeSignature signature, String oldVar, String newVar) { if (signature.getBaseTypeName().equalsIgnoreCase(oldVar)) { return new TypeSignature(newVar, signature.getParameters()); } else { ArrayList<TypeSignature> parameters = new ArrayList<>(); for (var parameter : signature.getParameters()) { parameters.add(replaceTypeVariable(parameter, oldVar, newVar)); } return new TypeSignature(signature.getBaseTypeName(), parameters); } } private static boolean satisfiesCoercion(CoercionType coercionType, DataType<?> fromType, TypeSignature toTypeSignature) { switch (coercionType) { case FULL: return fromType.isConvertableTo(toTypeSignature.createType(), false); case PRECEDENCE_ONLY: var toType = toTypeSignature.createType(); if (checkParametrizedTypes(fromType.getTypeSignature(), toTypeSignature)) { return true; } return fromType.equals(toType) || (fromType.isConvertableTo(toTypeSignature.createType(), false) && toType.precedes(fromType)); case NONE: default: var fromTypeSignature = fromType.getTypeSignature(); if (checkParametrizedTypes(fromTypeSignature, toTypeSignature)) { return true; } return fromTypeSignature.equals(toTypeSignature); } } private static boolean checkParametrizedTypes(TypeSignature fromTypeSignature, TypeSignature toTypeSignature) { // We always register numeric and text arguments without precision and scale thus the parameters // should not be checked while signature matching. String baseTypeName = fromTypeSignature.getBaseTypeName(); return ALLOW_BASENAME_MATCH.contains(baseTypeName) && baseTypeName.equals(toTypeSignature.getBaseTypeName()); } private interface TypeConstraintSolver { SolverReturnStatus update(BoundVariables.Builder bindings); } private enum SolverReturnStatus { UNCHANGED_SATISFIED, UNCHANGED_NOT_SATISFIED, CHANGED, UNSOLVABLE, } private static class SolverReturnStatusMerger { // This class gives the overall status when multiple status are seen from different parts. // The logic can be summarized as finding the right most item (based on the list below) seen so far: // UNCHANGED_SATISFIED, UNCHANGED_NOT_SATISFIED, CHANGED, UNSOLVABLE // If no item was seen ever, it provides UNCHANGED_SATISFIED. private SolverReturnStatus current = SolverReturnStatus.UNCHANGED_SATISFIED; public void add(SolverReturnStatus newStatus) { if (newStatus.ordinal() > current.ordinal()) { current = newStatus; } } public SolverReturnStatus getCurrent() { return current; } } private static class TypeParameterSolver implements TypeConstraintSolver { private final String typeParameter; private final DataType<?> actualType; public TypeParameterSolver(String typeParameter, DataType<?> actualType) { this.typeParameter = typeParameter; this.actualType = actualType; } @Override public SolverReturnStatus update(BoundVariables.Builder bindings) { if (!bindings.containsTypeVariable(typeParameter)) { bindings.setTypeVariable(typeParameter, actualType); return SolverReturnStatus.CHANGED; } DataType<?> originalType = bindings.getTypeVariable(typeParameter); DataType<?> commonType = getCommonType(originalType, actualType); if (commonType == null) { return SolverReturnStatus.UNSOLVABLE; } if (commonType.equals(originalType)) { return SolverReturnStatus.UNCHANGED_SATISFIED; } bindings.setTypeVariable(typeParameter, commonType); return SolverReturnStatus.CHANGED; } @Override public String toString() { return "TypeParameterSolver{" + "typeParameter='" + typeParameter + "'" + ", actualType=" + actualType + '}'; } } private static class TypeRelationshipConstraintSolver implements TypeConstraintSolver { private final TypeSignature superTypeSignature; private final Set<String> typeVariables; private final DataType<?> actualType; private final CoercionType coercionType; public TypeRelationshipConstraintSolver(TypeSignature superTypeSignature, Set<String> typeVariables, DataType<?> actualType, CoercionType coercionType) { this.superTypeSignature = superTypeSignature; this.typeVariables = typeVariables; this.actualType = actualType; this.coercionType = coercionType; } @Override public SolverReturnStatus update(BoundVariables.Builder bindings) { for (String variable : typeVariables) { if (!bindings.containsTypeVariable(variable)) { return SolverReturnStatus.UNCHANGED_NOT_SATISFIED; } } TypeSignature boundSignature = applyBoundVariables(superTypeSignature, bindings.build()); if (satisfiesCoercion(coercionType, actualType, boundSignature)) { return SolverReturnStatus.UNCHANGED_SATISFIED; } return SolverReturnStatus.UNCHANGED_NOT_SATISFIED; } @Override public String toString() { return "TypeRelationshipConstraintSolver{" + "superTypeSignature=" + superTypeSignature + ", typeVariables=" + typeVariables + ", actualType=" + actualType + ", allowCoercion=" + coercionType + '}'; } } public enum CoercionType { NONE, PRECEDENCE_ONLY, FULL } }
true
aabd70a0f23480791d7a3a5298216a35a5696e5b
Java
zhongxingyu/Seer
/Diff-Raw-Data/20/20_06be098d11d4bbd3bd45188424c7e7629619103b/SamplingPointPosition/20_06be098d11d4bbd3bd45188424c7e7629619103b_SamplingPointPosition_s.java
UTF-8
2,634
2.546875
3
[]
no_license
package de.hswt.hrm.inspection.ui.grid; import org.eclipse.swt.graphics.Rectangle; import com.google.common.base.Preconditions; import de.hswt.hrm.inspection.model.SamplingPointType; import de.hswt.hrm.scheme.model.Direction; import de.hswt.hrm.scheme.model.RenderedComponent; import de.hswt.hrm.scheme.model.Scheme; import de.hswt.hrm.scheme.model.SchemeComponent; import de.hswt.hrm.scheme.ui.SchemeGridItem; public class SamplingPointPosition { private static class Placement{ int x; int y; int width; int height; Direction direction; public Placement(int x, int y, int width, int height, Direction direction) { super(); this.x = x; this.y = y; this.width = width; this.height = height; this.direction = direction; } public Rectangle getRectangle(){ return new Rectangle(x, y, width, height); } } public static SchemeGridItem getSamplingPoint( SamplingPoints points, SamplingPointType type, Scheme scheme, SchemeComponent orig){ Placement pos = null; for(Placement r : getPlacements(orig)){ if(canPlace(scheme, r)){ pos = r; break; } } Preconditions.checkArgument(pos != null, "Can't place sampling point"); RenderedComponent rc = points.getRenderedComponent(type, isEven(orig, pos.direction)); SchemeComponent comp = new SchemeComponent(scheme, pos.x, pos.y, pos.direction, rc.getComponent()); return new SchemeGridItem(rc, comp); } private static boolean isEven(SchemeComponent c, Direction dir){ int edge; switch(dir){ case upDown: case downUp: edge = c.getWidth(); break; case leftRight: case rightLeft: edge = c.getHeight(); break; default: throw new RuntimeException("Internal Error"); } return edge % 2 == 1; } private static boolean canPlace(Scheme scheme, Placement r){ for(SchemeComponent c : scheme.getSchemeComponents()){ Rectangle r2 = new Rectangle(c.getX(), c.getY(), c.getWidth(), c.getHeight()); if(r.getRectangle().intersects(r2)){ return false; } } return true; } private static Placement[] getPlacements(SchemeComponent c){ int xm = c.getX() + c.getWidth() / 2; int ym = c.getY() + c.getHeight() / 2; return new Placement[] { new Placement(xm, c.getY() + c.getHeight(), 2, 1, Direction.downUp), //top new Placement(xm, c.getY() - 1, 2, 1, Direction.upDown), //bot new Placement(c.getX() - 1, ym, 1, 2, Direction.leftRight), //left new Placement(c.getX() + c.getWidth(), ym, 1, 2, Direction.rightLeft) //right }; } }
true
a8cd72b45fb40727b51c1677ea5caa2db66b77ab
Java
bx2j/vue-springboot-toy01
/src/test/java/com/toy/board/VueSpringbootToy01ApplicationTests.java
UTF-8
2,236
2.109375
2
[ "MIT" ]
permissive
package com.toy.board; import static org.junit.Assert.assertEquals; import java.sql.Connection; import java.sql.DriverManager; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import com.nhncorp.lucy.security.xss.XssFilter; @RunWith(SpringRunner.class) @SpringBootTest @TestPropertySource("classpath:./application.properties") public class VueSpringbootToy01ApplicationTests { private Logger log = LoggerFactory.getLogger(getClass()); @Value("${spring.datasource.driver-class-name}") private String DRIVER; @Value("${spring.datasource.url}") private String URL; @Value("${spring.datasource.username}") private String USERNAME; @Value("${spring.datasource.password}") private String PASSWORD; private String sql = "show databases"; @Test public void contextLoads() throws Exception { Class.forName(DRIVER); try (Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD)) { log.info("======================OK======================"); log.info(" " + con.toString() + " "); log.info(" " + con.prepareStatement(sql).execute() + " "); log.info("=============================================="); } catch(Exception e) { log.debug(e.getMessage()); } } @Test public void pairQuoteCheckOtherCase() { XssFilter filter = XssFilter.getInstance("lucy-xss-superset.xml"); String dirty = "<img src=\"<img src=1\\ onerror=alert(1234)>\" onerror=\"alert('XSS')\">"; String expected = "<img src=\"\"><!-- Not Allowed Attribute Filtered ( onerror=alert(1234)) --><img src=1\\>\" onerror=\"alert('XSS')\"&gt;"; String actual = filter.doFilter(dirty); assertEquals(expected, actual); dirty = "<img src='<img src=1\\ onerror=alert(1234)>\" onerror=\"alert('XSS')\">"; expected = "<img src=''><!-- Not Allowed Attribute Filtered ( onerror=alert(1234)) --><img src=1\\>\" onerror=\"alert('XSS')\"&gt;"; actual = filter.doFilter(dirty); assertEquals(expected, actual); } }
true
3b6a5cb18a851986f8c4fcabe93da406bfc976f7
Java
1097919195/programDemo
/TextToSpeech/zxingScan/src/com/xsf/zxing/WebResultActivity.java
UTF-8
1,262
2.296875
2
[]
no_license
package com.xsf.zxing; import android.app.Activity; import android.os.Bundle; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import static com.xsf.zxing.R.id.webview; /** * Created by asus-pc on 2017/10/10. */ public class WebResultActivity extends Activity{ private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web_result); webView = (WebView) findViewById(webview); Bundle extras = getIntent().getExtras(); if (null != extras) { String result = extras.getString("result"); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); webView.getSettings().setSupportMultipleWindows(true); webView.setWebViewClient(new WebViewClient());//防止有的网页重定向跳转到浏览器(重定向就是,在网页上设置一个约束条件,条件满足,就自动转入到其它网页、网址) webView.setWebChromeClient(new WebChromeClient()); webView.loadUrl(result); } } }
true
715cf035e3bb3399194e035cf61efe0c33e398ad
Java
hieunv2/student_manager_swing
/QLDSV/src/View/DangKyMonDay.java
UTF-8
11,702
2.15625
2
[]
no_license
package View; import Controller.GiangVien_MonDayController; import Controller.HocKyController; import Controller.LoginController; import Controller.MonHocController; import Controller.MonHoc_HocKyController; import connectsql.ConnectToDatabase; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.HeadlessException; import java.awt.event.ActionEvent; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableModel; public class DangKyMonDay extends JPanel { JLabel jLabelHocKy; JLabel jLabelTitle; JLabel jLabelDS; JTable TableDSMD; JButton btnSua; JButton btnThem; JButton btnThoat; JButton btnXoa; JLabel jLabelTenMon; JComboBox<String> txtHocKy; JComboBox<String> txtTenMon; private Connection conn; private ArrayList<String> listDSMD; private ArrayList<String> listMaHK; private ArrayList<String> listMaMH; DefaultTableModel model; public DangKyMonDay() throws SQLException{ initComponents(); // setTitle("Đăng ký môn dạy"); // setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(550, 100,1200,800); // setLocationRelativeTo(null); try { conn = ConnectToDatabase.ConnectToDatabase(); } catch (Exception e) { } // listDSMD= new GiangVien_MonDayController().getListGV_MD(); listMaHK = new HocKyController().DSHocKy(); //listMaMH = new MonHoc_HocKyController().getListMaMH DSMaHK(); txtHocKy.addActionListener((ActionEvent e) -> { listMaMH = new MonHoc_HocKyController().getListMaMH(txtHocKy.getSelectedItem().toString()); //Hiển thị dữ liệu từ cơ sở dữ liệu lên Jtable: Thông tin các môn mà Giảng viên đăng ký theo kỳ try { listDSMD = new GiangVien_MonDayController().getMonDay(LoginController.maTK,txtHocKy.getSelectedItem().toString()); } catch (SQLException ex) { Logger.getLogger(DangKyMonDay.class.getName()).log(Level.SEVERE, null, ex); } DSTenMH(); // showDSGV_MD(); }); //showDSMD(); } private void initComponents() { // JPanel panel = new JPanel(); this.setLayout(null); // panel.setPreferredSize(new Dimension(1200,800)); jLabelTitle = new JLabel("ĐĂNG KÝ MÔN DẠY"); jLabelTitle.setFont(new Font("Time New Roman", Font.BOLD, 24)); jLabelTitle.setForeground(new Color(255, 0, 0)); jLabelTitle.setBounds(325, 30, 520, 44); jLabelTitle.setHorizontalAlignment(SwingConstants.CENTER); add(jLabelTitle); jLabelHocKy = new JLabel("Học kỳ"); jLabelHocKy.setFont(new Font("Time New Roman", Font.PLAIN, 16)); jLabelHocKy.setBounds(150, 150, 150, 30); add(jLabelHocKy); jLabelTenMon= new JLabel("Môn học"); jLabelTenMon.setFont(new Font("Time New Roman", Font.PLAIN, 16)); jLabelTenMon.setBounds(150, 220, 150, 30); add(jLabelTenMon); txtHocKy = new JComboBox<>(); txtHocKy.setFont(new Font("Time New Roman", Font.PLAIN, 16)); txtHocKy.setBounds(225, 150, 250, 30); add(txtHocKy); txtTenMon = new JComboBox<>(); txtTenMon.setFont(new Font("Time New Roman", Font.PLAIN, 16)); txtTenMon.setBounds(225, 220, 250, 30); add(txtTenMon); btnThem = new JButton("Đăng ký"); btnThem.setFont(new Font("Time New Roman", Font.PLAIN, 16)); btnThem.setIcon(new ImageIcon("D:\\QLDSV\\src\\View\\images\\plus.png")); btnThem.setBounds(600, 150, 125, 30); add(btnThem); btnThem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { btnThemActionPerformed(evt); } catch (SQLException ex) { Logger.getLogger(DangKyMonDay.class.getName()).log(Level.SEVERE, null, ex); } } }); /* btnSua = new JButton("Sửa"); btnSua.setFont(new Font("Time New Roman", Font.PLAIN, 16)); btnSua.setIcon(new ImageIcon("D:\\QLDSV\\src\\View\\images\\updated.png")); btnSua.setBounds(850, 150, 125, 30); add(btnSua); btnSua.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSuaActionPerformed(evt); } }); */ btnXoa = new JButton("Hủy ĐK"); btnXoa.setFont(new Font("Time New Roman", Font.PLAIN, 16)); btnXoa.setIcon(new ImageIcon("D:\\QLDSV\\src\\View\\images\\delete.png")); btnXoa.setBounds(600, 220, 125, 30); add(btnXoa); btnXoa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { try { btnXoaActionPerformed(evt); } catch (SQLException ex) { Logger.getLogger(DangKyMonDay.class.getName()).log(Level.SEVERE, null, ex); } } }); /* btnThoat = new JButton("Thoát"); btnThoat.setFont(new Font("Time New Roman", Font.PLAIN, 16)); btnThoat.setIcon(new ImageIcon("D:\\QLDSV\\src\\View\\images\\multiply.png")); btnThoat.setBounds(850, 150, 125, 30); add(btnThoat); btnThoat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnThoatActionPerformed(evt); } }); */ jLabelDS = new JLabel("Danh sách"); jLabelDS.setFont(new Font("Time New Roman", Font.PLAIN, 20)); jLabelDS.setForeground(new Color(0, 204, 204)); jLabelDS.setBounds(150, 300, 150, 30); add(jLabelDS); createTable(); } private void btnThemActionPerformed(ActionEvent evt) throws SQLException { try { String maHK= txtHocKy.getSelectedItem().toString(); if ((new HocKyController().hkHienTai().compareTo(maHK))!=0) { JOptionPane.showMessageDialog(this, "Học kỳ hiện tại là: "+new HocKyController().hkHienTai()+". Hãy chọn đúng học kỳ"); } else { String maMH= new MonHocController().showMaMonHoc(txtTenMon.getSelectedItem().toString()); int id= new MonHoc_HocKyController().getId(maMH ,maHK); String matk= LoginController.maTK; if( new GiangVien_MonDayController().Them(id, matk)) { JOptionPane.showMessageDialog(this,"Đăng ký thành công"); listDSMD = new GiangVien_MonDayController().getMonDay(LoginController.maTK, maHK); showDSGV_MD(); } else{ JOptionPane.showMessageDialog(this, "Đăng ký thất bại"); } } } catch (HeadlessException | SQLException e) { } } private void btnXoaActionPerformed(ActionEvent evt) throws SQLException { try { int removeRow = TableDSMD.getSelectedRow(); if(removeRow < 0){ JOptionPane.showMessageDialog(this, "Hãy chọn môn cần hủy"); }else { int select = JOptionPane.showOptionDialog(null, "Bạn chắc chắn muốn hủy ?", "Hủy đăng ký", 0, JOptionPane.YES_NO_OPTION, null, null, 1); if (select == 0) { String maHK = TableDSMD.getValueAt(removeRow,0).toString(); String tenMH = TableDSMD.getValueAt(removeRow,1).toString(); String maMH = new MonHocController().showMaMonHoc(tenMH); int id = new MonHoc_HocKyController().getId(maMH ,maHK); if( new GiangVien_MonDayController().Xoa(id,LoginController.maTK)){ JOptionPane.showMessageDialog(this,"Hủy đăng ký thành công."); listDSMD = new GiangVien_MonDayController().getMonDay(LoginController.maTK, maHK); showDSGV_MD(); } else{ JOptionPane.showMessageDialog(this, "Hủy đăng ký thất bại."); } } } } catch (java.lang.ArrayIndexOutOfBoundsException e) { JOptionPane.showMessageDialog(null, e.getMessage()); } } /* private void btnThoatActionPerformed(ActionEvent evt) { this.dispose(); }*/ private void createTable() { // getContentPane().setLayout(null); model = new DefaultTableModel(); TableDSMD = new JTable(model); TableDSMD.setFont(new Font("Time New Roman", Font.PLAIN, 16)); model.addColumn("Học kỳ"); model.addColumn("Môn học"); JScrollPane sc = new JScrollPane(TableDSMD, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); sc.setBounds(150,350,900,300); // getContentPane().add(sc); this.add(sc, BorderLayout.CENTER); } private void showDSGV_MD(){ model.setRowCount(0); for (int i = 0; i < listDSMD.size(); i++) { model.addRow(new Object[]{ txtHocKy.getSelectedItem().toString(),listDSMD.get(i) }); } } /* public void restForm(){ txtHocKy.setSelectedItem(""); txtTenMon.setSelectedItem(""); } */ /* private void TableDSMDMouseClicked(MouseEvent evt) { int row = TableDSMD.getSelectedRow(); System.out.println(row); if(row >=0){ String maHK = TableDSMD.getValueAt(row,0).toString(); String tenMH = TableDSMD.getValueAt(row,1).toString(); } } */ private void DSMaHK() { try { for (int i = 0; i < listMaHK.size(); i++) { txtHocKy.addItem(listMaHK.get(i)); } } catch (java.lang.NullPointerException e) { JOptionPane.showMessageDialog(this, "Lỗi1"); } } private void DSTenMH() { try { txtTenMon.removeAllItems(); for (int i = 0; i < listMaMH.size(); i++) { String tenMH = new MonHocController().showTenMonHoc(listMaMH.get(i)); txtTenMon.addItem(tenMH); } } catch (java.lang.NullPointerException e) { JOptionPane.showMessageDialog(this, "Lỗi2"); } } }
true
56bd652f411ef82de1e1d6207d84c896a23a6d89
Java
sarpreetsingh3131/lime-assignment
/src/main/java/lime/assignment/model/TimeSlot.java
UTF-8
1,115
2.515625
3
[ "MIT" ]
permissive
package lime.assignment.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; import java.time.Duration; import java.time.LocalDateTime; @NoArgsConstructor @RequiredArgsConstructor @Data @JsonPropertyOrder({"startDate", "endDate", "startTime", "endTime"}) public class TimeSlot { @NonNull @JsonIgnore private LocalDateTime start; @NonNull @JsonIgnore private LocalDateTime end; @NonNull @JsonIgnore private Boolean isFree; @JsonIgnore public Integer getDuration() { return (int) Duration.between(start, end).toMinutes(); } public String getStartDate() { return start.toLocalDate().toString(); } public String getEndDate() { return end.toLocalDate().toString(); } public String getStartTime() { return start.toLocalTime().toString(); } public String getEndTime() { return end.toLocalTime().toString(); } }
true
93c7e81ae3f224045ba297acb02f2934a2b5b916
Java
hussainbzu344/backend
/src/main/java/com/edu/autoclass/util/DbConfig.java
UTF-8
3,137
2.5625
3
[]
no_license
package com.edu.autoclass.util; import com.edu.autoclass.bean.EntryPoint; import com.edu.autoclass.bean.Framework; import com.edu.autoclass.bean.ProjectType; import java.sql.*; import java.util.ArrayList; import java.util.List; public class DbConfig { Connection conn; public DbConfig() { try { conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/automatic_classification?characterEncoding=utf8", "root", "multan90"); } catch (SQLException e) { e.printStackTrace(); } } public List<ProjectType> getType(int id) { List<ProjectType> projectType = new ArrayList<ProjectType>(); try { Statement stmt = conn.createStatement(); String strSelect = "select * from project_type where id=" + id; ResultSet rset = stmt.executeQuery(strSelect); while (rset.next()) { // Move the cursor to the next row, return false if no more row ProjectType type = new ProjectType(); type.setId(rset.getInt("id")); type.setName(rset.getString("name")); type.setType(rset.getString("type")); projectType.add(type); } } catch (SQLException ex) { ex.printStackTrace(); } return projectType; } public List<Framework> getFramework(String name) { List<Framework> frameworks = new ArrayList<Framework>(); try { Statement stmt = conn.createStatement(); String strSelect = "select * from framework where ('" + name + "' like concat('%',core_library,'%'))"; ResultSet rset = stmt.executeQuery(strSelect); while (rset.next()) { Framework framework = new Framework(); framework.setId(rset.getInt("id")); framework.setName(rset.getString("name")); framework.setCoreLibrary(rset.getString("core_library")); framework.setTypeId(rset.getInt("type_id")); frameworks.add(framework); } } catch (SQLException ex) { ex.printStackTrace(); } return frameworks; } public List<EntryPoint> getEnteryPointsById(int id) { List<EntryPoint> entryPoints = new ArrayList<>(); try { Statement stmt = conn.createStatement(); String strSelect = "select * from entry_point where framework_id=" + id; ResultSet rset = stmt.executeQuery(strSelect); while (rset.next()) { EntryPoint entryPoint = new EntryPoint(); entryPoint.setId(rset.getInt("id")); entryPoint.setName(rset.getString("name")); entryPoint.setType(rset.getString("type")); entryPoint.setLocation(rset.getString("location")); entryPoint.setFrameworkId(rset.getInt("framework_id")); entryPoints.add(entryPoint); } } catch (SQLException ex) { ex.printStackTrace(); } return entryPoints; } }
true
420125f37ca8b0eb972f3b6689860606403e7063
Java
MyvinB/Algo-Learn
/src/Contest/Upsolve/LC2261.java
UTF-8
612
2.75
3
[]
no_license
package Contest.Upsolve; import java.util.HashSet; public class LC2261 { public static void main(String[] args) { } public int countDistinct(int[] nums, int k, int p) { HashSet<String> set = new HashSet<>(); for(int i=0;i<nums.length;i++){ int count = 0; StringBuilder sb = new StringBuilder(); for(int j=i;j<nums.length;j++){ if(nums[i]%p==0) count++; if(count>k) break; sb.append(nums[j]+"_"); set.add(sb.toString()); } } return set.size(); } }
true
0f368635d4316daf42a76dd9c9cb153eeaadc68f
Java
Hethaiklon/Little_Animal_Horror_Zoo
/Rabbit.java
UTF-8
1,999
3.625
4
[]
no_license
public class Rabbit{ private String name; private int rXPosition = 5; private int rYPosition = 5; public Rabbit(String name){ this.name = name; } public void moveUp(){ rYPosition++; if (this.rYPosition == 11) { rYPosition--; System.out.println("Ow! I, the " + name + " hit a wall at " + rXPosition + "," + rYPosition); } else { System.out.println("The " + name + " is in " + rXPosition + "," + rYPosition); } } public void moveDown(){ rYPosition--; if (this.rYPosition == 0) { rYPosition++; System.out.println("Ow! I, the " + name + " hit a wall at " + rXPosition + "," + rYPosition); } else { System.out.println("The " + name + " is in " + rXPosition + "," + rYPosition); } } public void moveRight(){ rXPosition++; if (this.rXPosition == 11) { rXPosition--; System.out.println("Ow! I, the " + name + " hit a wall at " + rXPosition + "," + rYPosition); } else { System.out.println("The " + name + " is in " + rXPosition + "," + rYPosition); } } public void moveLeft(){ rXPosition--; if (this.rXPosition == 0) { rXPosition++; System.out.println("Ow! I, the " + name + " hit a wall at " + rXPosition + "," + rYPosition); } else { System.out.println("The " + name + " is in " + rXPosition + "," + rYPosition); } } public void printPosition() { System.out.println("Hi I'm a " + name + " and I'm in " + rXPosition + "," + rYPosition); } //public void getRabbitPosition() { // this.rXPosition = rXPosition; // this.rYPosition = rYPosition; //} public int getRabbitXPosition() { return this.rXPosition; } public int getRabbitYPosition() { return this.rYPosition; } }
true
8d396174d23a520700cb5e508076cd101af07bf5
Java
MarcusWolschon/osmeditor4android
/src/main/java/de/blau/android/util/ScrollingLinearLayoutManager.java
UTF-8
3,186
2.71875
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
package de.blau.android.util; import android.content.Context; import android.graphics.PointF; import android.view.View; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearSmoothScroller; import androidx.recyclerview.widget.RecyclerView; /** * * @see https://blog.stylingandroid.com/scrolling-recyclerview-part-3/ * */ public class ScrollingLinearLayoutManager extends LinearLayoutManager { private final int duration; public ScrollingLinearLayoutManager(Context context, int duration) { this(context, VERTICAL, false, duration); } public ScrollingLinearLayoutManager(Context context, int orientation, boolean reverseLayout, int duration) { super(context, orientation, reverseLayout); this.duration = duration; } @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { View firstVisibleChild = recyclerView.getChildAt(0); int itemHeight = firstVisibleChild.getHeight(); int currentPosition = recyclerView.getChildAdapterPosition(firstVisibleChild); int distanceInPixels = Math.abs((currentPosition - position) * itemHeight); if (distanceInPixels == 0) { distanceInPixels = (int) Math.abs(firstVisibleChild.getY()); } int visibleItemCount = recyclerView.getHeight() / itemHeight; if (Math.abs(position - currentPosition) > visibleItemCount) { int itemCount = recyclerView.getAdapter().getItemCount(); int jump = position > currentPosition ? Math.max(0, position - 2*visibleItemCount) : Math.min(itemCount-1, position + 2*visibleItemCount); scrollToPosition(jump); } SmoothScroller smoothScroller = new SmoothScroller(recyclerView.getContext(), distanceInPixels, duration); smoothScroller.setTargetPosition(position); startSmoothScroll(smoothScroller); } private class SmoothScroller extends LinearSmoothScroller { private static final int TARGET_SEEK_SCROLL_DISTANCE_PX = 10000; private final float distanceInPixels; private final float duration; public SmoothScroller(Context context, int distanceInPixels, int duration) { super(context); this.distanceInPixels = distanceInPixels; float millisecondsPerPx = calculateSpeedPerPixel(context.getResources().getDisplayMetrics()); this.duration = distanceInPixels < TARGET_SEEK_SCROLL_DISTANCE_PX ? (int) (Math.abs(distanceInPixels) * millisecondsPerPx) : duration; } @Override protected int getVerticalSnapPreference() { return LinearSmoothScroller.SNAP_TO_ANY; } @Override public PointF computeScrollVectorForPosition(int targetPosition) { return ScrollingLinearLayoutManager.this.computeScrollVectorForPosition(targetPosition); } @Override protected int calculateTimeForScrolling(int dx) { float proportion = dx / distanceInPixels; return Math.max(1, (int) (duration * proportion)); } } }
true
dedaa78a014503b757bfcd4530aa4d01fb8429fa
Java
TalasZh/kurjun
/model/src/main/java/ai/subut/kurjun/model/metadata/Architecture.java
UTF-8
1,114
2.640625
3
[ "Apache-2.0" ]
permissive
package ai.subut.kurjun.model.metadata; /** * Architecture enumeration. */ public enum Architecture { ALL, AMD64, i386, I686, X86_64, IA64, ALPHA, ARM, ARMEB, ARMEL, HPPA, M32R, M68K, MIPS, MIPSEL, POWERPC, PPC64, S390, S390X, SH3, SH3EB, SH4, SH4EB, SPARC, ARMHF, ARMV7; /** * Gets architecture by name. This method does case-insensitive matching for architecture enum items. This method is * preferred to {@link Enum#valueOf(java.lang.Class, java.lang.String)} because in most of the places arch fields * are in lower case whereas enum items are defined in upper case. */ public static Architecture getByValue( String arch ) { for ( Architecture a : values() ) { if ( a.toString().equalsIgnoreCase( arch ) ) { return a; } } return null; } public static Architecture getRandom() { return values()[( int ) ( Math.random() * values().length )]; } @Override public String toString() { return super.toString().toLowerCase(); } }
true
a4a8dfc809414d0e13f3890f6d75a309a26c9884
Java
KqSMea8/Mestudy
/AdapterService_xg/src/main/java/com/tecsun/sisp/adapter/modules/sbjf/service/impl/PayRecordServiceImpl.java
UTF-8
5,381
2.078125
2
[]
no_license
package com.tecsun.sisp.adapter.modules.sbjf.service.impl; import com.tecsun.sisp.adapter.common.util.*; import com.tecsun.sisp.adapter.modules.common.service.BaseService; import com.tecsun.sisp.adapter.modules.sbjf.entity.PayRecordDetailEntity; import com.tecsun.sisp.adapter.modules.sbjf.entity.PayRecordEntity; import com.tecsun.sisp.adapter.modules.sbjf.entity.inputBean.CreateFlowNumBean; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by linzetian on 2017/6/6. */ @Service("PayRecordServiceImpl") public class PayRecordServiceImpl extends BaseService { @Autowired PayServiceImpl payService; @Autowired GradeServiceImpl gradeService; public final static String NAMESPACE = "com.tecsun.sisp.adapter.modules.sbjf.service.impl.PayRecordServiceImpl."; public final static String KEY_OF_PRINTCOUNT = "sbjf:print:%s"; public final static String PRINTCOUNT_TIMEOUT = Config.getInstance().get(Constants.SBJF_PRINT_TIMEOUT); public final static String PRINTCOUNT = Config.getInstance().get(Constants.SBJF_PRINT_COUNT); /** * 插入缴费记录 * @param bean * @return */ public boolean insertPayRecord4cssp(CreateFlowNumBean bean) throws Exception{ int count = this.getSqlSessionTemplate().insert(NAMESPACE + "insertPayRecord", bean); return count > 0 ? true : false; } /** * 插入缴费详细信息 * @param prd * @return * @throws Exception */ public boolean insertPayRecordDetail4cssp(PayRecordDetailEntity prd) throws Exception{ System.out.println(prd.getPayId()); int count = this.getSqlSessionTemplate().insert(NAMESPACE + "insertPayRecordDetail", prd); return count > 0 ? true : false; } /** * 根据缴费订单号获取详情清单 * @param flowNum * @return * @throws Exception */ public List<PayRecordDetailEntity> payRecordDetailList4cssp(String flowNum) throws Exception{ List<PayRecordDetailEntity> resList = this.getSqlSessionTemplate().selectList(NAMESPACE + "payRecordDetailList", flowNum); return resList; } /** * 获取已缴费记录 */ public Page<PayRecordEntity> payRecordList4cssp(Map<String,Object> bean) throws Exception{ bean = ParamUtil.addPage(bean); List<PayRecordEntity> res = this.getSqlSessionTemplate().selectList(NAMESPACE + "payRecordList", bean); Page<PayRecordEntity> page = ( Page<PayRecordEntity>)bean.get(Constants.PAGE); page.setData(res); return page; } /** * 获取打印次数 * @return * @throws Exception */ public Map<String,Object> getPrintCount4cssp(String sfzh,String payNum) throws Exception{ Map<String,Object> map = new HashMap<>(); int count = 0; String key = ""; if(StringUtils.isEmpty(sfzh)){ PayRecordEntity prInfo = payRecordInfo4cssp(payNum); if(prInfo==null) { prInfo = new PayRecordEntity(); } key = String.format(KEY_OF_PRINTCOUNT, prInfo.getSfzh()); }else{ key = String.format(KEY_OF_PRINTCOUNT, sfzh); } String strPrintCount = JedisUtil.getValue(key); if(StringUtils.isNotBlank(strPrintCount)){ count = Integer.parseInt(strPrintCount); map.put("printCount", count); map.put("printId",key); return map; }else { int timeout = Integer.parseInt(PRINTCOUNT_TIMEOUT); count = Integer.parseInt(PRINTCOUNT); JedisUtil.setValue(key, PRINTCOUNT,timeout); map.put("printCount", count); map.put("printId", key); return map; } } /** * 减少打印次数 * @param printId 唯一标识符 * @return */ public boolean subtractPrintCount(String printId){ int count = 0; try { String strPrintCount = JedisUtil.getValue(printId); if(StringUtils.isNotBlank(strPrintCount)){ count = Integer.parseInt(strPrintCount); if(count > 0){ count --; } int timeout = Integer.parseInt(PRINTCOUNT_TIMEOUT); JedisUtil.setValue(printId, count+"", timeout); return true; } } catch (Exception e) { System.out.println("减少打印次数异常"+e.getMessage()); } return false; } /** * 修改缴费记录状态 * @param bean * @return */ public boolean updateRecordStatus4cssp(Map<String,Object> bean)throws Exception{ int count = this.getSqlSessionTemplate().update(NAMESPACE + "updateRecordStatus",bean); return count > 0 ? true : false; } /** * 根据缴费单号获取缴费记录信息 * @param payNum * @return * @throws Exception */ public PayRecordEntity payRecordInfo4cssp(String payNum) throws Exception{ PayRecordEntity prInfo = this.getSqlSessionTemplate().selectOne(NAMESPACE + "payRecordInfo",payNum); return prInfo; } }
true
9e2b2039881b791b36d3cca65f22ea0a2947b84a
Java
sandys/filtro
/co.moviired:service-cash/src/main/java/com/moviired/src/main/java/com/moviired/controller/CashApi.java
UTF-8
9,052
2.09375
2
[]
no_license
package com.moviired.controller; import com.moviired.excepciones.ManagerException; import com.moviired.helper.Constant; import com.moviired.helper.Utilidad; import com.moviired.model.Configurations; import com.moviired.model.request.RequestFormat; import com.moviired.model.response.Data; import com.moviired.service.MoviiredCashApi; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.constraints.NotNull; @Slf4j @RestController(value = "cashApi") @RequestMapping("${spring.application.services.rest.uri}") @SuppressWarnings({"unchecked", "unused"}) public class CashApi { private static final String NO_DISPONIBLE = "Servicio no disponible."; private final MoviiredCashApi iMoviiredCashApi; private final Configurations configurations; @Autowired public CashApi( @NotNull Configurations pconfigurations, @NotNull MoviiredCashApi moviiredCashApi) { super(); this.configurations = pconfigurations; this.iMoviiredCashApi = moviiredCashApi; } @PostMapping(value = "${spring.application.methods.cashIn}", produces = {MediaType.APPLICATION_JSON_VALUE}) public final ResponseEntity<Data> cashIn(@RequestBody RequestFormat request, @PathVariable String phoneNumber, @RequestHeader(value = Constant.MERCHANT_ID) String merchantId, @RequestHeader(value = Constant.POS_ID) String posId, @RequestHeader(value = Constant.AUTHORIZATION) String userpass) { Data data; try { if (!configurations.isCashInEnabled()) { throw new ManagerException(Constant.NUMBER_TWO_NEGATIVE_EXCEPTION, Constant.TRANSACTION_ERROR, NO_DISPONIBLE); } RequestFormat requestFormat = RequestFormat.vCashIn(request, phoneNumber, userpass, merchantId, posId); data = this.iMoviiredCashApi.cashIn(requestFormat); } catch (Exception e) { data = Utilidad.generateErrorResponseCashIn(e); } finally { log.info("**************Finalizando el servicio de CashIn**************"); } ResponseEntity<Data> resp = new ResponseEntity<>(data, HttpStatus.valueOf(Integer.parseInt(data.getCode()))); data.setCode(null); return resp; } @GetMapping(value = "${spring.application.methods.cashOutPending}", produces = {MediaType.APPLICATION_JSON_VALUE}) public final ResponseEntity<Data> cashOutPending(@PathVariable String phoneNumber, @RequestHeader(value = Constant.MERCHANT_ID) String merchantId, @RequestHeader(value = Constant.POS_ID) String posId, @RequestHeader(value = Constant.AUTHORIZATION) String userpass) { Data data; ResponseEntity<Data> dataResponseEntity; try { log.info("**************Iniciando el servicio de CashOutPending**************"); if (!configurations.isCashOutPendingEnabled()) { throw new ManagerException(Constant.NUMBER_TWO_NEGATIVE_EXCEPTION, Constant.TRANSACTION_ERROR, NO_DISPONIBLE); } RequestFormat requestFormat = RequestFormat.vCashOutP(phoneNumber, userpass, merchantId, posId); data = this.iMoviiredCashApi.cashOutPending(requestFormat); } catch (Exception e) { data = Utilidad.generateErrorResponseCashIn(e); } finally { log.info("**************Finalizando el servicio de CashOutPending**************"); } dataResponseEntity = new ResponseEntity<>(data, HttpStatus.valueOf(Integer.parseInt(data.getCode()))); data.setCode(null); return dataResponseEntity; } @GetMapping(value = "${spring.application.methods.validateSubscriber}", produces = {MediaType.APPLICATION_JSON_VALUE}) public final ResponseEntity<Data> validateSubscriber(@PathVariable String phoneNumber, @RequestHeader(value = Constant.MERCHANT_ID) String merchantId, @RequestHeader(value = Constant.POS_ID) String posId, @RequestHeader(value = Constant.AUTHORIZATION) String userpass) { Data data; ResponseEntity<Data> dataResponseEntity; try { log.info("**************Iniciando el servicio de ValidateSubscriber**************"); if (configurations.isValidateSubscriberEnabled()) { throw new ManagerException(Constant.NUMBER_TWO_NEGATIVE_EXCEPTION, Constant.TRANSACTION_ERROR, NO_DISPONIBLE); } RequestFormat requestFormat = RequestFormat.vSubscriber(phoneNumber, userpass, merchantId, posId); data = this.iMoviiredCashApi.validateSubscriber(requestFormat); } catch (Exception e) { data = Utilidad.generateErrorResponseCashIn(e); } finally { log.info("**************Finalizando el servicio de ValidateSubscriber**************"); } dataResponseEntity = new ResponseEntity<>(data, HttpStatus.valueOf(Integer.parseInt(data.getCode()))); data.setCode(null); return dataResponseEntity; } @GetMapping(value = "${spring.application.methods.validateTransactions}", produces = {MediaType.APPLICATION_JSON_VALUE}) public final ResponseEntity<Data> validateTransactions(@PathVariable String correlationId, @RequestHeader(value = Constant.MERCHANT_ID) String merchantId, @RequestHeader(value = Constant.POS_ID) String posId, @RequestHeader(value = Constant.AUTHORIZATION) String userpass) { Data data; ResponseEntity<Data> dataResponseEntity; try { log.info("**************Iniciando el servicio de ValidateTransactions**************"); // Verificar si el servicio está habilitado if (configurations.isValidateTransactionsEnabled()) { throw new ManagerException(Constant.NUMBER_TWO_NEGATIVE_EXCEPTION, Constant.TRANSACTION_ERROR, NO_DISPONIBLE); } // Validar la entrada RequestFormat requestFormat = RequestFormat.vTransaction(correlationId, userpass, merchantId, posId); // Ejecutar la operación data = this.iMoviiredCashApi.validateTransaction(requestFormat); } catch (Exception e) { data = Utilidad.generateErrorResponseCashIn(e); } finally { log.info("**************Finalizando el servicio de ValidateTransactions**************"); } dataResponseEntity = new ResponseEntity<>(data, HttpStatus.valueOf(Integer.parseInt(data.getCode()))); data.setCode(null); return dataResponseEntity; } @GetMapping(value = "${spring.application.methods.validateUser}") public final ResponseEntity<Data> validateUser(@PathVariable String phoneNumber, @PathVariable String amount, @RequestHeader(value = "correlationId") String correlationId, @RequestHeader(value = Constant.MERCHANT_ID) String merchantId, @RequestHeader(value = Constant.POS_ID) String posId, @RequestHeader(value = Constant.AUTHORIZATION) String userpass) { Data data; ResponseEntity<Data> dataResponseEntity; log.info("**************Iniciando el servicio de validateUser **************"); Utilidad.assignCorrelative(correlationId); RequestFormat requestFormat = new RequestFormat(); requestFormat.setPhoneNumber(phoneNumber); requestFormat.setAmount(Integer.parseInt(amount)); requestFormat.setMerchantId(merchantId); String[] authorization = userpass.split(":"); requestFormat.setUsuario(authorization[0]); requestFormat.setMpin(authorization[1]); data = this.iMoviiredCashApi.validateUser(requestFormat); dataResponseEntity = new ResponseEntity<>(data, HttpStatus.valueOf(Integer.parseInt(data.getCode()))); data.setCode(Constant.TRANSACTION_OK_00); log.info("**************Finalizando el servicio de ValidateUser**************"); return dataResponseEntity; } }
true
cc712290c9b73e2dfcc25518557bc08117d52248
Java
LPRGDDD/OA
/irs-maven/src/main/java/com/chl/serviceImpl/MailServiceImpl.java
UTF-8
2,700
1.851563
2
[]
no_license
package com.chl.serviceImpl; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.chl.dao.MailDao; import com.chl.entity.Mail; import com.chl.service.MailService; @Service public class MailServiceImpl implements MailService{ @Autowired private MailDao dao; public int addMail(Map map) { // TODO Auto-generated method stub return dao.addMail(map); } @Override public List<Map> getMail(String keyWord, Integer userId) { // TODO Auto-generated method stub return dao.getMail(keyWord, userId); } @Override public List<Map> selectMail(Integer userId) { // TODO Auto-generated method stub return dao.selectMail(userId); } @Override public int saveMail(Map map) { // TODO Auto-generated method stub return dao.saveMail(map); } @Override public List<Map> selectWMail(String keyWord, Integer userId) { // TODO Auto-generated method stub return dao.selectWMail(keyWord, userId); } @Override @Transactional public List selectXMail(Integer emailId) { dao.updatesMail(emailId); return dao.selectXMail(emailId); } @Override @Transactional public int delMail(@Param("emailId") Integer emailId) { // TODO Auto-generated method stub return dao.delMail(emailId); } @Override @Transactional public int updateMail(String subject,String content,Integer emailId) { // TODO Auto-generated method stub return dao.updateMail(subject, content, emailId); } @Override public List<Map> getAllUsers(String keyWord) { // TODO Auto-generated method stub return dao.getAllUsers(keyWord); } @Override public Map selectById(Integer emailId) { // TODO Auto-generated method stub return dao.selectById(emailId); } /*@Override public List<Map> selectsMail(String keyWord, Integer userId) { // TODO Auto-generated method stub return dao.selectsMail(keyWord, userId); } */ @Override public List<Map> selectyMail(Integer id) { // TODO Auto-generated method stub return dao.selectyMail(id); } @Override public int deljMail(Integer emailId) { // TODO Auto-generated method stub return dao.deljMail(emailId); } @Override public List<Map> selectlMail(String keyWord, Integer userId) { // TODO Auto-generated method stub return dao.selectlMail(keyWord, userId); } @Override @Transactional public int updateLMail(Integer emailId) { // TODO Auto-generated method stub return dao.updateLMail(emailId); } }
true
48b690336a4f5e5510635a027e79fdef615fcd5b
Java
pauliverson/JavaStudy
/src/main/java/com/hjy/LearnStudy/JavaStudy/DesingPattern/BridgePatter/DrawAPI.java
UTF-8
199
2.25
2
[]
no_license
package com.hjy.LearnStudy.JavaStudy.DesingPattern.BridgePatter; /** * @author huangjunyan * @date 2019-07-11 12:12 */ public interface DrawAPI { void drawCircle(int radius, int x, int y); }
true
7ae50e1148fea56f710a2637bb6dac6878d79d58
Java
bigdongdong/YiYunDemo
/app/src/main/java/com/chen/firstdemo/recyclers/drag_recycler/DragCallback.java
UTF-8
3,088
2.5625
3
[]
no_license
package com.chen.firstdemo.recyclers.drag_recycler; import android.support.annotation.NonNull; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import com.chen.firstdemo.recyclers.empty_recyclerview.adapters.QuickAdapter; import java.util.Collections; /** * Created by chenxiaodong on 2020/1/17 * * 实现RecyclerView 拖拽工具类 */ public abstract class DragCallback extends ItemTouchHelper.Callback { private QuickAdapter adapter; public DragCallback(QuickAdapter adapter) { this.adapter = adapter; } @Override public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) { int dragFlag; int swipeFlag; RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { dragFlag = ItemTouchHelper.DOWN | ItemTouchHelper.UP | ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT; swipeFlag = 0; } else { dragFlag = ItemTouchHelper.DOWN | ItemTouchHelper.UP; swipeFlag = ItemTouchHelper.END; } return makeMovementFlags(dragFlag, swipeFlag); } @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { int fromPosition = viewHolder.getAdapterPosition(); int toPosition = target.getAdapterPosition(); if (fromPosition < toPosition) { for (int i = fromPosition; i < toPosition; i++) { Collections.swap(adapter.getList(), i, i + 1); } } else { for (int i = fromPosition; i > toPosition; i--) { Collections.swap(adapter.getList(), i, i - 1); } } recyclerView.getAdapter().notifyItemMoved(fromPosition, toPosition); return true; } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { int position = viewHolder.getAdapterPosition(); if (direction == ItemTouchHelper.END) { adapter.getList().remove(position); adapter.notifyItemRemoved(position); } } @Override public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { super.onSelectedChanged(viewHolder, actionState); if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) { onDrag(viewHolder); } } /*拖拽放下时*/ @Override public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { super.clearView(recyclerView, viewHolder); dropDownView(recyclerView,viewHolder); } /*拖拽过程中*/ abstract void onDrag(RecyclerView.ViewHolder holder); /*拖拽完成,丢下View时*/ abstract void dropDownView(RecyclerView recycler, RecyclerView.ViewHolder holder); }
true
e13c9c5ff1c45d084c9949d0c7d30f6ea179aeae
Java
Waterlize/IntelligentHouse
/app/src/main/java/com/example/bartek/flowers/utils/StatusSender.java
UTF-8
1,987
2.640625
3
[]
no_license
package com.example.bartek.flowers.utils; import com.example.bartek.flowers.DevicesList.DevicesInfiniteList; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.IOException; /** * Created by Bartek on 2015-06-28. */ public class StatusSender implements Runnable{ DevicesInfiniteList devicesInfiniteList; String adress= "http://151.80.146.205:8000"; int id; HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget; public StatusSender(DevicesInfiniteList devicesInfiniteList) { this.devicesInfiniteList = devicesInfiniteList; } @Override public void run() { while(true) { for(int i=0;i<Device.deviceList.size();i++) Device.deviceList.get(i).newState(); for (Device device : Device.deviceList) { id = 7; if (device.getId()==null) continue; if (device.getId().equals("ulrQ")) id = 1; if (device.getId().equals("7TLc")) id = 2; if (device.getId().equals("XSNC")) id = 3; if (device.getId().equals("Yax6")) id = 4; if (device.getId().equals("Azhg")) id = 5; if (id == 7) continue; httpget = new HttpGet(adress + "/door/?id=door" + id + "&color=" + device.getColor()); try { HttpResponse resposne = httpclient.execute(httpget); System.out.println("Sended color " + device.getColor() +" for device " + id); } catch (IOException e) { e.printStackTrace(); } } devicesInfiniteList.runOnUiThread(devicesInfiniteList); try { Thread.sleep(8000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
true
086366ac4c7598ce5f31163e7363764c7ffb2129
Java
saversux/docker-spring-boot
/src/main/java/de/julien/spring/rest/RestTest.java
UTF-8
577
2.140625
2
[ "Unlicense" ]
permissive
package de.julien.spring.rest; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author Julien Bernhart, julien.bernhart@hhu.de, 14.11.19 */ @RestController public class RestTest { @RequestMapping(value = "echo", produces = MediaType.APPLICATION_JSON_VALUE) public TestEntity test(@RequestParam(value="name", defaultValue="World") String name) { return new TestEntity("Hello ", name); } }
true
7ed0eba2646c6939c65596c502bfcaa93b7fcd0c
Java
Debarati00/ProfileRepo
/Profile-Service/src/main/java/com/pack/Profileservice/model/ExceptionResponse.java
UTF-8
321
1.703125
2
[]
no_license
package com.pack.Profileservice.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class ExceptionResponse { private String errorMessage; private String requestedURI; }
true
aa6d637c248c17a31446a32d0b25843bb5951813
Java
carlosaraujogonzalez/PFC---Teleco
/PFC/src/area/guias/pfc/CommentsArray.java
UTF-8
566
2.609375
3
[]
no_license
package area.guias.pfc; import java.util.ArrayList; public class CommentsArray implements CommentsStore { private ArrayList<Comment> commentsArray; public CommentsArray(){ commentsArray = new ArrayList<Comment>(); } @Override public void saveComment(Comment comment) { commentsArray.add(comment); } @Override public Comment getComment(int position) { return commentsArray.get(position); } @Override public void deleteList() { commentsArray.clear(); } @Override public ArrayList<Comment> commentsList() { return commentsArray; } }
true
66c1b1a3924c37e7abda11f3b7beeb5e9f352e9b
Java
xiaoshuang1998/cmfz
/src/main/java/com/baizhi/qs/entity/MapDto.java
UTF-8
275
1.554688
2
[]
no_license
package com.baizhi.qs.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; @Data @AllArgsConstructor @NoArgsConstructor public class MapDto implements Serializable { String name; String value; }
true
cf1debb6672ce78e8b3d5c615b3743927011ddf9
Java
yws528819/DesignPattern
/src/com/yws/command/Client.java
GB18030
1,524
3.125
3
[]
no_license
package com.yws.command; public class Client { public static void main(String[] args) { //ʹģʽͨңԵƵIJ RemoteController remoteController = new RemoteController(); //ƵĶ() LightReciever lightReciever = new LightReciever(); //ңǵң, no = 0 ǵƵĿ͹صIJ remoteController.setCommand(0, new LightOnCommand(lightReciever), new LightOffCommand(lightReciever)); System.out.println("--------µƵĿť-----------"); remoteController.onButtonWasPushed(0); System.out.println("--------µƵĹذť-----------"); remoteController.offButtonWasPushed(0); System.out.println("--------µƵijť-----------"); remoteController.undoButtonPushed(); //ʹң System.out.println("===========ʹң========="); TVReceiver tvReceiver = new TVReceiver(); //ǵң, no = 1 ǵӻĿ͹صIJ remoteController.setCommand(1, new TVOncommand(tvReceiver), new TVOffCommand(tvReceiver)); System.out.println("--------µӻĿť-----------"); remoteController.onButtonWasPushed(1); System.out.println("--------µӻĹذť-----------"); remoteController.offButtonWasPushed(1); System.out.println("--------µӻijť-----------"); remoteController.undoButtonPushed(); } }
true
c847c1168a5d083a0af88a75114fad0b0c82598a
Java
Ravi0715/SampleCodes
/FileDatacounting1.java
UTF-8
1,412
3.265625
3
[]
no_license
import java.io.*; import java.lang.*; import java.util.*; class FileDatacounting1 { public static void main(String args[]) throws IOException { Counter word= new Counter("word"); word.start(); Counter line= new Counter("line"); line.start(); Counter ch= new Counter("ch"); ch.start(); } } class Counter extends Thread { String select; public Counter(String select) { this.select=select; } synchronized public void run() { try { String inputFile="D:\\aaa\\one.txt"; File file = new File(inputFile); Scanner in = new Scanner(file); Scanner in1 = new Scanner(file); int words = 0; int lines = 0; int chars = 0; while(in.hasNext()) { String s = in.next(); words++; for(int i=0;i<s.length();i++) chars++; } while(in1.hasNextLine()) { in1.nextLine(); lines++; } if(select.equalsIgnoreCase("line")) System.out.println("No.of lines="+lines); else if(select.equalsIgnoreCase("word")) System.out.println("No.of words="+words); else System.out.println("No.of characters"+chars); } catch(Exception e) { e.printStackTrace(); } } }
true
80f2b4a78ee61a0f4c9ba4dd400bcbb05c4ce99a
Java
zhanght86/HSBC20171018
/LIS/sinosoft-parents/lis-business/src/main/java/com/sinosoft/lis/f1print/XZlisUI.java
UTF-8
2,236
2.671875
3
[]
no_license
package com.sinosoft.lis.f1print; import org.apache.log4j.Logger; import com.sinosoft.lis.pubfun.*; import com.sinosoft.utility.*; public class XZlisUI { private static Logger logger = Logger.getLogger(XZlisUI.class); /** 错误处理类,每个需要错误处理的类中都放置该类 */ public CErrors mErrors = new CErrors(); private VData mResult = new VData(); /** 全局数据 */ private GlobalInput mGlobalInput = new GlobalInput(); public XZlisUI() { } /** * 传输数据的公共方法 */ public boolean submitData(VData cInputData, String cOperate) { try { if (!cOperate.equals("PRINT")) { CError.buildErr(this, "不支持的操作字符串!"); return false; } // 得到外部传入的数据,将数据备份到本类中 if (!getInputData(cInputData)) { return false; } // 进行业务处理 if (!dealData()) { return false; } XZlisBL tXZlisBL = new XZlisBL(); logger.debug("Start tXZlisBL Submit ..."); if (!tXZlisBL.submitData(cInputData, cOperate)) { if (tXZlisBL.mErrors.needDealError()) { mErrors.copyAllErrors(tXZlisBL.mErrors); return false; } else { CError.buildErr(this, "XZlisBL,但是没有提供详细的出错信息"); return false; } } else { mResult = tXZlisBL.getResult(); return true; } } catch (Exception e) { e.printStackTrace(); CError.buildErr(this, e.toString()); return false; } } /** * 根据前面的输入数据,进行UI逻辑处理 如果在处理过程中出错,则返回false,否则返回true */ private boolean dealData() { return true; } /** * 从输入数据中得到所有对象 输出:如果没有得到足够的业务数据对象,则返回false,否则返回true */ private boolean getInputData(VData cInputData) { mGlobalInput.setSchema((GlobalInput) cInputData.getObjectByObjectName( "GlobalInput", 0)); TransferData tTransferData = (TransferData) cInputData .getObjectByObjectName("TransferData", 0); if (tTransferData == null || mGlobalInput == null) { CError.buildErr(this, "传入后台的参数缺少!"); return false; } return true; } public VData getResult() { return this.mResult; } }
true
e99ceb98a9e61766dcf529498c71b8de4e690a1b
Java
atiqorin/Codefights
/Interview/CurrencyArbitrage.java
UTF-8
819
3
3
[]
no_license
class CurrencyArbitrage { boolean currencyArbitrage(double[][] exchange) { double[][] dist = new double[exchange.length][exchange.length]; for(int i = 0; i < exchange.length; i++) { for(int j = 0; j < exchange.length; j++) { dist[i][j] = Math.log(exchange[i][j]); } } int V = exchange.length; for (int k = 0; k < V; k++) { for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][k] + dist[k][j] > dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } for (int i = 0; i < V; i++) { if (dist[i][i] > 0) { return true; } } return false; } }
true
39ddbddea0980d91ec6d093883d13adcbc932321
Java
LiudmilaVilenchyts/JavaBasics2-Classes
/src/LanguageCourse.java
UTF-8
256
2.3125
2
[]
no_license
public class LanguageCourse{ private String name; private List<Language> languages = new ArrayList<Language>(); } public class Language{ private String title; private int price; private int courseDuration; private int groupSize; }
true
9ca39024ceca8641e53c9916f569c777124131bb
Java
aljabrialam/PUPCCB
/app/src/main/java/pupccb/solutionsresource/com/util/CustomRetryPolicy.java
UTF-8
2,140
2.625
3
[]
no_license
package pupccb.solutionsresource.com.util; import android.annotation.SuppressLint; import android.util.Log; import com.octo.android.robospice.persistence.exception.SpiceException; import com.octo.android.robospice.retry.RetryPolicy; import retrofit.RetrofitError; /** * Created by Richard on 28/04/2015. */ public class CustomRetryPolicy implements RetryPolicy { /** The default number of retry attempts. */ public static final int DEFAULT_RETRY_COUNT = 3; /** The default delay before retry a request (in ms). */ public static final long DEFAULT_DELAY_BEFORE_RETRY = 2500; /** The default backoff multiplier. */ public static final float DEFAULT_BACKOFF_MULT = 1f; /** The number of retry attempts. */ private int retryCount = DEFAULT_RETRY_COUNT; /** * The delay to wait before next retry attempt. Will be multiplied by * {@link #backOffMultiplier} between every retry attempt. */ private long delayBeforeRetry = DEFAULT_DELAY_BEFORE_RETRY; /** * The backoff multiplier. Will be multiplied by {@link #delayBeforeRetry} * between every retry attempt. */ private float backOffMultiplier = DEFAULT_BACKOFF_MULT; public CustomRetryPolicy(int retryCount, long delayBeforeRetry, float backOffMultiplier) { this.retryCount = retryCount; this.delayBeforeRetry = delayBeforeRetry; this.backOffMultiplier = backOffMultiplier; } public CustomRetryPolicy() { this(DEFAULT_RETRY_COUNT, DEFAULT_DELAY_BEFORE_RETRY, DEFAULT_BACKOFF_MULT); } @Override public int getRetryCount() { return retryCount; } @SuppressLint("LongLogTag") @Override public void retry(SpiceException exception) { if (exception.getCause() instanceof RetrofitError) { Log.e("Retry Policy Error - Retrofit", exception.getMessage()); retryCount = 0; } else { retryCount--; } delayBeforeRetry = (long) (delayBeforeRetry * backOffMultiplier); } @Override public long getDelayBeforeRetry() { return delayBeforeRetry; } }
true
e5f886262368e2ada750a0226cdb6015e8d74dc6
Java
SQGit/mCity
/app/src/main/java/mcity/com/mcity/ThreeFragment.java
UTF-8
1,300
2.09375
2
[]
no_license
package mcity.com.mcity; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; /** * Created by Admin on 03-11-2016. */ public class ThreeFragment extends Fragment{ TextView tv; public ThreeFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view=inflater.inflate(R.layout.fragment_three, container, false); tv=(TextView)view.findViewById(R.id.tv); Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "mont.ttf"); tv.setTypeface(tf); // Inflate the layout for this fragment return view; } }
true
bd3bd0da05016f3f230b79f7f4a5ac076f011088
Java
luwenjit/SpringCloud-2020-Hoxton-SpringCloud-alibaba
/seata-order-service3001/src/main/java/com/atguigu/springcloud/alibaba/dao/OrderDao.java
UTF-8
452
1.875
2
[ "Apache-2.0" ]
permissive
package com.atguigu.springcloud.alibaba.dao; import com.atguigu.springcloud.alibaba.domain.Order; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; /** * @author 王柳 * @date 2020/4/23 13:42 */ @Mapper public interface OrderDao { // 1新建订单 void create(Order order); // 2修改订单状态,从0改为1 void update(@Param("userId") Long userId, @Param("status") Integer status); }
true
2da088f2b04228bc4f48f42400fc54c10f68a8f6
Java
jennydjen/CesiJeuJura
/src/com/example/cesijeujura/IHM/devis/TraitementDevisView.java
WINDOWS-1252
7,152
1.875
2
[]
no_license
package com.example.cesijeujura.IHM.devis; import java.awt.event.ActionEvent; import java.io.File; import java.util.List; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import com.example.cesijeujura.CesijeujuraUI; import com.example.cesijeujura.EJB.FichierEJB; import com.example.cesijeujura.EJB.ModuleEJB; import com.example.cesijeujura.Entities.Devis; import com.example.cesijeujura.Entities.Fichier; import com.example.cesijeujura.Entities.Module; import com.example.cesijeujura.IEJB.DevisIEJB; import com.example.cesijeujura.IEJB.FichierIEJB; import com.example.cesijeujura.IEJB.ModuleIEJB; import com.example.cesijeujura.IHM.popup.ChooseFile; import com.example.cesijeujura.devis.PopupSave; import com.vaadin.annotations.AutoGenerated; import com.vaadin.annotations.DesignRoot; import com.vaadin.data.Item; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Embedded; import com.vaadin.ui.GridLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.PopupView; import com.vaadin.ui.TabSheet; import com.vaadin.ui.Table; import com.vaadin.ui.TextField; import com.vaadin.ui.Upload; import com.vaadin.ui.Upload.Receiver; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import com.vaadin.ui.declarative.Design; /** * !! DO NOT EDIT THIS FILE !! * * This class is generated by Vaadin Designer and will be overwritten. * * Please make a subclass with logic and additional interfaces as needed, * e.g class LoginView extends LoginDesign implements View { } */ @DesignRoot @AutoGenerated @SuppressWarnings("serial") public class TraitementDevisView extends VerticalLayout { protected HorizontalLayout referenceHLayout; protected HorizontalLayout devisLblLayout; protected Label referenceDevisLabel; protected TextField referenceDevisTF; protected HorizontalLayout clientHLayout; protected Label referenceClientLabel; protected TextField referenceClientTF; protected TabSheet traitementSheet; protected HorizontalLayout filesHLayout; protected Table filesTable; protected VerticalLayout buttonLayout; protected Button addButton; protected Button deleteButton; protected HorizontalLayout chiffrageHLayout; protected Table modulesTable; protected Button editerCompButton; protected GridLayout buttonsGLayout; protected Button traiterButton; protected Button saveButton; protected Button quitButton; //final JFileChooser fc = new JFileChooser(); public TraitementDevisView(ModuleIEJB moduleEJB,final FichierIEJB fichiersIEJB,final DevisIEJB devisIEJB,final int id) { Design.read(this); // BOUTON AJOUTER LIGNE CHIFFRAGE editerCompButton.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent e) { } }); //UploadBox uploadbox = new UploadBox(); //addButton.addComponent(uploadbox); // layout.addComponent(new Upload("CV", new Upload.Receiver() { // // public OutputStream receiveUpload(String filename, String MIMEType) { // return null; // } // })); //ImageUploader receiver = new ImageUploader(); // Create the upload with a caption and set receiver later // addButton = new Upload("Upload Image Here", receiver); // addButton.setButtonCaption("Start Upload"); // addButton.addSucceededListener(receiver); // BOUTON AJOUTER LIGNE IMPORTATION addButton.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event){ //filesTable.removeAllItems(); //filesTable.setSizeFull(); //filesTable.setSelectable(true); //filesTable.addContainerProperty("Nom", String.class, ""); //filesTable.addContainerProperty("Chaine", String.class, ""); //Object newItemAddID = filesTable.addItem(); //Item rowadd = filesTable.getItem(newItemAddID); Devis devis = devisIEJB.find(id); ChooseFile choose = new ChooseFile(devis,fichiersIEJB); getUI().addWindow(choose); choose.setVisible(true); filesTable.refreshRowCache(); filesTable.validate(); //JOptionPane jop = new JOptionPane();//jop2 = new JOptionPane(); //String nom = jop.showInputDialog(null, "Veuillez dcliner votre identit !", "Gendarmerie nationale !", JOptionPane.QUESTION_MESSAGE); //jop2.showMessageDialog(null, "Votre nom est " + nom, "Identit", JOptionPane.INFORMATION_MESSAGE); //rowadd.getItemProperty("Nom").setValue(upload.getId()); //rowadd.getItemProperty("Chaine").setValue(upload.getDescription()); //rowadd.getItemProperty("Nom").setValue("coucou"); //rowadd.getItemProperty("Chaine").setValue("test"); } }); // BOUTON SUPPRIMER LIGNE IMPORTATION deleteButton.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { //Devis d = mapsDevis.get((Integer) devisTable.getValue()); //CesijeujuraUI.getInstanceMenuView().afficherFicheDevis(d.getId()); filesTable.removeItem(filesTable.getValue()); filesTable.refreshRowCache(); filesTable.validate(); //if (filesTable.getTabIndex() != -1) { // remove selected row from the model //filesTable.removeItem(filesTable.getTabIndex()); //} //filesTable.removeItem(itemId); } }); saveButton.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { PopupSave popup = new PopupSave(); getUI().addWindow(popup); popup.setVisible(true); } }); traiterButton.addClickListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { } }); // LISTE TABLE CHIFFRAGE List<Module> module = moduleEJB.findAllModule(); modulesTable.removeAllItems(); modulesTable.setSizeFull(); modulesTable.setSelectable(true); modulesTable.addContainerProperty("Nom des modules", String.class, ""); modulesTable.addContainerProperty("Nombre de Composants associs", String.class, ""); modulesTable.addContainerProperty("Prix estim()", String.class, ""); for (Module m : module){ Object newItemID = modulesTable.addItem(); Item row1 = modulesTable.getItem(newItemID); row1.getItemProperty("Nom des modules").setValue(m.getNom()); row1.getItemProperty("Nombre de Composants associs").setValue(m.getComposants().size()+""); row1.getItemProperty("Prix estim()").setValue(m.getPrixModule().toString()); } // LISTE TABLE IMPORT List<Fichier> fichiers = fichiersIEJB.findAllFichiers(); filesTable.removeAllItems(); filesTable.setSizeFull(); filesTable.setSelectable(true); filesTable.addContainerProperty("Nom", String.class, ""); filesTable.addContainerProperty("Chaine", String.class, ""); for (Fichier f : fichiers){ Object newItemAddID = filesTable.addItem(); Item rowadd = filesTable.getItem(newItemAddID); rowadd.getItemProperty("Nom").setValue(f.getId()+""); rowadd.getItemProperty("Chaine").setValue(f.getPath()); } } }
true
a950c6b7556b9ae3f107ac5e6799497d4e96b2c5
Java
Coldmananer/StuComp
/OriObject/src/com/whb/Dao/competitionDao.java
GB18030
708
1.984375
2
[]
no_license
package com.whb.Dao; import java.util.List; import com.Model.Competition; public interface competitionDao { //վIDҾ public Competition findbyCompId(int CompId); //澺 public void save(Competition competition); //!¾ public void update(Competition competition); //վͲҾ public List<Competition> findbyCompTypeid(int compTypeid); //վģѯ public List<Competition> findbyCompName(String CompName); //ҳѯ public List<Competition> queryByPage(String hql, int offset, int pageSize); public List<Competition> findAll(); public int getAllRowCount(String hql); }
true
2c0c907556a2cbd3cefe3d4c3a4f4896867ad14e
Java
jeanLuizInsight/CompiladorJLZ
/src/AnaliseSintatica/classe/TIPO.java
UTF-8
1,516
3.109375
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package AnaliseSintatica.classe; import AnaliseLexica.Token; import AnaliseLexica.TokenDefines; import AnaliseSintatica.LeitorDeToken; import AnaliseSintatica.Producao; import AnaliseSintatica.SimboloGramatical.NaoTerminal; import AnaliseSintatica.SimboloGramatical.SimboloGramatical; /** * * @author Jean Luiz */ //classe retorna um simbolo (tipo primitivo ou identificador) public class TIPO extends Producao { @Override public SimboloGramatical derivar() throws Exception { //pega a instância do tokenReader LeitorDeToken tokenReader = LeitorDeToken.getInstance(); //consome o primeiro token Token token = tokenReader.tokenAtual(); //cria um símbolo NaoTerminal naoTerminal = new NaoTerminal(this.getClass().getSimpleName()); //se char ou int if(token.getTokenDefine().equals(TokenDefines.PALAVRA_RESERVADA) && (token.getAtributo().toString().equals("char") || token.getAtributo().toString().equals("int") || token.getAtributo().toString().equals("String"))) { //adiciano derivando de TIPO_PRIMITIVO naoTerminal.add(new TIPO_PRIMITIVO().derivar()); } else { naoTerminal.add(erro(this.getClass().getSimpleName(), "TIPO Deve ser char, int ou String.")); } //retorna um símbolo return naoTerminal; } }
true
e19263f9fe0a1856c0aef9304e9853b30e243e74
Java
SSUHan/deviewsched-android
/app/src/main/java/com/gdgssu/android_deviewsched/ui/findfriends/FindFriendsAdapter.java
UTF-8
2,829
2.28125
2
[ "MIT" ]
permissive
package com.gdgssu.android_deviewsched.ui.findfriends; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.gdgssu.android_deviewsched.DeviewSchedApplication; import com.gdgssu.android_deviewsched.R; import java.util.LinkedList; public class FindFriendsAdapter extends BaseAdapter { private Context mContext; private LayoutInflater mInflater; private LinkedList<String> m_List; public FindFriendsAdapter(){ m_List = new LinkedList<String>(); } public FindFriendsAdapter(LinkedList<String> list){ this.mContext = DeviewSchedApplication.GLOBAL_CONTEXT; m_List = list; this.mInflater = (LayoutInflater.from(this.mContext)); } @Override public int getCount() { return m_List.size(); } @Override public Object getItem(int position) { return m_List.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView avatarView = null; TextView userNameView = null; final int pos = position; final Context context = parent.getContext(); if(convertView == null){ LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.item_findfriend,parent,false); // TextView item_text = (TextView)convertView.findViewById(R.id.item_text); // item_text.setText(m_List.get(position)); Button item_button = (Button)convertView.findViewById(R.id.item_button); item_button.setText("Click"); item_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context, "button click contents" + m_List.get(pos) + " pos:" + pos, Toast.LENGTH_SHORT).show(); } }); convertView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context,"item click contents:"+m_List.get(pos)+" pos"+pos,Toast.LENGTH_LONG).show(); } }); } ImageView item_image = (ImageView)convertView.findViewById(R.id.item_image); TextView item_text = (TextView)convertView.findViewById(R.id.item_text); item_text.setText(m_List.get(position)); return convertView; } }
true
0ba0bcf8ad33be934d233b6f504814c8be45f86b
Java
yhc3l-java-1416/jpa
/week4/src/main/java/se/coredev/jpa/repository/EmployeeRepositoryImpl.java
UTF-8
279
2.328125
2
[]
no_license
package se.coredev.jpa.repository; import se.coredev.jpa.model.Employee; public class EmployeeRepositoryImpl implements EmployeeRepositoryCustom { @Override public void logEmployee(Employee employee) { System.out.println("0 # Logging employee: [" + employee + "]"); } }
true
13d9c75535058703ccddd409a24699b4c1437d2d
Java
akashrampura/HackerRank
/src/com/hackerrank/BloombergAbhishek.java
UTF-8
968
3.390625
3
[]
no_license
package com.hackerrank; import java.sql.SQLOutput; import java.util.*; public class BloombergAbhishek { static class Adj{ char ch; int freq; Adj(char ch){ this.ch = ch; this.freq = 1; } } public static void main(String[] args) { String s = "AABBBAB"; // B LinkedList<Adj> stack = new LinkedList<>(); for(char c : s.toCharArray()){ if(!stack.isEmpty() && stack.peek().ch == c){ stack.peek().freq++; }else{ stack.push(new Adj(c)); } if(stack.peek().freq == 3){ stack.pop(); } } StringBuilder sb = new StringBuilder(); while(!stack.isEmpty()){ Adj adj = stack.removeLast(); for(int i = 0; i< adj.freq; i++){ sb.append(adj.ch); } } System.out.println(sb.toString()); } }
true
aec6f3723a11fa1173d4e97fb2253b7bf435dd32
Java
380450382/book-listen
/src/main/java/com/book/command/enums/ResultEnum.java
UTF-8
371
2.34375
2
[]
no_license
package com.book.command.enums; public enum ResultEnum { SUCCESS("成功",200), FAIL("失败",500), ; private String desc; private int code; public String desc() { return desc; } public int code() { return code; } ResultEnum(String desc, int code) { this.desc = desc; this.code = code; } }
true
3fefe1f17456f3df85add755f8d0bf75c2c2ca5c
Java
xyueji/cold-eye
/cold-eye-druid/src/main/java/com/xyueji/coldeye/druid/service/impl/DruidServiceImpl.java
UTF-8
6,221
2.5
2
[]
no_license
package com.xyueji.coldeye.druid.service.impl; import com.xyueji.coldeye.druid.common.DruidHelper; import com.xyueji.coldeye.druid.common.MessageEntity; import com.xyueji.coldeye.druid.common.ResultResp; import com.xyueji.coldeye.druid.service.DruidService; import org.springframework.stereotype.Service; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.*; /** * @author xiongzhigang * @date 2021-02-01 14:52 * @description */ @Service("druidService") public class DruidServiceImpl implements DruidService { /** * 查询druid数据列表 * * @param params 查询参数 * @return ResultResp */ @Override public ResultResp queryDruidList(Map<String, Object> params) { //根据参数组装查询条件 String sql = querySQL(params); // 实例化Druid JDBC连接 DruidHelper helper = new DruidHelper(); Connection connection = null; Statement st = null; ResultSet rs = null; try { List<MessageEntity> resultList = new ArrayList<>(); connection = helper.getConnection(); st = connection.createStatement(); rs = st.executeQuery(sql); while (rs.next()) { MessageEntity messageEntity = rs2Entity(rs); resultList.add(messageEntity); } //设置返回格式 Map<String, Object> map = new HashMap<String, Object>(); map.put("items", resultList); return ResultResp.ok(map); } catch (Exception e){ e.printStackTrace(); } finally { helper.close(connection, st, rs); } return ResultResp.error(); } /** * 查询设备温度湿度 * * @param params 查询参数 * @return ResultResp */ @Override public ResultResp queryDruidTumHum(Map<String, Object> params) { //查询druid数据列表 List<MessageEntity> list = (List<MessageEntity>)queryDruidList(params).get("items"); List<String> times = new ArrayList<>(); List<Integer> tems = new ArrayList<>(); List<Integer> hums = new ArrayList<>(); //给数组赋值 for (int i = 0; i < list.size(); i++) { MessageEntity messageHistoryEntity = (MessageEntity) list.get(i); String strTime = messageHistoryEntity.getCurtime(); times.add(strTime.substring(8, 10) + ":" + strTime.substring(10, 12)+ ":" + strTime.substring(12, 14)); tems.add(messageHistoryEntity.getTem()); hums.add(messageHistoryEntity.getHum()); } //按时间重新排序 Collections.reverse(times); Collections.reverse(tems); Collections.reverse(hums); Map<String, Object> map = new HashMap<String, Object>(); map.put("xAxis", times); map.put("tem", tems); map.put("hum", hums); return ResultResp.ok(map); } /** * 查询条件 * @param params * @return */ private String querySQL(Map<String, Object> params){ StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("SELECT * from all_device_message where 1= 1 "); //设备编码 String metercode = params.get("meterCode").toString().trim(); if(!metercode.equals("")){ stringBuffer.append(" and meterCode = '"); stringBuffer.append(metercode); stringBuffer.append("' "); } //前台传入开始、结束时间 String startTime = params.get("startTime").toString().trim(); if(!startTime.equals("")){ stringBuffer.append(" and __time > '"); stringBuffer.append(startTime); stringBuffer.append("' "); } String endTime = params.get("endTime").toString().trim(); if(!endTime.equals("")){ stringBuffer.append(" and __time < '"); stringBuffer.append(endTime); stringBuffer.append("' "); } stringBuffer.append(" order by __time desc"); //查询条数 String limit = params.get("limit")!=null? params.get("limit").toString().trim():"10"; stringBuffer.append(" limit "); stringBuffer.append(limit); System.out.println(stringBuffer.toString()); return stringBuffer.toString(); } /** * 查询结果转化为对象 * @param rs * @return * @throws Exception */ private MessageEntity rs2Entity(ResultSet rs) throws Exception{ MessageEntity messageEntity = new MessageEntity(); messageEntity.setMeterCode(rs.getString("meterCode")); messageEntity.setMeterId(rs.getString("meterId")); messageEntity.setMeterName(rs.getString("meterName")); messageEntity.setHostCode(rs.getString("hostCode")); messageEntity.setHostId(rs.getString("hostId")); messageEntity.setHostName(rs.getString("hostName")); messageEntity.setHouseCode(rs.getString("houseCode")); messageEntity.setHouseId(rs.getString("houseId")); messageEntity.setHouseName(rs.getString("houseName")); messageEntity.setCompanyName(rs.getString("companyName")); messageEntity.setCompanyId(rs.getString("companyId")); messageEntity.setTem(Integer.valueOf(rs.getString("tem"))); messageEntity.setMaxTem(Integer.valueOf(rs.getString("maxTem"))); messageEntity.setMinTem(Integer.valueOf(rs.getString("minTem"))); messageEntity.setHum(Integer.valueOf(rs.getString("hum"))); messageEntity.setMaxHum(Integer.valueOf(rs.getString("maxHum"))); messageEntity.setMinHum(Integer.valueOf(rs.getString("minHum"))); messageEntity.setTemAlert(Integer.valueOf(rs.getString("temAlert"))); messageEntity.setHumAlert(Integer.valueOf(rs.getString("humAlert"))); messageEntity.setState(Integer.valueOf(rs.getString("state"))); messageEntity.setLat(rs.getString("lat")); messageEntity.setLon(rs.getString("lon")); messageEntity.setCurtime(rs.getString("curtime")); return messageEntity; } }
true
6ac6a7a6406c3e8045f3bb7c5956f19d532db684
Java
msamkov/patterns
/test/ee/agile/patterns/composite/MultiVolumeUnzipperTest.java
UTF-8
928
2.9375
3
[]
no_license
package ee.agile.patterns.composite; import org.junit.Test; import java.io.InputStream; import static ee.agile.patterns.composite.SimpleUnzipperTest.*; import static org.junit.Assert.assertEquals; public class MultiVolumeUnzipperTest { @Test public void singleVolume() throws Exception { InputStream in = stream("Here~=%. Let~HW$UC!1O! beast, for~-=!1OaM: his~1=60&6ty-~6."); Unzipper unzipper = new SimpleUnzipper(in); assertEquals(REVELATION, unzipper.unzip()); } @Test public void unzipMultipleVolumes() throws Exception { InputStream vol1 = stream("Here~=%. Let~HW$"); InputStream vol2 = stream("UC!1O! beast, fo"); InputStream vol3 = stream("r~-=!1OaM: his~1"); InputStream vol4 = stream("=60&6ty-~6."); Unzipper unzipper = new MultiVolumeUnzipper(vol1, vol2, vol3, vol4); assertEquals(REVELATION, unzipper.unzip()); } }
true
8d798f9cf644497547992fad51c61963a55c4ebc
Java
Stu-P/product-poller
/src/main/java/stu/learning/kafka/productpoller/event/ProductCreatedEvent.java
UTF-8
1,011
2.375
2
[]
no_license
package stu.learning.kafka.productpoller.event; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import stu.learning.kafka.productpoller.model.Product; import java.time.Instant; import java.util.UUID; public class ProductCreatedEvent extends BaseEvent { private final Product product; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public ProductCreatedEvent( @JsonProperty("product") Product product, @JsonProperty("correlationId") UUID correlationId, @JsonProperty("timeStamp") Instant timeStamp) { super(correlationId, timeStamp); this.product = product; } public Product getProduct() { return product; } @Override public String toString() { return "ProductCreatedEvent{" + "product=" + product + ", correlationId=" + correlationId + ", timeStamp=" + timeStamp + '}'; } }
true
d243251cd24f8655c0b23fd4e1ff3c1ad344e4ce
Java
MesutCevik/JavaLeichtGemacht
/Udemy-Java-Kurs-Kontrollstrukturen/src/com/company/VerzweigungSwitchCase.java
UTF-8
2,322
4.03125
4
[]
no_license
package com.company; import java.util.Scanner; public class VerzweigungSwitchCase { public static void main(String[] args) { /* Kontrollstrukturen steuern den Programmablaufplan * D.h. man kann mit Kontrollstrukturen den Programmablauf steuern. * * switch - Fallunterscheidung * case - Der Fall (einer der möglichen Fälle) * * (Bedingung) - Als Bedingung gilt nur ein int, char und ein String. * Anders ausgedrückt, die switch-Anweisung kann eine Bedinung nur überprüfen auf ein int, char oder ein String. */ /* Mit der switch-Anweisung kann eine Fallunterscheidung vorgenommen werden, genauso wie eine if-else-Anweisung. * Vorteil: übersichtlicher als eine if-else-Anweisung, die umfangreich und mit jeweils umfangreichen Anweisungsblöcken. * zu switch: In den runden Klammern steht die Bedingung dieser Fallunterscheidung. Hier wird die Bedingung auf eine Zahl geprüft. * zu case 0: Fall, wenn die Bedingung eine 0 ist. Wenn dieser eintritt, dann führe die nachfolgenden Anweisungen aus. * zu break: Unterbreche diese Fallunterscheidung, wenn dieser Fall eingetreten ist. Ansonsten werden alle weiteren * cases/Fälle auch überprüft, was unnötig ist und Rechenpower frisst. */ /* switch (5) { case 0: { System.out.println("Die Zahl ist eine 0."); } break; case 3: { System.out.println("Die Zahl ist eine 3."); } break; case 5: { System.out.println("Die Zahl ist eine 5."); } break; } */ System.out.println("Wie wieviele Bundesländer hat Deutschland?"); System.out.println("16 oder 3 oder 30 oder 15"); Scanner scan = new Scanner(System.in); int eingabeUser = scan.nextInt(); switch (eingabeUser){ case 15: { System.out.println("Das ist falsch."); } break; case 30: { System.out.println("Das ist falsch."); } break; case 3: { System.out.println("Das ist falsch."); } break; case 16: { System.out.println("Das ist richtig :-)"); } break; default: {// Standardausgabe, wenn keiner der obigen cases/Fälle eintritt. "default"-Befehl ist wie "else". System.out.println("Diese Zahl ist unbekannt."); } } } }
true
050e1ebac05fa2bd1ac98ba2c8731f7e36978db4
Java
xiaolengSS/Source-code
/sourcecode-gateway-api-backend/src/main/java/com/sourcecode/config/DateFormatConfig.java
UTF-8
666
1.9375
2
[]
no_license
package com.sourcecode.config; import com.sourcecode.converter.DateConverter; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * 注册日期格式化转换器 */ @Configuration public class DateFormatConfig extends WebMvcConfigurerAdapter { public void addFormatters(FormatterRegistry registry) { registry.addConverter(new DateConverter()); } }
true
42f1a32d0d3de5df7f2291c7e08fe0858df9232b
Java
trescube/AddressTagger
/src/main/java/com/grunick/addresstagger/data/AddressTag.java
UTF-8
553
2.28125
2
[]
no_license
package com.grunick.addresstagger.data; public enum AddressTag { AA1, /* Admin area level 1 - Country */ AA2, /* Admin area level 2 - State/Province */ AA3, /* Admin area level 3 - County */ AA4, /* Admin area level 4 - City */ PFX, /* Prefix */ PDR, /* Pre-directional */ SFX, /* Suffix */ SDR, /* Post-directional */ STR, /* Base street name */ NUM, /* Street/House number */ ZIP, /* Postal Code */ UNK, /* Unknown token */ START, /* Used for Markov chains */ STOP /* Used for Markov chains */ }
true
206d17f7957d8b9e7e3a92ac3f28aab98d63974d
Java
chauhandivyesh18/SMS
/app/src/main/java/com/millionaires/sms/Login/ForgotPasswordFragments/ForgotPasswordMidFragment.java
UTF-8
1,711
2.0625
2
[]
no_license
package com.millionaires.sms.Login.ForgotPasswordFragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.millionaires.sms.Base.BaseFragment; import com.millionaires.sms.Common.Constants; import com.millionaires.sms.ChangePassword.ChangePasswordFragments.ChangePasswordMidFragment; import com.millionaires.sms.Login.EmptyBottomFragment; import com.millionaires.sms.Login.LoginActivity; import com.millionaires.sms.R; /** * A simple {@link Fragment} subclass. */ public class ForgotPasswordMidFragment extends BaseFragment implements View.OnClickListener { Button mForgotPasswordButton; public ForgotPasswordMidFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_forgot_password_mid, container, false); mForgotPasswordButton = (Button) view.findViewById(R.id.forgot_password_button); mForgotPasswordButton.setOnClickListener(this); return view; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.forgot_password_button: LoginActivity.getINSTANCE().replaceFragments(new String[]{ Constants.CHANGE_PASSWORD_MID_FRAGMENT, Constants.EMPTY_BOTTOM_FRAGMENT}, new ChangePasswordMidFragment(), new EmptyBottomFragment()); break; } } }
true
2e1b8a62eeb47def907f91343491177a41f41fc7
Java
jyygn/ledown
/core/listener/OnSaveLastPositionListener.java
UTF-8
615
2.125
2
[]
no_license
package com.mobile.ledown.core.listener; import ledown.core.file.IFileParagraph; /** * 下载结束或暂停保存最后进度事件 * @author yangn */ public interface OnSaveLastPositionListener { /** * 保存最后位置 * @param fileParagraph */ public void onSaveLastPosition(IFileParagraph fileParagraph, String downloadingFileName); /** * 创建一个新的位置并保存 * @param fileParagraph * @param downloadingFileName */ public void onSaveNewLastPositions(IFileParagraph[] fileParagraphs, String downloadingFileName); }
true
0b7292e959873425d3dd58d42bb2ab30008218bb
Java
PengJiwu/dmat
/src/main/java/it/unipr/aotlab/forceload/ForceLoadClasses.java
UTF-8
2,146
2.640625
3
[]
no_license
package it.unipr.aotlab.forceload; import it.unipr.aotlab.dmat.core.errors.DMatInternalError; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; public class ForceLoadClasses { static public void listFromFile(Class<?> c, String filename) { try { ForceLoadClasses.listFromFileImpl(filename); } catch (ClassNotFoundException e) { throw new DMatInternalError( c.getCanonicalName() + " initialization invalid file. Original Message " + e.getMessage()); } catch (IOException e) { throw new DMatInternalError( c.getCanonicalName() + " initialization IO error. Original Message " + e.getMessage()); } } static public void listFromFileImpl(String filename) throws ClassNotFoundException, IOException { InputStream classListStream = null; try { classListStream = ForceLoadClasses.class.getClassLoader() .getResourceAsStream("forceload/" + filename); if (classListStream == null) throw new IOException("Could not read " + filename); DataInputStream classListDataInputStream = new DataInputStream( classListStream); InputStreamReader classListReader = new InputStreamReader( classListDataInputStream, "UTF-8"); BufferedReader reader = new BufferedReader(classListReader); String className; while ((className = reader.readLine()) != null) { Class.forName(className); } } catch (UnsupportedEncodingException e) { // Unsupported UTF-8 means a bug in the JVM! // http://docs.oracle.com/javase/1.4.2/docs/api/java/nio/charset/Charset.html e.printStackTrace(); System.exit(1); } finally { classListStream.close(); } } }
true
63d77f756b27c7a8ca611e7d4bbace8d409b8169
Java
KochetovNicolai/fizteh-java-2013
/src/ru/fizteh/fivt/students/mishatkin/calculator/ReversePolishNoteEncoder.java
UTF-8
4,475
3.296875
3
[]
no_license
/** * ReversePolishNoteEncoder.java * calculator * * Created by Vladimir Mishatkin on 9/14/13 */ package ru.fizteh.fivt.students.mishatkin.calculator; import java.math.BigInteger; import java.util.NoSuchElementException; import java.util.Vector; public class ReversePolishNoteEncoder { private Vector<Integer> st; // operands stack private Vector<Character> op; // operators stack public ReversePolishNoteEncoder() { st = new Vector<Integer>(); op = new Vector<Character>(); } private boolean isSeparator(char c) { return c == ' '; } private boolean isOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/' || c == '%'; } private boolean isDigit(char c) { return c >= '0' && c <= '9'; } private boolean isValidAlpha(char c) { return isDigit(c) || (Calculator.MyBase >= 10 && c >= 'A' && c <= 'A' + Calculator.MyBase - 10); } private int priorityForOperation(char op) { return op == '+' || op == '-' ? 1 : op == '*' || op == '/' || op == '%' ? 2 : -1; } private void processOperation(Vector<Integer> st, char op) throws Exception { int r; int l; try { r = st.lastElement(); st.removeElementAt(st.size() - 1); l = st.lastElement(); st.removeElementAt(st.size() - 1); } catch (NoSuchElementException e) { throw new Exception("Wrong input format: not enough operands for operator \'" + op + "\'."); } BigInteger bigLeft = BigInteger.valueOf(l); BigInteger bigRight = BigInteger.valueOf(r); Exception overflowException = new Exception("Overflow."); switch (op) { case '+': if (!bigLeft.add(bigRight).equals(BigInteger.valueOf(l + r))) { throw overflowException; } st.add(l + r); break; case '-': if (!bigLeft.subtract(bigRight).equals(BigInteger.valueOf(l - r))) { throw overflowException; } st.add(l - r); break; case '*': if (!bigLeft.multiply(bigRight).equals(BigInteger.valueOf(l * r))) { throw overflowException; } st.add(l * r); break; case '/': st.add(l / r); break; case '%': st.add(l % r); break; } } public int calculate(String s) throws Exception { for (int i = 0; i < s.length(); ++i) { if (isSeparator(s.charAt(i))) { continue; } if (s.charAt(i) == '(') { op.add('('); } else if (s.charAt(i) == ')') { while (op.lastElement() != '(') { processOperation(st, op.lastElement()); op.removeElementAt(op.size() - 1); } op.removeElementAt(op.size() - 1); } else if (isOperator(s.charAt(i))) { char currentOperation = s.charAt(i); while (!op.isEmpty() && priorityForOperation(op.lastElement()) >= priorityForOperation(s.charAt(i))) { processOperation(st, op.lastElement()); op.removeElementAt(op.size() - 1); } op.add(currentOperation); } else { StringBuilder operandBuilder = new StringBuilder(); while (i < s.length() && isValidAlpha(s.charAt(i))) { operandBuilder.append(s.charAt(i++)); } String operand = new String(operandBuilder); --i; try { st.add(Integer.valueOf(operand, Calculator.MyBase)); } catch (NumberFormatException e) { System.err.println(e.getMessage()); throw new Exception("Wrong input format: numbers should match " + Calculator.MyBase + "-based numeric system."); } } } while (!op.isEmpty()) { processOperation (st, op.lastElement()); op.removeElementAt(op.size() - 1); } if (st.size() != 1) { throw new Exception("Invalid input."); } return st.lastElement(); } }
true
1c11cda84b6181bb5b09904c436f52e549913549
Java
Humakt83/supercoveragetest
/src/test/java/fi/ukkosnetti/coverage/CoveragerTest.java
UTF-8
252
1.640625
2
[ "MIT" ]
permissive
package fi.ukkosnetti.coverage; import java.io.IOException; import org.junit.Test; import fi.ukkosnetti.coverage.Coverager; public class CoveragerTest { @Test public void testCoverager() throws IOException { new Coverager().coverage(); } }
true
13e7a26d73201c69b42a74f750dcacd0f88459e8
Java
wwcy1998/recursive-algorithm
/Hannoi.java
UTF-8
731
3.9375
4
[]
no_license
public class Hannoi { public static void main(String[] args) { char a = 'a'; char b = 'b'; char c = 'c'; hanoi(2,a,b,c); //n:盘子数量 } static void hanoi(int n, char a, char b, char c) { if (1 == n)/* 如果剩下一个盘子,直接从a-->c */ { System.out.println(n+":"+a+"-->"+c); } else { /* 把n-1个盘子从a移动到b借助于c */ hanoi(n - 1, a, c, b); System.out.println(n + ":" + a + "-->" + c ); /* 把第n和盘子从a移动c */ hanoi(n - 1, b, a, c);/* 把n-1个盘子从b移动到c借助于a */ } } }
true
64a543ab3d5baeca05f13bae278e9f58a62a2189
Java
mike1234-pixel/Java
/Collections2.java
UTF-8
2,670
3.875
4
[]
no_license
// TRAVERSING LISTS package Collections2; import java.util.ArrayList; public class Application { public static void main(String[] args) { // TODO Auto-generated method stub ArrayList<String> animals = new ArrayList<String>(); animals.add("Lion"); animals.add("cat"); animals.add("dog"); animals.add("bird"); System.out.println(animals); // TRAVERSING LISTS // for for (int i = 0; i < animals.size(); i++) { System.out.println(animals.get(i)); } // for each for(String value : animals) { System.out.println(value); } System.out.println("______________________________________"); // TRAVERSING ARRAY OF OBJECTS ArrayList<Vehicle> vehicles = new ArrayList<Vehicle>(); Vehicle vehicle2 = new Vehicle("Toyota", "Camery", 12000, false); vehicles.add(new Vehicle("Honda", "accord", 12000, false)); // initialising object inline to be added to array list, can also init first then add to list vehicles.add(vehicle2); vehicles.add(new Vehicle("Jeep", "Wrangler", 25000, true)); /// for each for(Vehicle car : vehicles) { // TRAVERSE OBJECT PROPERTIES USING GETTERS System.out.println("_________"); System.out.println("NEW CAR:"); System.out.println(car.getMake()); System.out.println(car.getModel()); System.out.println(car.getPrice()); System.out.println(car.isFourWDrive()); // TRAVERSE OBJECT PROPERTIES USING TOSTRING() // toString() returns the string representation of an object System.out.println(car); } } } /////////////////////// VEHICLE CLASS ////////////////////////////////////////// package Collections2; public class Vehicle { String make; String model; int price; boolean fourWDrive; // GENERATE TO STRING METHOD SO OBJECTS RETURNED WHEN LIST TRAVERSED ARE HUMAN READABLE OBJECTS, NOT HASHCODES (WHICH IS THE DEFAULT) @Override public String toString() { return "Vehicle [make=" + make + ", model=" + model + ", price=" + price + ", fourWDrive=" + fourWDrive + "]"; } public Vehicle(String make, String model, int price, boolean fourWDrive) { super(); this.make = make; this.model = model; this.price = price; this.fourWDrive = fourWDrive; } public String getMake() { return make; } public void setMake(String make) { this.make = make; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public boolean isFourWDrive() { return fourWDrive; } public void setFourWDrive(boolean fourWDrive) { this.fourWDrive = fourWDrive; } }
true
4a9f3c1133710320530bcac6725b17fe92ae5cec
Java
tang1007/obama
/app/src/main/java/com/ksk/obama/fragment/TechnicianNoFragment.java
UTF-8
3,088
1.96875
2
[]
no_license
package com.ksk.obama.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.gson.Gson; import com.ksk.obama.R; import com.ksk.obama.adapter.TechnicianNoAdapter; import com.ksk.obama.callback.IHttpCallBack; import com.ksk.obama.custonview.OnRecyclClickListener; import com.ksk.obama.custonview.SpaceItemDecoration; import com.ksk.obama.model.Technician; import com.ksk.obama.utils.NetworkUrl; import com.ksk.obama.utils.SharedUtil; import com.ksk.obama.utils.Utils; import com.orhanobut.logger.Logger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by djy on 2017/2/22. */ public class TechnicianNoFragment extends BaseFragment { private RecyclerView rlv; private TechnicianNoAdapter adapter; private List<Technician.ResultDataBean.EmployeeBean> list = new ArrayList<>(); @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_house_no, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); rlv = (RecyclerView) getView().findViewById(R.id.rly); GridLayoutManager gridLayoutManager = new GridLayoutManager(activity, 3); rlv.setLayoutManager(gridLayoutManager); SpaceItemDecoration spaceItemDecoration = new SpaceItemDecoration(3, 30, false); rlv.addItemDecoration(spaceItemDecoration); adapter = new TechnicianNoAdapter(activity, list); rlv.setAdapter(adapter); getHttpData(); adapter.setOnClickRecyclLIstener(new OnRecyclClickListener() { @Override public void OnClickRecyclListener(int position) { Utils.showToast(activity,position+""); } }); } private void getHttpData() { Map<String, String> map = new HashMap<>(); map.put("dbName", SharedUtil.getSharedData(activity, "dbname")); map.put("ShopID", SharedUtil.getSharedData(activity, "shopid")); postToHttp(NetworkUrl.PERSON, map, new IHttpCallBack() { @Override public void OnSucess(String jsonText) { Logger.e(jsonText); Technician houseNo = new Gson().fromJson(jsonText, Technician.class); if (houseNo.getResult_stadus().equals("SUCCESS")) { list.clear(); list.addAll(houseNo.getResult_data().getEmployee()); if (list != null) { adapter.notifyDataSetChanged(); } } } @Override public void OnFail(String message) { } }); } }
true
86fc4bd8228272f71a691b6ca2be9b64ed0f90b4
Java
meistermeier/QuickReminder
/src/com/meistermeier/reminder/TaskItem.java
UTF-8
545
2.25
2
[]
no_license
package com.meistermeier.reminder; /** * Some nice information */ public interface TaskItem { final static String ID_FIELD = "_id"; final static String NAME_FIELD = "name"; final static String TIMESTAMP_FIELD = "timestamp"; final static String REMINDER_FIELD = "reminder"; long getId(); void setId(long id); String getName(); void setName(String name); long getTimestamp(); void setTimestamp(long dueDate); Boolean isReminderActive(); void setReminderActive(boolean reminderActive); }
true
66f06e31cfbba8062c311ff7ccb67dffd73de58e
Java
rainlf/rainlf-framework
/src/main/java/com/railf/framework/infrastructure/mail/MailSenderProperties.java
UTF-8
448
1.867188
2
[ "MIT" ]
permissive
package com.railf.framework.infrastructure.mail; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; /** * @author : rain * @date : 2021/5/6 13:43 */ @Data @ConfigurationProperties(prefix = "framework.mail") public class MailSenderProperties { private Boolean enable = Boolean.FALSE; private String host; private Integer port; private String username; private String password; }
true
f10072759081dbe27c48c4d7abd04c76030561f8
Java
MarcoGan/renren-security
/renren-admin/src/main/java/io/renren/modules/sys/service/impl/WarehouseinRecordsServiceImpl.java
UTF-8
9,836
1.9375
2
[ "Apache-2.0" ]
permissive
package io.renren.modules.sys.service.impl; import org.apache.commons.lang.StringUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import java.io.InputStream; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import io.renren.common.utils.PageUtils; import io.renren.common.utils.Query; import io.renren.modules.sys.dao.WarehouseinRecordsDao; import io.renren.modules.sys.entity.WarehouseinRecordsEntity; import io.renren.modules.sys.service.WarehouseinRecordsService; @Service("warehouseinRecordsService") public class WarehouseinRecordsServiceImpl extends ServiceImpl<WarehouseinRecordsDao, WarehouseinRecordsEntity> implements WarehouseinRecordsService { @Autowired private WarehouseinRecordsService warehouseinRecordsService; @Autowired private WarehouseinRecordsDao WarehouseinRecordsDao; @Override public PageUtils queryPage(Map<String, Object> params) { String startlogtime = (String)params.get("startlogtime"); String endlogtime = (String)params.get("endlogtime"); Page<WarehouseinRecordsEntity> page = this.selectPage( new Query<WarehouseinRecordsEntity>(params).getPage(), new EntityWrapper<WarehouseinRecordsEntity>() .ge(StringUtils.isNotBlank(startlogtime),"logtime", startlogtime) .le(StringUtils.isNotBlank(endlogtime),"logtime", endlogtime) ); return new PageUtils(page); } @Transactional(readOnly = false,rollbackFor = Exception.class) @Override public boolean batchImport(String fileName, MultipartFile file) throws Exception { boolean notNull = false; List<WarehouseinRecordsEntity> warehouseList = new ArrayList<WarehouseinRecordsEntity>(); if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) { throw new MyException("上传文件格式不正确"); } boolean isExcel2003 = true; if (fileName.matches("^.+\\.(?i)(xlsx)$")) { isExcel2003 = false; } InputStream is = file.getInputStream(); Workbook wb = null; if (isExcel2003) { wb = new HSSFWorkbook(is); } else { wb = new XSSFWorkbook(is); } Sheet sheet = wb.getSheetAt(0); if(sheet!=null){ notNull = true; } WarehouseinRecordsEntity WarehouseinRecordsEntity; for (int r = 1; r <= sheet.getLastRowNum()-1; r++) { Row row = sheet.getRow(r); if (row == null){ continue; } WarehouseinRecordsEntity = new WarehouseinRecordsEntity(); Date logtime = null; String date; if(row.getCell(0)!=null){ date = row.getCell(0).getStringCellValue(); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); logtime = dateFormat.parse(date); }else{ logtime = null; } String reviewSign; if(row.getCell(1)!=null){ reviewSign = row.getCell(1).getStringCellValue(); }else{ reviewSign = ""; } String receiptNumber; if(row.getCell(2)!=null){ receiptNumber = row.getCell(2).getStringCellValue(); }else{ receiptNumber = ""; } String supplier; if(row.getCell(3)!=null){ supplier = row.getCell(3).getStringCellValue(); }else{ supplier = ""; } String digest; if(row.getCell(4)!=null){ digest = row.getCell(4).getStringCellValue(); }else{ digest = ""; } String warehouse; if(row.getCell(5)!=null){ warehouse = row.getCell(5).getStringCellValue(); }else{ warehouse = ""; } String materialCode; if(row.getCell(6)!=null){ materialCode = row.getCell(6).getStringCellValue(); }else{ materialCode = ""; } String materialName; if(row.getCell(7)!=null){ materialName = row.getCell(7).getStringCellValue(); }else{ materialName = ""; } String materialModel; if(row.getCell(8)!=null){ materialModel = row.getCell(8).getStringCellValue(); }else{ materialModel = ""; } String unit; if(row.getCell(9)!=null){ unit = row.getCell(9).getStringCellValue(); }else{ unit = ""; } Double receivedQuantity; if(row.getCell(10)!=null){ receivedQuantity = row.getCell(10).getNumericCellValue(); }else{ receivedQuantity = 0.0; } Double unitprice; if(row.getCell(11)!=null){ unitprice = row.getCell(11).getNumericCellValue(); }else{ unitprice = 0.0; } String money; row.getCell(12).setCellType(Cell.CELL_TYPE_STRING); if(row.getCell(12)!=null){ money = row.getCell(12).getStringCellValue(); }else{ money = ""; } Double invoiceNum; if(row.getCell(13)!=null){ invoiceNum = row.getCell(13).getNumericCellValue(); }else{ invoiceNum = 0.0; } String remark; if(row.getCell(14)!=null){ remark = row.getCell(14).getStringCellValue(); }else{ remark = ""; } String deliveryPoints; if(row.getCell(15)!=null){ deliveryPoints = row.getCell(15).getStringCellValue(); }else{ deliveryPoints = ""; } String department; if(row.getCell(16)!=null){ department = row.getCell(16).getStringCellValue(); }else{ department = ""; } String executive; if(row.getCell(17)!=null){ executive = row.getCell(17).getStringCellValue(); }else{ executive = ""; } WarehouseinRecordsEntity.setLogtime(logtime); WarehouseinRecordsEntity.setReviewSign(reviewSign); WarehouseinRecordsEntity.setReceiptNumber(receiptNumber); WarehouseinRecordsEntity.setSupplier(supplier); WarehouseinRecordsEntity.setDigest(digest); WarehouseinRecordsEntity.setWarehouse(warehouse); WarehouseinRecordsEntity.setMaterialCode(materialCode); WarehouseinRecordsEntity.setMaterialName(materialName); WarehouseinRecordsEntity.setMaterialModel(materialModel); WarehouseinRecordsEntity.setUnit(unit); WarehouseinRecordsEntity.setReceivedQuantity(receivedQuantity); WarehouseinRecordsEntity.setUnitprice(unitprice); WarehouseinRecordsEntity.setMoney(money); WarehouseinRecordsEntity.setInvoiceNum(invoiceNum); WarehouseinRecordsEntity.setRemark(remark); WarehouseinRecordsEntity.setDeliveryPoints(deliveryPoints); WarehouseinRecordsEntity.setDepartment(department); WarehouseinRecordsEntity.setExecutive(executive); warehouseList.add(WarehouseinRecordsEntity); } for (WarehouseinRecordsEntity warehouseResord : warehouseList) { String receiptNumber = warehouseResord.getReceiptNumber(); int cnt = WarehouseinRecordsDao.selectByWarehouseResord(receiptNumber); if (cnt == 0) { warehouseinRecordsService.insert(warehouseResord); System.out.println(" 插入 "+warehouseResord); } else { WarehouseinRecordsDao.updateWarehouseByName(warehouseResord); System.out.println(" 更新 "+warehouseResord); } } /*warehouseinRecordsService.insert(warehouseResord); }*/ return notNull; } @Override public double getTotalQuantity(String startlogtime, String endlogtime) { // TODO Auto-generated method stub double total = WarehouseinRecordsDao.getTotalQuantity(startlogtime,endlogtime); return total; } @Override public double getTotalMoney(String startlogtime, String endlogtime) { double total = WarehouseinRecordsDao.getTotalMoney(startlogtime,endlogtime); return total; } @Override public double getTotalInvoiceNum(String startlogtime, String endlogtime) { double total = WarehouseinRecordsDao.getTotalInvoiceNum(startlogtime,endlogtime); return total; } }
true
dd114895e509eadc9ac9f59429778e87ad9e108a
Java
qqins/SpringLearn
/src/main/java/edu/cqupt/eini/chapter10/service/CustomerService.java
UTF-8
227
1.890625
2
[]
no_license
package edu.cqupt.eini.chapter10.service; import edu.cqupt.eini.chapter10.po.Customer; /** * @author: Hello World * @date: 2018/8/18 11:04 */ public interface CustomerService { public void addCustomer(Customer customer); }
true
4fb5b061f84d0cbba2c72319efa2899156126887
Java
luizvbo/ssr
/src/ec/ssr/core/ParallelVersions/SSR2/NormalizedFunction.java
UTF-8
1,300
2.609375
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 ec.ssr.core.ParallelVersions.SSR2; import ec.gp.GPNode; import ec.ssr.functions.Function; /** * * @author luiz */ public class NormalizedFunction implements Function{ protected Function function; protected NormalizationParameters parameters; public NormalizedFunction(double mean, double std) { parameters = new NormalizationParameters(mean, std); } public NormalizedFunction(Function function, NormalizationParameters parameters) { this.function = function; this.parameters = parameters; } public void setFunction(Function function) { this.function = function; } public double unormalizedEval(double[] val) { return function.eval(val); } @Override public double eval(double[] val) { return (function.eval(val)*(parameters.std))+parameters.mean; } @Override public String print() { return "(" + parameters.std + "*(" + function.print() + ")+" + parameters.mean + ")"; } @Override public int getNumNodes(){ return function.getNumNodes(); } }
true
b5339851ed9045684a754c578a3fb6f69a8b3299
Java
GitSahib/cs544_group_a_shoping_store
/src/main/java/mum/edu/webstore/controller/BCheckoutController.java
UTF-8
9,057
1.828125
2
[ "MIT" ]
permissive
package mum.edu.webstore.controller; import java.math.BigDecimal; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.braintreegateway.BraintreeGateway; import com.braintreegateway.CreditCard; import com.braintreegateway.Result; import com.braintreegateway.Transaction; import com.braintreegateway.Transaction.Status; import com.braintreegateway.TransactionRequest; import com.braintreegateway.ValidationError; import mum.edu.webstore.WebStoreAppCtxHolder; import mum.edu.webstore.model.Cart; import mum.edu.webstore.model.CartItem; import mum.edu.webstore.model.Customer; import mum.edu.webstore.model.Order; import mum.edu.webstore.model.OrderItem; import mum.edu.webstore.model.PaymentType; import mum.edu.webstore.service.CartItemService; import mum.edu.webstore.service.CustomerService; import mum.edu.webstore.service.OrderService; @RequestMapping(value = "/gateway/") @Controller public class BCheckoutController { @Autowired private CustomerService customerService; @Autowired private CartItemService cartItemService; @Autowired private OrderService orderService; private BraintreeGateway gateway = WebStoreAppCtxHolder.gateway; private Status[] TRANSACTION_SUCCESS_STATUSES = new Status[] { Transaction.Status.AUTHORIZED, Transaction.Status.AUTHORIZING, Transaction.Status.SETTLED, Transaction.Status.SETTLEMENT_CONFIRMED, Transaction.Status.SETTLEMENT_PENDING, Transaction.Status.SETTLING, Transaction.Status.SUBMITTED_FOR_SETTLEMENT }; @RequestMapping(value = "/", method = RequestMethod.GET) public String root(Model model) { return "redirect:/gateway/checkouts"; } @RequestMapping(value = "/checkouts", method = RequestMethod.GET) public String checkout(Model model,HttpServletRequest request) { String clientToken = gateway.clientToken().generate(); model.addAttribute("clientToken", clientToken); String name = request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : ""; Customer customer = customerService.getByEmail(name.toString()); Cart cart = customer.getCart(); if(cart.getCartItems().size() <= 0) { return "redirect:/checkout"; } model.addAttribute("order",new Order()); model.addAttribute("amount",cart.getGrandTotal()); return "checkouts/new"; } @RequestMapping(value = "/checkout/{order_id}", method = RequestMethod.GET) public String checkoutOrder(@PathVariable long order_id, Model model,HttpServletRequest request) { Order order = orderService.get(order_id); String clientToken = gateway.clientToken().generate(); model.addAttribute("clientToken", clientToken); /* String name = request.getUserPrincipal() != null ? request.getUserPrincipal().getName() : ""; Customer customer = customerService.getByEmail(name.toString()); Cart cart = customer.getCart(); if(cart.getCartItems().size() <= 0) { return "redirect:/checkout"; } */ model.addAttribute("order", order); model.addAttribute("amount",order.getTotal()); return "checkouts/new"; } @RequestMapping(value = "/checkouts", method = RequestMethod.POST) public String postForm(@Valid Order order, @RequestParam("amount") String amount, @RequestParam("payment_method_nonce") String nonce, Model model, final RedirectAttributes redirectAttributes,HttpServletRequest req) { BigDecimal decimalAmount; try { decimalAmount = new BigDecimal(amount); } catch (NumberFormatException e) { redirectAttributes.addFlashAttribute("errorDetails", "Error: 81503: Amount is an invalid format."); return "redirect:/gateway/checkouts"; } TransactionRequest request = new TransactionRequest() .amount(decimalAmount) .paymentMethodNonce(nonce) .options() .submitForSettlement(true) .done(); Result<Transaction> result = gateway.transaction().sale(request); if (result.isSuccess()) { Transaction transaction = result.getTarget(); String name = req.getUserPrincipal() != null ? req.getUserPrincipal().getName() : ""; Customer customer = customerService.getByEmail(name.toString()); Cart cart = customer.getCart(); return "redirect:/gateway/checkouts/" + transaction.getId(); } else if (result.getTransaction() != null) { Transaction transaction = result.getTransaction(); return "redirect:/gateway/checkouts/" + transaction.getId(); } else { String errorString = ""; for (ValidationError error : result.getErrors().getAllDeepValidationErrors()) { errorString += "Error: " + error.getCode() + ": " + error.getMessage() + "\n"; } redirectAttributes.addFlashAttribute("errorDetails", errorString); return "redirect:/gateway/checkouts"; } } @RequestMapping(value = "/checkoutorder/{order_id}", method = RequestMethod.POST) public String checkoutOrder(@PathVariable long order_id, @RequestParam("amount") String amount, @RequestParam("payment_method_nonce") String nonce, Model model, final RedirectAttributes redirectAttributes,HttpServletRequest req) { Order order = orderService.get(order_id); BigDecimal decimalAmount; try { decimalAmount = new BigDecimal(amount); } catch (NumberFormatException e) { redirectAttributes.addFlashAttribute("errorDetails", "Error: 81503: Amount is an invalid format."); return "redirect:/gateway/checkouts"; } TransactionRequest request = new TransactionRequest() .amount(decimalAmount) .orderId(""+order.getId()) .paymentMethodNonce(nonce) .options() .submitForSettlement(true) .done(); Result<Transaction> result = gateway.transaction().sale(request); if (result.isSuccess()) { Transaction transaction = result.getTarget(); String name = req.getUserPrincipal() != null ? req.getUserPrincipal().getName() : ""; Customer customer = customerService.getByEmail(name.toString()); Cart cart = customer.getCart(); order.setPaid(true); orderService.save(order); //cartItemService.removeAllCartItems(cart); return "redirect:/gateway/checkouts/" + transaction.getId(); } else if (result.getTransaction() != null) { Transaction transaction = result.getTransaction(); return "redirect:/gateway/checkouts/" + transaction.getId(); } else { String errorString = ""; for (ValidationError error : result.getErrors().getAllDeepValidationErrors()) { errorString += "Error: " + error.getCode() + ": " + error.getMessage() + "\n"; } redirectAttributes.addFlashAttribute("errorDetails", errorString); return "redirect:/gateway/checkouts"; } } @RequestMapping(value = "/checkouts/{transactionId}") public String getTransaction(Order order, @PathVariable String transactionId, Model model) { Transaction transaction; CreditCard creditCard; com.braintreegateway.Customer customer; try { transaction = gateway.transaction().find(transactionId); creditCard = transaction.getCreditCard(); customer = transaction.getCustomer(); } catch (Exception e) { System.out.println("Exception: " + e); return "redirect:/gateway/checkouts"; } model.addAttribute("order", order); model.addAttribute("isSuccess", Arrays.asList(TRANSACTION_SUCCESS_STATUSES).contains(transaction.getStatus())); model.addAttribute("transaction", transaction); model.addAttribute("creditCard", creditCard); model.addAttribute("customer", customer); return "checkouts/show"; } }
true
7583dbdd31fc6d2c4177df97f0c33b6e2a80033e
Java
elkont/Harmonic-sequence
/Harmonic1.java
UTF-8
252
3.171875
3
[]
no_license
class Harmonic1{ public static void main(String args[]){ int num = 1; double result = 0.0; while(num <= 5){ result = result + (double) 1 / num; num++; System.out.println("Output of Harmonic Series is "+result); } } }
true
42df58baccaf26e9c640f0e7a551f1c3dc8386c7
Java
PearsonEducation/StatsAgg
/src/main/java/com/pearson/statsagg/database_objects/suspensions/SuspensionsSql.java
UTF-8
7,834
2.046875
2
[ "Apache-2.0" ]
permissive
package com.pearson.statsagg.database_objects.suspensions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Jeffrey Schmidt */ public class SuspensionsSql { private static final Logger logger = LoggerFactory.getLogger(SuspensionsSql.class.getName()); protected final static String DropTable_Suspensions = "DROP TABLE SUSPENSIONS"; protected final static String CreateTable_Suspensions_Derby = "CREATE TABLE SUSPENSIONS (" + "ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), " + "NAME VARCHAR(500) NOT NULL, " + "UPPERCASE_NAME VARCHAR(500) NOT NULL, " + "DESCRIPTION CLOB(1048576) NOT NULL, " + "IS_ENABLED BOOLEAN NOT NULL, " + "SUSPEND_BY INTEGER NOT NULL, " + "ALERT_ID INTEGER, " + "METRIC_GROUP_TAGS_INCLUSIVE CLOB(1048576), " + "METRIC_GROUP_TAGS_EXCLUSIVE CLOB(1048576), " + "METRIC_SUSPENSION_REGEXES CLOB(1048576), " + "IS_ONE_TIME BOOLEAN NOT NULL, " + "IS_SUSPEND_NOTIFICATION_ONLY BOOLEAN NOT NULL, " + "IS_RECUR_SUNDAY BOOLEAN NOT NULL, " + "IS_RECUR_MONDAY BOOLEAN NOT NULL, " + "IS_RECUR_TUESDAY BOOLEAN NOT NULL, " + "IS_RECUR_WEDNESDAY BOOLEAN NOT NULL, " + "IS_RECUR_THURSDAY BOOLEAN NOT NULL, " + "IS_RECUR_FRIDAY BOOLEAN NOT NULL, " + "IS_RECUR_SATURDAY BOOLEAN NOT NULL, " + "START_DATE TIMESTAMP NOT NULL, " + "START_TIME TIMESTAMP NOT NULL, " + "DURATION BIGINT NOT NULL, " + "DURATION_TIME_UNIT INTEGER NOT NULL, " + "DELETE_AT_TIMESTAMP TIMESTAMP " + ")"; protected final static String CreateTable_Suspensions_MySQL = "CREATE TABLE SUSPENSIONS (" + "ID INTEGER AUTO_INCREMENT PRIMARY KEY NOT NULL, " + "NAME VARCHAR(500) NOT NULL, " + "UPPERCASE_NAME VARCHAR(500) NOT NULL, " + "DESCRIPTION MEDIUMTEXT NOT NULL, " + "IS_ENABLED BOOLEAN NOT NULL, " + "SUSPEND_BY INTEGER NOT NULL, " + "ALERT_ID INTEGER, " + "METRIC_GROUP_TAGS_INCLUSIVE MEDIUMTEXT, " + "METRIC_GROUP_TAGS_EXCLUSIVE MEDIUMTEXT, " + "METRIC_SUSPENSION_REGEXES MEDIUMTEXT, " + "IS_ONE_TIME BOOLEAN NOT NULL, " + "IS_SUSPEND_NOTIFICATION_ONLY BOOLEAN NOT NULL, " + "IS_RECUR_SUNDAY BOOLEAN NOT NULL, " + "IS_RECUR_MONDAY BOOLEAN NOT NULL, " + "IS_RECUR_TUESDAY BOOLEAN NOT NULL, " + "IS_RECUR_WEDNESDAY BOOLEAN NOT NULL, " + "IS_RECUR_THURSDAY BOOLEAN NOT NULL, " + "IS_RECUR_FRIDAY BOOLEAN NOT NULL, " + "IS_RECUR_SATURDAY BOOLEAN NOT NULL, " + "START_DATE TIMESTAMP NULL DEFAULT NULL, " + "START_TIME TIMESTAMP NULL DEFAULT NULL, " + "DURATION BIGINT NOT NULL, " + "DURATION_TIME_UNIT INTEGER NOT NULL, " + "DELETE_AT_TIMESTAMP TIMESTAMP NULL DEFAULT NULL" + ") " + "ROW_FORMAT=DYNAMIC"; protected final static String CreateIndex_Suspensions_PrimaryKey = "ALTER TABLE SUSPENSIONS " + "ADD CONSTRAINT AS_PK PRIMARY KEY (ID)"; protected final static String CreateIndex_Suspensions_Unique_Name = "ALTER TABLE SUSPENSIONS ADD CONSTRAINT AS_U_NAME UNIQUE (" + "NAME" + ")"; protected final static String CreateIndex_Suspensions_Unique_UppercaseName = "ALTER TABLE SUSPENSIONS ADD CONSTRAINT AS_U_UPPERCASE_NAME UNIQUE (" + "UPPERCASE_NAME" + ")"; protected final static String CreateIndex_Suspensions_SuspendBy = "CREATE INDEX AS_SUSPEND_BY ON SUSPENSIONS(SUSPEND_BY)"; protected final static String CreateIndex_Suspensions_DeleteAtTimestamp = "CREATE INDEX AS_DELETE_AT_TIMESTAMP ON SUSPENSIONS(DELETE_AT_TIMESTAMP)"; protected final static String CreateIndex_Suspensions_ForeignKey_AlertId = "ALTER TABLE SUSPENSIONS " + "ADD CONSTRAINT AS_AID_FK FOREIGN KEY (ALERT_ID) " + "REFERENCES ALERTS(ID)"; protected final static String Select_Suspension_ByPrimaryKey = "SELECT * FROM SUSPENSIONS " + "WHERE ID = ?"; protected final static String Select_Suspension_ByName = "SELECT * FROM SUSPENSIONS " + "WHERE NAME = ?"; protected final static String Select_AllSuspensions = "SELECT * FROM SUSPENSIONS"; protected final static String Select_SuspensionId_BySuspendBy = "SELECT ID FROM SUSPENSIONS " + "WHERE SUSPEND_BY = ?"; protected final static String Select_Suspension_BySuspendBy = "SELECT * FROM SUSPENSIONS " + "WHERE SUSPEND_BY = ?"; protected final static String Insert_Suspension = "INSERT INTO SUSPENSIONS " + "(NAME, UPPERCASE_NAME, DESCRIPTION, IS_ENABLED, SUSPEND_BY, ALERT_ID, METRIC_GROUP_TAGS_INCLUSIVE, METRIC_GROUP_TAGS_EXCLUSIVE, METRIC_SUSPENSION_REGEXES, " + "IS_ONE_TIME, IS_SUSPEND_NOTIFICATION_ONLY, " + "IS_RECUR_SUNDAY, IS_RECUR_MONDAY, IS_RECUR_TUESDAY, IS_RECUR_WEDNESDAY, IS_RECUR_THURSDAY, IS_RECUR_FRIDAY, IS_RECUR_SATURDAY, " + "START_DATE, START_TIME, DURATION, DURATION_TIME_UNIT, DELETE_AT_TIMESTAMP) " + "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; protected final static String Update_Suspension_ByPrimaryKey = "UPDATE SUSPENSIONS " + "SET NAME = ?, UPPERCASE_NAME = ?, DESCRIPTION = ?, IS_ENABLED = ?, SUSPEND_BY = ?, ALERT_ID = ?, " + "METRIC_GROUP_TAGS_INCLUSIVE = ?, METRIC_GROUP_TAGS_EXCLUSIVE = ?, METRIC_SUSPENSION_REGEXES = ?, IS_ONE_TIME = ?, IS_SUSPEND_NOTIFICATION_ONLY = ?, " + "IS_RECUR_SUNDAY = ?, IS_RECUR_MONDAY = ?, IS_RECUR_TUESDAY = ?, IS_RECUR_WEDNESDAY = ?, " + "IS_RECUR_THURSDAY = ?, IS_RECUR_FRIDAY = ?, IS_RECUR_SATURDAY = ?, " + "START_DATE = ?, START_TIME = ?, DURATION = ?, DURATION_TIME_UNIT = ?, DELETE_AT_TIMESTAMP = ? " + "WHERE ID = ?"; protected final static String Delete_Suspension_ByPrimaryKey = "DELETE FROM SUSPENSIONS " + "WHERE ID = ?"; protected final static String Delete_Suspension_DeleteAtTimestamp = "DELETE FROM SUSPENSIONS " + "WHERE DELETE_AT_TIMESTAMP <= ?"; protected final static String Select_Suspension_ByPageNumberAndPageSize_Derby = "SELECT ID, NAME FROM SUSPENSIONS ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; protected final static String Select_Suspension_ByPageNumberAndPageSize_MySQL = "SELECT ID, NAME FROM SUSPENSIONS ORDER BY ID ASC LIMIT ?,?"; }
true
bc0ece8316c2685e857e9a11b7342437dfc49a62
Java
dwursteisen/formation
/05 - Threads/src/com/github/dwursteisen/threads/webservice/IWebservice.java
UTF-8
264
1.929688
2
[]
no_license
package com.github.dwursteisen.threads.webservice; /** * User: Wursteisen David * Date: 22/10/11 * Time: 22:46 */ public interface IWebservice { void demarrage(); String interrogation(); void arret(); boolean isVivant(); String nomService(); }
true
4a99879e5642ab1bf0011d7dbfbc6c510dbeda33
Java
porali2000/shuffler
/restapi/src/main/java/com/controllers/GamingController.java
UTF-8
2,585
2.59375
3
[]
no_license
package com.controllers; import com.models.Deck; import com.service.GamingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.*; import java.util.List; import static org.springframework.web.bind.annotation.RequestMethod.*; /** * Created by Porali_S on 12/14/2016. */ @RestController public class GamingController { @Autowired GamingService gamingService; @RequestMapping(path = "/deck", method = PUT) @ResponseBody String newNamedDeck(@RequestParam String deckName) { try { this.gamingService.putNewNamedDeck(deckName); return "OK"; } catch (Exception e) { throw new RuntimeException(e); } } @RequestMapping(path = "/shuffle", method = POST) @ResponseBody Object shuffleExistingNamedDeck(@RequestBody String deckName) { try { List<Deck> decks = this.gamingService.shuffleExistingNamedDeck(deckName); if ( ObjectUtils.isEmpty(decks)) { throw new RuntimeException("No Deck Available"); } return decks.toString(); } catch (Exception e) { throw new RuntimeException(e); } } @RequestMapping(path = "/decks", method = GET) @ResponseBody Object persistedDecks() { try { List<String> persistedDecks = this.gamingService.getPersistedDecks(); if(ObjectUtils.isEmpty(persistedDecks)) throw new RuntimeException("No Data Found"); return persistedDecks; } catch (Exception e) { throw new RuntimeException(e); } } @RequestMapping(path = "/deck", method = GET) @ResponseBody Object getNamedDeck(@RequestParam String deckName) { try { Deck namedDeck = this.gamingService.getNamedDeck(deckName); if (null == namedDeck) throw new RuntimeException("Unable to find -" + deckName); return namedDeck.toString(); } catch (Exception e) { throw new RuntimeException(e); } } @RequestMapping(path = "/deck", method = DELETE) @ResponseBody Object deleteNamedDeck(@RequestParam String deckName) { try { if (!this.gamingService.purgeNamedDeck(deckName)) throw new RuntimeException("Unable to delete -" + deckName); return "Done"; } catch (Exception e) { throw new RuntimeException(e); } } }
true
9278b847a80ae7a906f102b901f9b389d381f55f
Java
radhadevi11/LmsApp
/src/main/java/com/glosys/lms/entity/WorkshopType.java
UTF-8
3,390
2.578125
3
[]
no_license
package com.glosys.lms.entity; import javax.persistence.*; @Table(name = "workshop_type") @Entity public class WorkshopType { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "workshop_type_id") private Integer id; @Column(name = " mode_of_training") private String modeOfTraining; @Column(name = "no_of_workshops ") private int noOfWorkshops; @Column(name = "total_days") private int totalDays; @Column (name = "total_hours" ) private int totalHours; @Column(name = "hours_per_day") private int hoursPerDay; @Column(name = "package") private String workshopPackage; @Column(name = "cost") private double cost; public WorkshopType() { } public WorkshopType(String modeOfTraining, int noOfWorkshops, int totalDays, int totalHours, int hoursPerDay, String workshopPackage, double cost) { this(null, modeOfTraining, noOfWorkshops, totalDays, totalHours, hoursPerDay, workshopPackage, cost); } public WorkshopType(Integer id, String modeOfTraining, int noOfWorkshops, int totalDays, int totalHours, int hoursPerDay, String workshopPackage, double cost) { this.id = id; this.modeOfTraining = modeOfTraining; this.noOfWorkshops = noOfWorkshops; this.totalDays = totalDays; this.totalHours = totalHours; this.hoursPerDay = hoursPerDay; this.workshopPackage = workshopPackage; this.cost = cost; } public WorkshopType(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getModeOfTraining() { return modeOfTraining; } public void setModeOfTraining(String modeOfTraining) { this.modeOfTraining = modeOfTraining; } public int getNoOfWorkshops() { return noOfWorkshops; } public void setNoOfWorkshops(int noOfWorkshops) { this.noOfWorkshops = noOfWorkshops; } public int getTotalDays() { return totalDays; } public void setTotalDays(int totalDays) { this.totalDays = totalDays; } public int getTotalHours() { return totalHours; } public void setTotalHours(int totalHours) { this.totalHours = totalHours; } public int getHoursPerDay() { return hoursPerDay; } public void setHoursPerDay(int hoursPerDay) { this.hoursPerDay = hoursPerDay; } public String getWorkshopPackage() { return workshopPackage; } public void setWorkshopPackage(String workshopPackage) { this.workshopPackage = workshopPackage; } public double getCost() { return cost; } public void setCost(double cost) { this.cost = cost; } @Override public String toString() { return "WorkshopType{" + "id=" + id + ", modeOfTraining='" + modeOfTraining + '\'' + ", noOfWorkshops=" + noOfWorkshops + ", totalDays=" + totalDays + ", totalHours=" + totalHours + ", hoursPerDay=" + hoursPerDay + ", workshopPackage='" + workshopPackage + '\'' + ", cost=" + cost + '}'; } }
true
bb049aec8559fe65359c22ee7f51c85b9be7daa4
Java
mirek190/x86-android-5.0
/cts/apps/CtsVerifier/src/com/android/cts/verifier/bluetooth/BleScannerHardwareScanFilterActivity.java
UTF-8
5,871
1.8125
2
[]
no_license
/* * Copyright (C) 2013 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 com.android.cts.verifier.bluetooth; import com.android.cts.verifier.PassFailButtons; import com.android.cts.verifier.R; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; public class BleScannerHardwareScanFilterActivity extends PassFailButtons.Activity { private static final String TAG = "BleScannerHardwareScanFilter"; private ListView mScanResultListView; private MapAdapter mAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ble_scanner_hardware_scan_filter); setPassFailButtonClickListeners(); setInfoResources(R.string.ble_scanner_scan_filter_name, R.string.ble_scanner_scan_filter_info, -1); mScanResultListView = (ListView)findViewById(R.id.ble_scan_result_list); mAdapter = new MapAdapter(); mScanResultListView.setAdapter(mAdapter); ((Button) findViewById(R.id.ble_scan_with_filter)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(BleScannerHardwareScanFilterActivity.this, BleScannerService.class); intent.putExtra(BleScannerService.EXTRA_COMMAND, BleScannerService.COMMAND_SCAN_WITH_FILTER); startService(intent); } }); ((Button) findViewById(R.id.ble_scan_without_filter)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(BleScannerHardwareScanFilterActivity.this, BleScannerService.class); intent.putExtra(BleScannerService.EXTRA_COMMAND, BleScannerService.COMMAND_SCAN_WITHOUT_FILTER); startService(intent); } }); } @Override public void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction(BleScannerService.BLE_SCAN_RESULT); registerReceiver(onBroadcast, filter); } private BroadcastReceiver onBroadcast = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case BleScannerService.BLE_SCAN_RESULT: String uuid = intent.getStringExtra(BleScannerService.EXTRA_UUID); String data = intent.getStringExtra(BleScannerService.EXTRA_DATA); if (data != null) { mAdapter.addItem(uuid + " : " + data); } break; } } }; @Override public void onPause() { super.onPause(); unregisterReceiver(onBroadcast); } private void stop() { stopService(new Intent(this, BleScannerService.class)); } @Override public void onDestroy() { super.onDestroy(); stop(); } public class MapAdapter extends BaseAdapter { private Map<String, Integer> mData; private ArrayList<String> mKeys; public MapAdapter() { mData = new HashMap<>(); mKeys = new ArrayList<>(); } @Override public int getCount() { return mData.size(); } @Override public Object getItem(int position) { return mData.get(mKeys.get(position)); } @Override public long getItemId(int arg0) { return arg0; } public void addItem(String key) { if (!mData.containsKey(key)) { mKeys.add(key); mData.put(key, new Integer(1)); } else { mData.put(key, mData.get(key) + 1); } this.notifyDataSetChanged(); } @Override public View getView(int pos, View view, ViewGroup parent) { if (view == null) { view = LayoutInflater.from(parent.getContext()) .inflate(android.R.layout.simple_list_item_2, parent, false); } String key = mKeys.get(pos); String value = getItem(pos).toString(); TextView text1 = (TextView) view.findViewById(android.R.id.text1); TextView text2 = (TextView) view.findViewById(android.R.id.text2); text1.setText(key); text2.setText(value); return view; } } }
true
2aa623d25d56f7d703314e8fa46e4ef388750812
Java
helloGB20171008/-123-
/src/com/easy/mapper/CarTypeMapper.java
UTF-8
153
1.8125
2
[]
no_license
package com.easy.mapper; import java.util.List; import com.easy.model.CarType; public interface CarTypeMapper { public List<CarType> selectAll(); }
true
20d5d6a1966a20bc66b655ec6e89680e846c55cf
Java
google-code-export/meta-editor
/MEditor/src/cz/fi/muni/xkremser/editor/client/view/other/ScanRecord.java
UTF-8
5,657
2.1875
2
[]
no_license
/* * Metadata Editor * @author Jiri Kremser * * * * Metadata Editor - Rich internet application for editing metadata. * Copyright (C) 2011 Jiri Kremser (kremser@mzk.cz) * Moravian Library in Brno * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * */ package cz.fi.muni.xkremser.editor.client.view.other; import com.smartgwt.client.widgets.tile.TileRecord; import cz.fi.muni.xkremser.editor.client.util.Constants; // TODO: Auto-generated Javadoc /** * The Class PageRecord. */ public class ScanRecord extends TileRecord { /** * Instantiates a new page record. */ public ScanRecord() { } /** * Instantiates a new page record. * * @param scanIndex * the scanIndex * @param name * the name * @param issn * the issn * @param picture * the picture * @param path * the path */ public ScanRecord(int scanIndex, String name, String model, String barcode, String picture, String path, String pageType) { setScanIndex(scanIndex); setName(name); setModel(model); setBarcode(barcode); setPicture(picture); setPath(path); setPageType(pageType); } /** * Set the scanIndex. * * @param scanIndex * the scanIndex */ public void setScanIndex(int scanIndex) { setAttribute(Constants.ATTR_SCAN_INDEX, scanIndex); } /** * Return the scanIndex. * * @return the scanIndex */ public int getScanIndex() { return getAttributeAsInt(Constants.ATTR_SCAN_INDEX); } /** * Set the name. * * @param name * the name */ public void setName(String name) { setAttribute(Constants.ATTR_NAME, name); } /** * Return the name. * * @return the name */ public String getName() { return getAttribute(Constants.ATTR_NAME); } /** * Set the model. * * @param model * the model */ public void setModel(String model) { setAttribute(Constants.ATTR_MODEL, model); } /** * Return the model. * * @return the model */ public String getModel() { return getAttribute(Constants.ATTR_MODEL); } /** * Set the barcode. * * @param barcode * the barcode */ public void setBarcode(String barcode) { setAttribute(Constants.ATTR_BARCODE, barcode); } /** * Return the barcode. * * @return the barcode */ public String getBarcode() { return getAttribute(Constants.ATTR_BARCODE); } /** * Set the picture. * * @param picture * the picture */ public void setPicture(String picture) { setAttribute(Constants.ATTR_PICTURE, picture); } /** * Return the picture. * * @return the picture */ public String getPicture() { return getAttribute(Constants.ATTR_PICTURE); } /** * Set the path. * * @param path * the path */ public void setPath(String path) { setAttribute(Constants.ATTR_PATH, path); } /** * Return the path. * * @return the path */ public String getPath() { return getAttribute(Constants.ATTR_PATH); } /** * Set the pageType. * * @param pageType * the pageType */ public void setPageType(String pageType) { setAttribute(Constants.ATTR_PAGE_TYPE, pageType); } /** * Return the pageType. * * @return the pageType */ public String getPageType() { return getAttribute(Constants.ATTR_PAGE_TYPE); } /** * Deep copy. * * @return the page record */ public ScanRecord deepCopy() { return new ScanRecord(getScanIndex(), getName(), getModel(), getBarcode(), getPicture(), getPath(), getPageType()); } /** * {@inheritDoc} */ @Override public String toString() { return "ScanRecord [getScanIndex()=" + getScanIndex() + ", getName()=" + getName() + ", getModel()=" + getModel() + ", getBarcode()=" + getBarcode() + ", getPicture()=" + getPicture() + ", getPath()=" + getPath() + ", getPageType()=" + getPageType() + "]"; } }
true
b59644524e773e74d34a5f739fc131be9a31e67e
Java
juexingzero/qgsl1
/src/main/java/com/manhui/gsl/jbqgsl/model/topicevaluate/export/TopicPassiveAndActiveScoreBean.java
UTF-8
892
1.8125
2
[]
no_license
package com.manhui.gsl.jbqgsl.model.topicevaluate.export; import java.util.List; import lombok.Data; /** * @类名称 TopicEvaluateExportBean.java * @类描述 主题评价导出excel * @作者 kevin kwmo1005@163.com * @创建时间 2018年8月27日 下午2:56:07 * @版本 1.00 * * @修改记录 * * <pre> * 版本 修改人 修改日期 修改内容描述 * ---------------------------------------------- * 1.00 kevin 2018年8月27日 创建 * ---------------------------------------------- * </pre> */ @Data public class TopicPassiveAndActiveScoreBean { private String passive_order; //被评价方排名 private String passive_name; //被评价方名称 private String passive_score; //被评价方得分 List<TopicActiveScoreBean> activeScoreList; }
true
2bcf0cf13404cd8ec039bc6ccd8e03896fb39e32
Java
annot8/annot8-common-deprecated
/annot8-common-implementations/src/test/java/io/annot8/common/implementations/configuration/ComponentConfigurerTest.java
UTF-8
3,645
2.078125
2
[ "Apache-2.0" ]
permissive
/* Annot8 (annot8.io) - Licensed under Apache-2.0. */ package io.annot8.common.implementations.configuration; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import io.annot8.common.implementations.context.SimpleContext; import io.annot8.core.components.Processor; import io.annot8.core.components.Resource; import io.annot8.core.context.Context; import io.annot8.core.exceptions.BadConfigurationException; import io.annot8.core.exceptions.MissingResourceException; import io.annot8.core.settings.Settings; @ExtendWith(MockitoExtension.class) class ComponentConfigurerTest { @Mock Resource globalResource; ComponentConfigurer configurer; @BeforeEach public void beforeEach() { Context context = new SimpleContext(Map.of("global", globalResource)); configurer = new ComponentConfigurer(context); } @Test public void globalResourcesAvailable() { final Map<String, Resource> gotResources = configurer.getResources(); assertThat(gotResources).containsEntry("global", globalResource); } @Test void configureEmptyResources() { ResourcesHolder holder = new ResourcesHolder(); final Map<String, Resource> resources = configurer.configureResources(holder); final Map<String, Resource> gotResources = configurer.getResources(); assertThat(gotResources).isEqualTo(resources); // Confirm that our global resource is still there assertThat(gotResources).containsEntry("global", globalResource); assertThat(gotResources).hasSize(1); } @Test void configureResources() throws BadConfigurationException, MissingResourceException { ResourcesHolder holder = new ResourcesHolder(); Resource r = mock(Resource.class); Collection<Settings> settings = new ArrayList<>(); holder.addResource("local", r, settings); final Map<String, Resource> resources = configurer.configureResources(holder); final Map<String, Resource> gotResources = configurer.getResources(); assertThat(gotResources).isEqualTo(resources); // Confirm that our global resource is still there assertThat(gotResources).containsEntry("global", globalResource); // Check rest of resources // Ensure configure has been called verify(r).configure(any(Context.class)); assertThat(gotResources).containsEntry("local", r); } @Test void configureComponents() throws BadConfigurationException, MissingResourceException { ComponentHolder<Processor> holder = new ComponentHolder<>(); Processor p = mock(Processor.class); Collection<Settings> settings = new ArrayList<>(); holder.add(p, settings); Processor q = mock(Processor.class); Collection<Settings> qSettings = new ArrayList<>(); holder.add(q, qSettings); final List<Processor> processors = configurer.configureComponents(holder); assertThat(processors).containsExactly(p, q); verify(p).configure(any(Context.class)); } @Test void configureComponent() throws BadConfigurationException, MissingResourceException { Processor p = mock(Processor.class); Collection<Settings> settings = new ArrayList<>(); configurer.configureComponent(p, settings); verify(p).configure(any(Context.class)); } }
true
be80482abc0d567e0d2fc68126ae2e6e75b792f2
Java
ourCHK/Mines
/app/src/main/java/com/chk/mines/GameActivity.java
UTF-8
24,674
1.84375
2
[]
no_license
package com.chk.mines; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import com.chk.mines.Beans.Mine; import com.chk.mines.Beans.Record; import com.chk.mines.Interfaces.GameState; import com.chk.mines.Interfaces.OnDialogButtonClickListener; import com.chk.mines.CustomDialogs.CustomDialog; import com.chk.mines.CustomViews.MineView; import com.chk.mines.CustomViews.MineViewType1; import com.chk.mines.CustomViews.MineViewType2; import com.chk.mines.CustomViews.MineViewType3; import com.chk.mines.CustomViews.MineViewType4; import com.chk.mines.CustomViews.TimeTextView; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import static com.chk.mines.GameActivity.PointType.DRAG; import static com.chk.mines.GameActivity.PointType.FLAG; public class GameActivity extends BaseActivity implements View.OnClickListener,GameState{ public final static String TAG = GameActivity.class.getSimpleName(); public final static String GAME_TYPE = "GameType"; public final static String SERVER_OR_CLIENT = "ServerOrClient"; public final static int TYPE_1 = 1; //8*8 public final static int TYPE_2 = 1<<1; //16*16 public final static int TYPE_3 = 1<<2; //16*30 public final static int TYPE_4 = 1<<3; //custom public final static int FLAG_IS_SINGLE = 1<<4; public final static int FLAG_IS_DOUBLE = 1<<5; public final static int GAME_OVER = -1; public final static int GAME_SUCCESS = 1; public final static int GAME_PAUSED = 2; public final static int GAME_START = 3; //用于开始计时 public final static int GAME_RESTART = 4; public final static int GAME_INIT = 5; //初始化 public final static int RECEIVED_MESSAGE = 6; public final static int TIME_CHANGED = 8; private int GAME_STATE; //游戏初始化 public final static int PointDown = 10; //接收View传来的消息 Handler mHandler; Timer timer; int time; private int mServerOrClient; private int mChoosedGameType; private boolean isSingle; MineView mMineView; Mine[][] mines; int rows; int columns; int mMineCount; private String mMinesString; //多人游戏时存储的雷的数据 public enum PointType { //用于判断点击下去时是什么状态,挖雷状态还是标记状态,又或者是疑惑雷标记等等 DRAG, FLAG, FLAG_CONFUSED } PointType mCurrentType = DRAG; //默认是挖雷状态 LinearLayout mMainLayout; //整个窗口的Layout LinearLayout mOperateLayout; //操作窗口的Layout // @BindView(R.id.mineViewContainer) LinearLayout mMineViewContainer; // @BindView(R.id.shovel) ImageView mShovel; // @BindView(R.id.flag) ImageView mFlag; // @BindView(R.id.flag_confused) ImageView mFlagConfused; // @BindView(R.id.timeView) TimeTextView mTimeView; // @BindView(R.id.restart) ImageView mRestart; // @BindView(R.id.startAndPaused) ImageView mStartAndPaused; // @BindView(R.id.remainMines) TextView mRemainMines; // @BindView(R.id.gameView) ScrollView mGameView; // @BindView(R.id.pausedView) TextView mPausedView; // ServerConnectService mServerConnectService; // ServiceConnection mServerConnection; // ClientConnectService mClientConnectService; // ServiceConnection mClientConnection; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game_second); init(); } @SuppressLint("HandlerLeak") void init() { // InitBindView.init(this); mMainLayout = findViewById(R.id.mainLayout); // mMainLayout.measure(0,0); mOperateLayout = findViewById(R.id.operateLayout); // mOperateLayout.measure(0,0); int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.EXACTLY); int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.EXACTLY); mMainLayout.measure(w, h); Log.i(TAG,"MainLayout Height:"+mMainLayout.getHeight()+" "+mMainLayout.getMeasuredHeight()); Log.i(TAG,"OperateLayout Height:"+mOperateLayout.getHeight()+" "+mOperateLayout.getMeasuredHeight()); Log.i(TAG,"MainLayout Height:"+mMainLayout.getLayoutParams().height+" "+mMainLayout.getLayoutParams().width); // int height = imageView.getMeasuredHeight(); // int width = imageView.getMeasuredWidth(); mMineViewContainer = findViewById(R.id.mineViewContainer); mShovel = findViewById(R.id.shovel); mFlag = findViewById(R.id.flag); mFlagConfused = findViewById(R.id.flag_confused); mTimeView = findViewById(R.id.timeView); mRestart = findViewById(R.id.restart); mStartAndPaused = findViewById(R.id.startAndPaused); mRemainMines = findViewById(R.id.remainMines); mGameView = findViewById(R.id.gameView); mPausedView = findViewById(R.id.pausedView); mHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case GAME_INIT: gameInit(); break; case GAME_SUCCESS: gameSuccess(); break; case GAME_OVER: gameOver(); break; case GAME_START: gameStart(); break; case GAME_PAUSED: gamePause(); break; case GAME_RESTART: gameRestart(); break; case TIME_CHANGED: mTimeView.setText("TIME:"+ time); break; case PointDown: pointDownCube(msg.arg1,msg.arg2); break; // case RECEIVED_MESSAGE_FROM_SERVER: //接收到网络消息 // isReceivedMessage(msg); // break; } } }; Intent intent = getIntent(); int gameType = intent.getIntExtra(GAME_TYPE,-1); // mServerOrClient = intent.getIntExtra(SERVER_OR_CLIENT,-1); mChoosedGameType = gameType & (TYPE_1 | TYPE_2 | TYPE_3 | TYPE_4); isSingle = (gameType & FLAG_IS_SINGLE) == FLAG_IS_SINGLE; switch (mChoosedGameType) { case TYPE_1: mMineView = new MineViewType1(this); mines = new Mine[8][8]; mMineCount = 10; break; case TYPE_2: mMineView = new MineViewType2(this); mines = new Mine[16][16]; mMineCount = 40; break; case TYPE_3: mMineView = new MineViewType3(this); mines = new Mine[16][30]; mMineCount = 99; break; case TYPE_4: // mMineView = new MineViewType4(this); break; default: break; } LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); mMineViewContainer.addView(mMineView,lp); initMines(mines, mMineCount); mMineView.setMines(mines, mMineCount); mMineView.setHandler(mHandler); mHandler.sendEmptyMessage(GAME_INIT); mShovel.setOnClickListener(this); mFlag.setOnClickListener(this); mFlagConfused.setOnClickListener(this); mRestart.setOnClickListener(this); mStartAndPaused.setOnClickListener(this); } void initMines(Mine[][] mines,int mineCount) { Random random = new Random(System.currentTimeMillis()); int createdMines = 0; int row; int column; rows = mines.length; columns = mines[0].length; for (int i=0; i<rows; i++) { for (int j=0; j<columns; j++) { mines[i][j] = new Mine(); } } while (createdMines < mineCount) { row = random.nextInt(rows); column = random.nextInt(columns); if (!mines[row][column].isMine()) { mines[row][column].setMine(true); mines[row][column].setNum(-1); createdMines++; } } //下面开始生成雷周围的数字 for (int i=0; i<rows; i++) { for (int j=0; j<columns; j++) { if (mines[i][j].isMine()) { if (i-1 >= 0 && j-1 >= 0 && !mines[i-1][j-1].isMine()) mines[i-1][j-1].setNum(mines[i-1][j-1].getNum()+1); if (i-1 >= 0 && !mines[i-1][j].isMine()) mines[i-1][j].setNum(mines[i-1][j].getNum()+1); if (i-1 >= 0 && j+1 < columns && !mines[i-1][j+1].isMine()) mines[i-1][j+1].setNum(mines[i-1][j+1].getNum()+1); if (j-1 >= 0 && !mines[i][j-1].isMine()) mines[i][j-1].setNum(mines[i][j-1].getNum()+1); if (j+1 < columns && !mines[i][j+1].isMine()) mines[i][j+1].setNum(mines[i][j+1].getNum()+1); if (i+1 < rows && j-1 >= 0 && !mines[i+1][j-1].isMine()) mines[i+1][j-1].setNum(mines[i+1][j-1].getNum()+1); if (i+1 < rows && !mines[i+1][j].isMine()) mines[i+1][j].setNum(mines[i+1][j].getNum()+1); if (i+1 < rows && j+1 < columns && !mines[i+1][j+1].isMine()) mines[i+1][j+1].setNum(mines[i+1][j+1].getNum()+1); } } } for (int i=0; i<rows; i++) { String string = new String(); for (int j = 0; j < columns; j++) { if (mines[i][j].getNum() == -1) string += "*" + " "; else string += mines[i][j].getNum() + " "; } Log.i("GameActivity",string); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.flagButton: mMineView.setCurrentType(); break; case R.id.restart: gameRestart(); break; case R.id.showDialog: break; case R.id.flag: //这里对按钮背景或则资源进行设置 case R.id.flag_confused: case R.id.shovel: setBackgroundOrSrc(v.getId()); break; case R.id.startAndPaused: startOrPauseGame(); break; } } void showCustomDialog(int GameType) { CustomDialog dialog = null; switch (GameType) { case GAME_SUCCESS: dialog = new CustomDialog(this,R.style.Custom_Dialog_Style,R.layout.dialog_layout_success,time); break; case GAME_OVER: dialog = new CustomDialog(this,R.style.Custom_Dialog_Style,R.layout.dialog_layout_fail,-1); break; } if (dialog != null) { dialog.setOnDialogButtonClickListener(new OnDialogButtonClickListener() { @Override public void onLeftClick() { } @Override public void onRightClick() { gameRestart(); } }); dialog.show(); } } void pointDownCube(int row,int column) { switch (GAME_STATE) { case GAME_INIT: mHandler.sendEmptyMessage(GAME_START); break; case GAME_PAUSED: case GAME_OVER: case GAME_SUCCESS: return; } switch (mCurrentType) { case DRAG: if (mines[row][column].isFlaged()) //flag状态下也不可点击 return; else openCube(row,column); break; case FLAG: flagCube(row, column); break; case FLAG_CONFUSED: confuseCube(row, column); makeGameSuccessTest(); break; } mMineView.invalidate(); //刷新界面 setRemainMinesOrCheckResult(); //在这里也许应该加一个网络通信的东西 } /** * 瞬间让游戏成功 */ void makeGameSuccessTest() { for (int i=0; i<mines.length; i++) { for (int j=0; j<mines[0].length; j++) { if (mines[i][j].getNum() != -1) { mines[i][j].setOpen(true); } } } // mMineView.invalidate(); // setRemainMinesOrCheckResult(); } /** * 对周围进行递归找出可以打开的方块 * @param row * @param column */ void openCube(int row, int column) { if (mines[row][column].isMine()) { //打开的是雷,游戏直接结束 setGameOver(); return; } if (mines[row][column].isOpen()) //已经打开过了,结束 return; mines[row][column].setOpen(true); //首先设置为打开状态 mines[row][column].setFlaged(false); //去掉标记状态 mines[row][column].setConfused(false); //去掉?标记 if (mines[row][column].getNum() != 0) { //如果打开的不是0,结束 return; } else { //如果打开的是0, 判断边界是否合法,对周围8个方向进行递归 if (row-1 >= 0 && column-1 >= 0) openCube(row-1,column-1); if (row-1 >= 0) openCube(row-1,column); if (row-1 >= 0 && column+1 < columns) openCube(row-1,column+1); if (column-1 >= 0) openCube(row,column-1); if (column+1 < columns) openCube(row,column+1); if (row+1 < rows && column-1 >= 0 ) openCube(row+1,column-1); if (row+1 < rows) openCube(row+1,column); if (row+1 < rows && column+1 < columns) openCube(row+1,column+1); } } /** * 标记雷 * @param row * @param column */ void flagCube(int row, int column) { if (mines[row][column].isOpen()) return; if (mines[row][column].isConfused()) mines[row][column].setConfused(false); if (mines[row][column].isFlaged()) mines[row][column].setFlaged(false); else mines[row][column].setFlaged(true); } void confuseCube(int row, int column) { if (mines[row][column].isOpen()) return; if (mines[row][column].isFlaged()) { mines[row][column].setFlaged(false); } if (mines[row][column].isConfused()) mines[row][column].setConfused(false); else mines[row][column].setConfused(true); } void setBackgroundOrSrc(int id) { if (mFlag.getId() == id) { mFlag.setBackgroundResource(R.drawable.image_background); mFlagConfused.setBackgroundResource(0); mShovel.setBackgroundResource(0); mCurrentType = FLAG; } else if (mFlagConfused.getId() == id) { mFlagConfused.setBackgroundResource(R.drawable.image_background); mFlag.setBackgroundResource(0); mShovel.setBackgroundResource(0); mCurrentType = PointType.FLAG_CONFUSED; } else if (mShovel.getId() == id) { mShovel.setBackgroundResource(R.drawable.image_background); mFlagConfused.setBackgroundResource(0); mFlag.setBackgroundResource(0); mCurrentType = DRAG; } } void setGameOver() { mMineView.setGameOver(); mHandler.sendEmptyMessage(GAME_OVER); Log.i("MineView","GameOver"); } void startOrPauseGame() { if (GAME_STATE == GAME_START) { showView(); gamePause(); } else if (GAME_STATE == GAME_PAUSED) { showView(); gameStart(); } } void setRemainMinesOrCheckResult() { int flagMines = 0; int openedCount = 0; for (int i=0; i<rows; i++) { for (int j=0; j<columns; j++) { if (mines[i][j].isFlaged()) flagMines++; if (!mines[i][j].isMine() && mines[i][j].isOpen()) openedCount++; } } if (openedCount == rows * columns - mMineCount) //说明成功了 mHandler.sendEmptyMessage(GAME_SUCCESS); //通知GameActivity mRemainMines.setText("Mines:"+flagMines+"/"+mMineCount); } @Override public void gameInit() { GAME_STATE = GAME_INIT; timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { if (GAME_STATE == GAME_START) { time++; mHandler.sendEmptyMessage(TIME_CHANGED); } } },1000,1000); mStartAndPaused.setImageResource(R.mipmap.pause); mRemainMines.setText("Mines:"+0+"/"+mMineCount); } @Override public void gameStart() { GAME_STATE = GAME_START; mStartAndPaused.setImageResource(R.mipmap.start); } @Override public void gamePause() { GAME_STATE = GAME_PAUSED; mStartAndPaused.setImageResource(R.mipmap.pause); } @Override public void gameRestart() { if (GAME_STATE == GAME_INIT) //没有开始的时候不进行restart return; GAME_STATE = GAME_RESTART; if (timer != null) timer.cancel(); time = 0; mTimeView.setText("Time:0"); initMines(mines,mMineCount); mMineView.restart(mines,mMineCount); setBackgroundOrSrc(mShovel.getId()); showView(); if (timer != null) timer.cancel(); mHandler.sendEmptyMessage(GAME_INIT); } @Override public void gameSuccess() { GAME_STATE = GAME_SUCCESS; mStartAndPaused.setImageResource(R.mipmap.pause); if (isNewRecord(time, mChoosedGameType)) { //新纪录 Record record = new Record(); record.setGameData(System.currentTimeMillis()+""); record.setGameTime(time); record.setGameType(mChoosedGameType); showNewRecordDialog(record); } else showCustomDialog(GAME_SUCCESS); if (timer != null) timer.cancel(); Log.i("GameActivity","Success"); } @Override public void gameOver() { GAME_STATE = GAME_OVER; mStartAndPaused.setImageResource(R.mipmap.pause); showCustomDialog(GAME_OVER); Log.i("GameActivity","GameOver"); if (timer != null) timer.cancel(); } // private void isReceivedMessage(Message message) { // CommunicateData communicateData = GsonUtil.stringToCommunicateData((String) message.obj); // switch (communicateData.getType()) { // case CommunicateData.USER_OPERATION: //用户点击方块的操作 // break; // case CommunicateData.GAME_STATE: //游戏状态改变 // switch (communicateData.getGame_state()) { // case CommunicateData.GAME_INIT: // mHandler.sendEmptyMessage(GAME_INIT); // break; // } // break; // case CommunicateData.OTHER: //其他的消息,准备接受服务端发来的消息 // Mine[][] tempMines = GsonUtil.stringToMines(communicateData.getMessage()); // for (int i=0 ;i<rows; i++) { // for (int j=0; j<columns; j++) { // mines[i][j] = tempMines[i][j]; // } // } //// LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); //// mMineViewContainer.addView(mMineView,lp); // // mMineView.setMines(mines, mMineCount); // mMineView.setHandler(mHandler); // mHandler.sendEmptyMessage(GAME_INIT); // break; // } // } void showView() { AlphaAnimation appearAnimation = new AlphaAnimation(0, 1); appearAnimation.setDuration(500); AlphaAnimation disappearAnimation = new AlphaAnimation(1, 0); disappearAnimation.setDuration(500); if (GAME_STATE == GAME_START) { mPausedView.setAnimation(appearAnimation); mPausedView.setVisibility(View.VISIBLE); mGameView.setAnimation(disappearAnimation); mGameView.setVisibility(View.GONE); } else if (GAME_STATE == GAME_PAUSED) { mGameView.setAnimation(appearAnimation); mGameView.setVisibility(View.VISIBLE); mPausedView.setAnimation(disappearAnimation); mPausedView.setVisibility(View.GONE); } else if (GAME_STATE == GAME_RESTART) { mGameView.setVisibility(View.VISIBLE); mPausedView.setVisibility(View.GONE); } } // void startBindServerService() { // Intent serverIntent = new Intent(this,ServerConnectService.class); // mServerConnection = new ServiceConnection() { // @Override // public void onServiceConnected(ComponentName name, IBinder service) { // Toast.makeText(GameActivity.this, "ClientService has Started", Toast.LENGTH_SHORT).show(); // ServerConnectService.LocalBinder binder = (ServerConnectService.LocalBinder) service; // mServerConnectService = binder.getService(); // mServerConnectService.setGameActivityHandler(mHandler); // } // // @Override // public void onServiceDisconnected(ComponentName name) { // mServerConnectService = null; // Toast.makeText(GameActivity.this, "the ServiceService has Stopped", Toast.LENGTH_SHORT).show(); // Log.i(TAG,"The ServiceService has Stopped!"); // } // }; // bindService(serverIntent,mServerConnection,BIND_AUTO_CREATE); // } // // void startBindClientService() { // Intent clientIntent = new Intent(this,ClientConnectService.class); // mClientConnection = new ServiceConnection() { // @Override // public void onServiceConnected(ComponentName name, IBinder service) { // Toast.makeText(GameActivity.this, "ServiceService has Started", Toast.LENGTH_SHORT).show(); // ClientConnectService.LocalBinder binder = (ClientConnectService.LocalBinder) service; // mClientConnectService = binder.getService(); // mClientConnectService.setGameActivityHandler(mHandler); // } // // @Override // public void onServiceDisconnected(ComponentName name) { // mClientConnectService = null; // Toast.makeText(GameActivity.this, "the ClientService has Stopped", Toast.LENGTH_SHORT).show(); // Log.i(TAG,"The ClientService has Stopped!"); // } // }; // bindService(clientIntent,mClientConnection,BIND_AUTO_CREATE); // } // // @Override // protected void onDestroy() { // super.onDestroy(); // unbindService(mClientConnection); // unbindService(mServerConnection); // } }
true
bfc51c9528575124251c2d462ba4c1af8c6d6fa4
Java
zuberol/songmate
/src/main/java/pl/jzuber/songmate/persistence_layer/example/RandomEntity.java
UTF-8
138
1.882813
2
[]
no_license
package pl.jzuber.songmate.persistence_layer.example; public interface RandomEntity<E> { public void deleteCustomById(E itemType); }
true
a01771d372534bdfc6e774eceaf5bd9f7a461afe
Java
ripa1993/eftaios
/src/test/java/it/polimi/ingsw/cg_8/controller/playerActions/UsetItemCardValidatorTest.java
UTF-8
2,752
2.453125
2
[]
no_license
package it.polimi.ingsw.cg_8.controller.playerActions; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import it.polimi.ingsw.cg_8.controller.playeraction.EndTurn; import it.polimi.ingsw.cg_8.controller.playeraction.UseItemCardValidator; import it.polimi.ingsw.cg_8.model.Model; import it.polimi.ingsw.cg_8.model.cards.item.AdrenalineCard; import it.polimi.ingsw.cg_8.model.cards.item.AttackCard; import it.polimi.ingsw.cg_8.model.cards.item.ItemCard; import it.polimi.ingsw.cg_8.model.cards.item.SedativesCard; import it.polimi.ingsw.cg_8.model.exceptions.EmptyDeckException; import it.polimi.ingsw.cg_8.model.exceptions.GameAlreadyRunningException; import it.polimi.ingsw.cg_8.model.exceptions.NotAValidMapException; import it.polimi.ingsw.cg_8.model.exceptions.TooManyCardsException; import it.polimi.ingsw.cg_8.model.map.GameMapName; import it.polimi.ingsw.cg_8.model.player.Player; import it.polimi.ingsw.cg_8.model.player.character.alien.Alien; import java.util.List; import org.junit.Before; import org.junit.Test; public class UsetItemCardValidatorTest { Model model; Player currentPlayer; @Before public void init() throws NotAValidMapException, GameAlreadyRunningException, EmptyDeckException, TooManyCardsException { model = new Model(GameMapName.FERMI); model.addPlayer("Ann"); model.addPlayer("Bob"); model.initGame(); currentPlayer = model.getPlayers().get(model.getCurrentPlayer()); if (currentPlayer.getCharacter() instanceof Alien) { EndTurn.endTurn(model); currentPlayer = model.getPlayers().get(model.getCurrentPlayer()); } currentPlayer.getHand().addItemCard(new AttackCard()); currentPlayer.getHand().addItemCard(new AdrenalineCard()); } @Test public void testCardUsage() { assertTrue(UseItemCardValidator.validateItemCardUsage(model, new AdrenalineCard())); } @Test public void testCardUsage2() { assertTrue(UseItemCardValidator.validateItemCardUsage(model, new AttackCard())); } @Test public void testCardUsage3() { assertFalse(UseItemCardValidator.validateItemCardUsage(model, new SedativesCard())); } @Test public void testCardRemoval() { boolean removalCheck = false; UseItemCardValidator.validateItemCardUsage(model, new AdrenalineCard()); List<ItemCard> heldCards = currentPlayer.getHand().getHeldCards(); for (ItemCard c : heldCards) { if (c instanceof AdrenalineCard) { removalCheck = true; } } assertFalse(removalCheck); } }
true
9ef92b1084c85786ac406801bd2ab1ff8fc931bd
Java
151608133/zp_workspace
/zpm_server/zpm-webapp/src/main/java/com/zp/sys/controller/OperationsController.java
UTF-8
1,642
2.125
2
[]
no_license
package com.zp.sys.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import com.zp.core.util.Const; import com.zp.sys.entity.Function; import com.zp.sys.service.FunctionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.zp.set.entity.OperationLog2; import com.zp.sys.entity.User; /** * 日志操作类 * @author ShenHuiYang * @since 2016-09-05 */ @Controller @RequestMapping(value="/opt") public class OperationsController { @Autowired private FunctionService funcService; /** * 左侧菜单栏默认查询 * @param request * @param operationLog * @return */ @RequestMapping(method=RequestMethod.GET) public ModelAndView getRoleList(HttpServletRequest request, OperationLog2 operationLog, HttpSession session){ User user = (User)session.getAttribute(Const.SESSION_USER); Map mm = new HashMap(); String language = session.getAttribute(Const.SESSION_SYS_LANGUAGE) == null ? "zh" : session.getAttribute(Const.SESSION_SYS_LANGUAGE).toString(); mm.put("parentFuncId", 9); mm.put("userId", user.getUserId()); List<Function> list = funcService.getOperationsByUserId(mm); ModelAndView mv = new ModelAndView(); mv.addObject("user", user); mv.addObject("menuList", list); mv.setViewName("system/operations"); return mv; } }
true
787bf334684b03f26398f650da2e0aba4b175ba1
Java
marjunindia/android
/Android-Design-Patterns/12PrototypePattern/app/src/main/java/com/example/arjun_mu/a12prototypepattern/SequenceCache.java
UTF-8
863
3.125
3
[]
no_license
package com.example.arjun_mu.a12prototypepattern; import java.util.Hashtable; /** * Created by arjun_mu on 1/16/2018. */ public class SequenceCache { private static Hashtable<String, Sequence> sequenceHashtable = new Hashtable<String, Sequence>(); public static Sequence getSequence(String sequenceId) { Sequence cachedSequence = sequenceHashtable.get(sequenceId); try { return (Sequence) cachedSequence.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return null; } public static void loadCache() { Prime prime = new Prime(); prime.setId("1"); sequenceHashtable.put(prime.getId(), prime); Fibonacci fib = new Fibonacci(); fib.setId("2"); sequenceHashtable.put(fib.getId(), fib); } }
true
555d3a01a6ce2b82a7c6610f58b13cd7e399de26
Java
balacgvak/zoupons_test_branch
/Zoupons/src/com/us/zoupons/storeowner/customercenter/FavouriteCustomerDetails.java
UTF-8
352
1.828125
2
[]
no_license
package com.us.zoupons.storeowner.customercenter; /** * * Class variables to hold favorite customer details * */ public class FavouriteCustomerDetails { public String mCustomerName="",mCustomerFirstName="",mCustomerLastName="",mCustomerId="",mCustomerProfileImage="",mMessage="",mIsFavouriteStoreRemoved="",mTransactionAmount="0"; }
true
388e4305cb070b295e82ca27d7f8c6176c2e5190
Java
CapGemeni/BeHappy
/app/src/main/java/com/bbva/intranet/behappy/modules/recompensas/PuntosFragment.java
UTF-8
2,033
1.851563
2
[]
no_license
package com.bbva.intranet.behappy.modules.recompensas; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import com.bbva.intranet.behappy.R; import com.bbva.intranet.behappy.databinding.FragmentPuntosBinding; public class PuntosFragment extends Fragment implements View.OnClickListener{ FragmentPuntosBinding binding; public PuntosFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_puntos, container, false); binding= DataBindingUtil.inflate(inflater, R.layout.fragment_puntos, container,false); setListener(); return binding.getRoot(); } private void setListener(){ //binding.btnPscArea.setOnClickListener(this); //binding.btnPscDireccion.setOnClickListener(this); } @Override public void onClick(View view) { /*if (view.getId() == R.id.btn_psc_direccion) { binding.contenedorList.setVisibility(View.GONE); binding.contenedorList2.setVisibility(View.VISIBLE); //binding.btnPscDireccion.setVisibility(View.GONE); //binding.btnPscArea.setVisibility(View.VISIBLE); //binding.textviewPsc.setText("Posiciones por dirección"); }if (view.getId() == R.id.btn_psc_area){ binding.contenedorList.setVisibility(View.VISIBLE); binding.contenedorList2.setVisibility(View.GONE); //binding.btnPscDireccion.setVisibility(View.VISIBLE); //binding.btnPscArea.setVisibility(View.GONE); //binding.textviewPsc.setText("Posiciones por aréa"); }*/ } }
true
0461014ab92e7399f0adbeb8da717691204a6d23
Java
kakorenko/java-
/cofee/src/com/company/PhilipsHD8829.java
UTF-8
347
2.578125
3
[]
no_license
package com.company; public class PhilipsHD8829 extends CofeeMashine { //1800г воды // 250г кофе PhilipsHD8829(){ coffeeCapacity=250; waterCapacity=1800; coffee=coffeeCapacity; water=waterCapacity; } @Override public void about() { System.out.println("philips"); } }
true
786310515a5cfcf8636218ff1a1ee119687b4452
Java
rgocal/Appsii
/Appsi/src/main/java/com/appsimobile/appsii/iab/IabPurchaseHelper.java
UTF-8
10,715
2.015625
2
[ "Apache-2.0" ]
permissive
/* Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.appsimobile.appsii.iab; import android.app.Activity; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.IntentSender.SendIntentException; import android.os.Bundle; import android.os.RemoteException; import android.util.Log; import org.json.JSONException; /** * A specific iab-helper implementation. Gives access to the purchase function * if the iab-library */ public class IabPurchaseHelper extends BaseIabHelper { /** * Creates an instance. After creation, it will not yet be ready to use. You must perform * setup by calling {@link #startSetup} and wait for setup to complete. This constructor does * not * block and is safe to call from a UI thread. * * @param ctx Your application or Activity context. Needed to bind to the in-app billing * service. */ public IabPurchaseHelper(Context ctx) { super(ctx); } /** * Handles an activity result that's part of the purchase flow in in-app billing. If you * are calling {@link #launchPurchaseFlow}, then you must call this method from your * Activity's {@link android.app.Activity@onActivityResult} method. This method * MUST be called from the UI thread of the Activity. * * @param resultCode The resultCode as you received it. * @param data The data (Intent) as you received it. * * @return Returns true if the result was related to a purchase flow and was handled; * false if the result was not related to a purchase, in which case you should * handle it normally. */ public static int handleActivityResult( int resultCode, Intent data, OnIabPurchaseFinishedListener purchaseListener, String itemType, String devPayload) { if (data == null) { logError("Null data in IAB activity result."); return IABHELPER_BAD_RESPONSE; } int responseCode = getResponseCodeFromIntent(data); String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA); String dataSignature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE); if (resultCode == Activity.RESULT_OK && responseCode == BILLING_RESPONSE_RESULT_OK) { logDebug("Successful resultcode from purchase activity."); logDebug("Purchase data: " + purchaseData); logDebug("Data signature: " + dataSignature); logDebug("Extras: " + data.getExtras()); logDebug("Expected item type: " + itemType); if (purchaseData == null || dataSignature == null) { logError("BUG: either purchaseData or dataSignature is null."); logDebug("Extras: " + data.getExtras().toString()); return IABHELPER_UNKNOWN_ERROR; } Purchase purchase; try { purchase = new Purchase(itemType, purchaseData, dataSignature); String sku = purchase.getSku(); // Verify signature if (!Security.verifyPurchase(RSA_CODE, purchaseData, dataSignature)) { logError("Purchase signature verification FAILED for sku " + sku); return IABHELPER_VERIFICATION_FAILED; } logDebug("Purchase signature successfully verified."); if (!Security.verifyDeveloperPayload(purchase, devPayload)) { logError("Purchase payload verification FAILED for sku " + sku); return IABHELPER_DEVELOPER_PAYLOAD_FAILED; } logDebug("Developer payload successfully verified."); } catch (JSONException e) { logError("Failed to parse purchase data."); e.printStackTrace(); return IABHELPER_BAD_RESPONSE; } if (purchaseListener != null) { purchaseListener.onIabPurchaseSuccess(purchase); } return BILLING_RESPONSE_RESULT_OK; } else if (resultCode == Activity.RESULT_OK) { // result code was OK, but in-app billing response was not OK. logDebug("Result code was OK but in-app billing response was not OK: " + getResponseDesc(responseCode)); return responseCode; } else if (resultCode == Activity.RESULT_CANCELED) { logDebug("Purchase canceled - Response: " + getResponseDesc(responseCode)); return IABHELPER_USER_CANCELLED; } else { logError("Purchase failed. Result code: " + Integer.toString(resultCode) + ". Response: " + getResponseDesc(responseCode)); return IABHELPER_UNKNOWN_PURCHASE_RESPONSE; } } /** * Returns whether subscriptions are supported. */ public boolean subscriptionsSupported() { return mSubscriptionsSupported; } public int launchInAppItemPurchaseFlow(Activity act, String sku, int requestCode, String developerPayload) { return launchPurchaseFlow(act, sku, ITEM_TYPE_INAPP, requestCode, developerPayload); } public int launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode, String extraData) { return launchPurchaseFlow(act, sku, ITEM_TYPE_SUBS, requestCode, extraData); } /** * Initiate the UI flow for an in-app purchase. Call this method to initiate an in-app purchase, * which will involve bringing up the Google Play screen. The calling activity will be paused * while * the user interacts with Google Play, and the result will be delivered via the activity's * {@link android.app.Activity#onActivityResult} method, at which point you must call * this object's {@link #handleActivityResult} method to continue the purchase flow. This method * MUST be called from the UI thread of the Activity. * * @param act The calling activity. * @param sku The sku of the item to purchase. * @param itemType indicates if it's a product or a subscription (ITEM_TYPE_INAPP or * ITEM_TYPE_SUBS) * @param requestCode A request code (to differentiate from other responses -- * as in {@link android.app.Activity#startActivityForResult}). * @param developerPayload Extra data (developer payload), which will be returned with the * purchase data * when the purchase completes. This extra data will be permanently bound to that purchase * and will always be returned when the purchase is queried. */ public int launchPurchaseFlow(Activity act, String sku, String itemType, int requestCode, String developerPayload) { checkSetupDone("launchPurchaseFlow"); if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) { return IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE; } try { logDebug("Constructing buy intent for " + sku + ", item type: " + itemType); Bundle buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, developerPayload); int response = getResponseCodeFromBundle(buyIntentBundle); if (response != BILLING_RESPONSE_RESULT_OK) { logError("Unable to buy item, Error response: " + getResponseDesc(response)); return response; } PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT); logDebug("Launching buy intent for " + sku + ". Request code: " + requestCode); act.startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, new Intent(), 0, 0, 0); return BILLING_RESPONSE_RESULT_OK; } catch (SendIntentException e) { logError("SendIntentException while launching purchase flow for sku " + sku); e.printStackTrace(); return IABHELPER_SEND_INTENT_FAILED; } catch (RemoteException e) { logError("RemoteException while launching purchase flow for sku " + sku); e.printStackTrace(); return IABHELPER_REMOTE_EXCEPTION; } } /** * Consumes a given in-app product. Consuming can only be done on an item * that's owned, and as a result of consumption, the user will no longer own it. * This method may block or take long to return. * * @throws IabException if there is a problem during consumption. */ int consume(String sku, String token) { checkSetupDone("consume"); try { if (token == null || token.equals("")) { logError("Can't consume " + sku + ". No token."); return IABHELPER_MISSING_TOKEN; } logDebug("Consuming sku: " + sku + ", token: " + token); int response = mService.consumePurchase(3, mContext.getPackageName(), token); if (response == BILLING_RESPONSE_RESULT_OK) { logDebug("Successfully consumed sku: " + sku); } else { logDebug("Error consuming consuming sku " + sku + ". " + getResponseDesc(response)); } return response; } catch (RemoteException e) { Log.wtf("Appsii", "Remote exception while consuming. Sku: " + sku, e); return IABHELPER_REMOTE_EXCEPTION; } } /** * Callback that notifies when a purchase is finished. */ public interface OnIabPurchaseFinishedListener { /** * Called to notify that an in-app purchase finished. If the purchase was successful, * then the sku parameter specifies which item was purchased. If the purchase failed, * the sku and extraData parameters may or may not be null, depending on how far the * purchase * process went. * * @param info The purchase information (null if purchase failed) */ void onIabPurchaseSuccess(Purchase info); } }
true
ac13b3171b6eb73b774820fd9ce20e20987f3467
Java
kangliuxu/design-pattern
/src/adapter/Adapter.java
UTF-8
261
2.78125
3
[]
no_license
package adapter; public class Adapter implements Target{ private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } @Override public void process() { adaptee.bar(); adaptee.foo(); } }
true
55fb3188010471225406e06337ef6d40304702eb
Java
wanghouting/agileway
/agileway-dmmq/src/main/java/com/jn/agileway/dmmq/core/SimpleProducer.java
UTF-8
1,733
2.640625
3
[ "Apache-2.0" ]
permissive
package com.jn.agileway.dmmq.core; import com.jn.langx.annotation.NonNull; import com.jn.langx.annotation.Nullable; import com.jn.langx.util.Preconditions; import com.jn.langx.util.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Just send message to the 'DEFAULT' topic if the topicName is not specified * * @param <M> */ public class SimpleProducer<M> implements Producer<M> { private static final Logger logger = LoggerFactory.getLogger(SimpleProducer.class); private TopicAllocator<M> topicAllocator; private MessageTopicDispatcher dispatcher; public TopicAllocator<M> getTopicAllocator() { return topicAllocator; } public void setTopicAllocator(TopicAllocator<M> topicAllocator) { this.topicAllocator = topicAllocator; } @Override public void publish(M message) { publish(null, message); } @Override public void publish(@Nullable String topicName, @NonNull M message) { Preconditions.checkNotNull(message); topicName = getTopic(topicName, message); if (Strings.isEmpty(topicName)) { logger.warn("not found an invalid topic for the message: {}", message); return; } dispatcher.publish(topicName, message); } private String getTopic(String topicName, M message) { if (Strings.isEmpty(topicName)) { return topicAllocator.apply(message); } return topicName; } @Override public void setMessageTopicDispatcher(MessageTopicDispatcher dispatcher) { this.dispatcher = dispatcher; } @Override public MessageTopicDispatcher getMessageTopicDispatcher() { return dispatcher; } }
true
3185db2391ec4fbcd3a8e7d73eb721764b4377a5
Java
checkmarx-ltd/cx-flow
/src/main/java/com/checkmarx/flow/dto/bitbucket/Destination.java
UTF-8
1,165
1.960938
2
[ "Apache-2.0" ]
permissive
package com.checkmarx.flow.dto.bitbucket; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "commit", "branch", "repository" }) public class Destination { @JsonProperty("commit") private Commit commit; @JsonProperty("branch") private Branch branch; @JsonProperty("repository") private Repository repository; @JsonProperty("commit") public Commit getCommit() { return commit; } @JsonProperty("commit") public void setCommit(Commit commit) { this.commit = commit; } @JsonProperty("branch") public Branch getBranch() { return branch; } @JsonProperty("branch") public void setBranch(Branch branch) { this.branch = branch; } @JsonProperty("repository") public Repository getRepository() { return repository; } @JsonProperty("repository") public void setRepository(Repository repository) { this.repository = repository; } }
true
f1cbe2b439c38b83ddbc63d711cb38e0b02d56e4
Java
fyamvbf/example-chat
/backend/src/test/java/com/example/domain/model/account/TemporaryUserTokenTest.java
UTF-8
686
2.390625
2
[ "Apache-2.0" ]
permissive
package com.example.domain.model.account; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; public class TemporaryUserTokenTest { @Test void valid() { new TemporaryUserToken("testtoken"); } @Test void invalidWithNull() { assertThrows(NullPointerException.class, () -> new TemporaryUserToken(null)); } @ParameterizedTest @ValueSource(strings = { "", " " }) void invalidWith(String value) { assertThrows(IllegalArgumentException.class, () -> new TemporaryUserToken(value)); } }
true