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
b1ad59268bd9785d02cf0ae2b92cbd4147a83979
Java
carlosap92/LoginFace
/samples/Scrumptious/src/com/facebook/scrumptious/TabActivity.java
UTF-8
1,909
2.109375
2
[]
no_license
package com.facebook.scrumptious; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTabHost; import android.view.Menu; import android.view.MenuItem; import android.widget.TabHost; public class TabActivity extends FragmentActivity { private FragmentTabHost mTabHost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tab); mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost); mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"), Tab1.class, null); mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"), Tab1.class, null); mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"), Tab1.class, null); mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"), Tab1.class, null); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_tab, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
true
01a33cb60ffb5fa4a1a0960d2ed68d1fcc440550
Java
ziemm/basic-code
/basic-code/src/cn/xie/base02/demoStream/DemoStreamList.java
UTF-8
1,165
3.3125
3
[]
no_license
package cn.xie.base02.demoStream; import java.util.ArrayList; import java.util.stream.Stream; /** * @author: xie * @create: 2019-10-12 20:37 **/ public class DemoStreamList { public static void main(String[] args) { //第一支队伍 ArrayList<String> one = new ArrayList<>(); one.add("迪丽热巴"); one.add("宋远桥"); one.add("苏星河"); one.add("石破天"); one.add("石中玉"); one.add("老子"); one.add("庄子"); one.add("洪七公"); //第二支队伍 ArrayList<String> two = new ArrayList<>(); two.add("古力娜扎"); two.add("张无忌"); two.add("赵丽颖"); two.add("张三丰"); two.add("尼古拉斯赵四"); two.add("张天爱"); two.add("张二狗"); //狠!! Stream<String> streamOne = one.stream().filter(name->name.length()==3).limit(3); Stream<String> streamTwo = two.stream().filter(name->name.startsWith("张")).skip(2); Stream.concat(streamOne,streamTwo).map(name->new Person(name)).forEach(name->System.out.println(name)); } }
true
8393f6a1b6e1fa66d4c539ae8d587e5f552b7d47
Java
RobertoXocop-seguros/rosetabackend-platzi-spring
/src/main/java/com/rxocop/rosetabackend/web/controller/CompraController.java
UTF-8
1,198
2.046875
2
[]
no_license
package com.rxocop.rosetabackend.web.controller; import com.rxocop.rosetabackend.persistence.entity.Compra; import com.rxocop.rosetabackend.persistence.inter.CompraRepositoryInt; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/compras") public class CompraController { @Autowired private CompraRepositoryInt compraRepositoryInt; @GetMapping("/all") public ResponseEntity<List<Compra>> getAll(){ return new ResponseEntity<>(compraRepositoryInt.listar(), HttpStatus.OK); } @GetMapping("/cliente/{id}") public ResponseEntity getAllByIdCliente(@PathVariable("id") String id){ return compraRepositoryInt.getByClient(id).map(compras -> new ResponseEntity<>(compras,HttpStatus.OK)).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); } @PostMapping("/save") public ResponseEntity<Compra> agregar(@RequestBody Compra compra){ return new ResponseEntity<>(compraRepositoryInt.registrar(compra),HttpStatus.CREATED); } }
true
785c02f9023d71162a81044505eb31f8fd9e6640
Java
masterweb87/BoxCongress
/app/src/main/java/masterwb/design/arkcongress/adapters/EventTypeAdapter.java
UTF-8
693
2.21875
2
[]
no_license
package masterwb.design.arkcongress.adapters; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; /** * Created by Administrator on 12-09-2016. */ public class EventTypeAdapter extends ArrayAdapter<CharSequence> { private Context context; private boolean firstShow = true; public EventTypeAdapter(Context context, int resource, CharSequence[] objects) { super(context, resource, objects); this.context = context; } @Override public int getCount() { int count = super.getCount(); return count > 0 ? count - 1 : count; } }
true
5f2fca2c320a0e582c317ab3e52f9a164cf32e59
Java
BrenoBrandao77/state
/state/estados/Cinza.java
UTF-8
392
2.25
2
[]
no_license
package estados; import java.util.List; import entidades.No; import interfaci.Cor; public class Cinza extends Cor { @Override public void busca(No no, List<No> lista) { } @Override public void assumiu(No no, List<No> lista) { for(No adj : no.getAdjacentes()) { adj.buscaProfundidade(lista); } no.setCor(new Preto(), lista); } }
true
6963d7d6b781466363edf5e3b39d9cb44a010b39
Java
VincentHuis/bakbijbel
/BakBijbel/app/src/main/java/com/bakbijbel/bakbijbel/LoginActivity.java
UTF-8
3,108
2.25
2
[]
no_license
package com.bakbijbel.bakbijbel; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import org.json.JSONException; import org.json.JSONObject; public class LoginActivity extends AppCompatActivity implements AsyncResponse { public static TextView textView; public static JSONObject resultJson; EditText loginIF; EditText passwordIF; Button loginBtn; Button signUp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_activity); textView = findViewById(R.id.textView2); loginBtn = findViewById(R.id.loginBtn); signUp = findViewById(R.id.SignUp); textView.setText(""); loginIF = findViewById(R.id.loginInputField); passwordIF = findViewById(R.id.passwordInputField); loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Login(); } }); signUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SignUp(); } }); } void SignUp() { Toast.makeText(LoginActivity.this, "Een account aanmaken kan momenteel alleen via de website: Bakbijbel.nl", Toast.LENGTH_LONG).show(); } //Async methode wordt aangeroepen void Login() { AsyncTaskRunner runner = new AsyncTaskRunner(getApplicationContext()); String userName = loginIF.getText().toString(); String password = passwordIF.getText().toString(); runner.delegate = this; runner.execute(userName, password); } @Override public void processFinish(String result, Context context) throws JSONException { JSONObject jsonObject = new JSONObject(result); JSONObject jsonObject1 = new JSONObject(jsonObject.get("user").toString()); if(result.contains("error")) textView.setText("Foutieve combinatie, probeer het opnieuw!"); if(jsonObject.isNull("error") == true) { User user = new User(jsonObject.get("access_token").toString(), jsonObject1.get("name").toString()); //MainActivity.SetUser(user); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); editor.putString("Name", user.name); editor.putString("AccessToken", user.accesToken); editor.apply(); Intent newActivity = new Intent(LoginActivity.this, MainActivity.class); startActivity(newActivity); finish(); } } }
true
39e55803b2573dde201ded7082cb8da478291472
Java
fernandesdiego/cursomc
/src/main/java/com/diegof/cursomc/repositories/EnderecoRepository.java
UTF-8
292
1.585938
2
[]
no_license
package com.diegof.cursomc.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.diegof.cursomc.domain.Endereco; @Repository public interface EnderecoRepository extends JpaRepository<Endereco, Integer>{ }
true
dfd54d6871c646ef824fe0e6a66e83486f746b3f
Java
jinapark08-Ruler/Ruler-H
/javaapp0426/src/hiding/StudentTest.java
UTF-8
490
3.09375
3
[]
no_license
package hiding; public class StudentTest { public static void main(String[] args) { // private 변수를 확인해보기 위한 클래스 Student studentLee = new Student(); //private 변수로 선언한 studentName이기 때문에 오류 발생 //studentLee.studentName = "이상원"; //set을 이용한 멤버 변수에 이름 값 대입 studentLee.setStudentName("이상원"); //get을 이용해서 확인 System.out.println(studentLee.getStudentName()); } }
true
bdeefdadbc9e890bd2d13c39ce060aaaae581836
Java
1739745826/XueCheng
/xc-service-ucenter/src/main/java/com/xuecheng/ucenter/service/UserService.java
UTF-8
1,922
2.09375
2
[]
no_license
package com.xuecheng.ucenter.service; import com.xuecheng.framework.domain.ucenter.XcCompanyUser; import com.xuecheng.framework.domain.ucenter.XcMenu; import com.xuecheng.framework.domain.ucenter.XcUser; import com.xuecheng.framework.domain.ucenter.ext.XcUserExt; import com.xuecheng.ucenter.dao.XcComparyUserRepostory; import com.xuecheng.ucenter.dao.XcMenuMapper; import com.xuecheng.ucenter.dao.XcUserRepository; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 标题: * 作者:何处是归程 * 时间:2020/3/14 - 9:11 */ @Service public class UserService { @Autowired XcUserRepository xcUserRepository; @Autowired XcComparyUserRepostory xcComparyUserRepostory; @Autowired XcMenuMapper xcMenuMapper; /** * @功能: 根据账号查询xcUser信息 * @作者: 高志红 */ public XcUser findXcUserByIsername(String username) { return xcUserRepository.findByUsername(username); } /** * @功能: 根据账号查询用户信息 * @作者: 高志红 */ public XcUserExt getUserExt(String username) { // 根据账号查询xcUser信息 XcUser xcUser = this.findXcUserByIsername(username); if (xcUser == null) { return null; } // 用户ID String userId = xcUser.getId(); // 查询用户的所有权限 List<XcMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(userId); // 根据用户ID查询用户所属公司ID XcCompanyUser xcCompanyUser = xcComparyUserRepostory.findByUserId(userId); // 取到用户公司ID String companyId = null; if (xcCompanyUser != null) { companyId = xcCompanyUser.getCompanyId(); } XcUserExt xcUserExt = new XcUserExt(); BeanUtils.copyProperties(xcUser, xcUserExt); xcUserExt.setCompanyId(companyId); // 设置权限 xcUserExt.setPermissions(xcMenus); return xcUserExt; } }
true
b18502ac9e2d57513a3eea0d0059dc074caccde5
Java
danielcagostinho/LearningJava
/src/JavaExercises1_2.java
UTF-8
5,862
3.5
4
[]
no_license
public class JavaExercises1_2 { public static void main(String[] args){ // Arguments: theta, evenDivide(1), evenDivide(2), triSide(1), triSide(2), triSide(3), randInt(1), randInt(2) double theta = Double.parseDouble(args[0]); trigIdentity(theta); addConcatOutput(); charOutput(); maxValOutput(); piOutput(); System.out.println(isEvenDivide(Integer.parseInt(args[1]),Integer.parseInt(args[2]))); System.out.println(isTriangle(Integer.parseInt(args[3]),Integer.parseInt(args[4]),Integer.parseInt(args[5]))); System.out.println(randomInt(Integer.parseInt(args[6]),Integer.parseInt(args[7]))); sumDice(); System.out.println(sineOutput(Double.parseDouble(args[8]))); System.out.println(displacement(Double.parseDouble(args[9]),Double.parseDouble(args[10]), Double.parseDouble(args[11]))); System.out.println(isBtwnDates(Integer.parseInt(args[12]),Integer.parseInt(args[13]))); } public static void trigIdentity(double theta){ // Exercise 1.2.2 - Determines if a theta passed in as a command line argument follows the trig identity 1 = sin^2(theta) + cos^2(theta) System.out.println(1 == (int)(Math.sin(theta)*Math.sin(theta) + Math.cos(theta)*Math.cos(theta))); } public static void addConcatOutput(){ // Exercise 1.2.7 - Experiments with outputting different strings System.out.println(2 + "bc"); System.out.println(2 + 3 + "bc"); System.out.println((2+3) + "bc"); System.out.println("bc" + (2+3)); System.out.println("bc" + 2 + 3); System.out.println("The output above results from the difference between concatenating a int literal vs adding in the string. \nWhen the numbers are in the parentheses, the compiler interprets it as addition which is then concatenated.\nIn the second case, the first two integers are not separated by a string in between so the compiler adds the \ntwo numbers"); } public static void charOutput(){ // Exercise 1.2.9 - Experiments with outputting different strings System.out.println('b'); System.out.println((char)('b' + 'c' - 'c')); System.out.println((char) ('a' + 4)); System.out.println("The output above where b + c = 197 results from the addition of two chars. The resulting value from b + c is \n197 which is the combined value of the codes for b and c. The output for (char) ('a'+4) is the int representing \na, added to 4, and converted back into the char e."); } public static void maxValOutput(){ // Exercise 1.2.10 - Experiments with outputting different numbers close to the max value int a = Integer.MAX_VALUE; System.out.println(a); System.out.println(a+1); System.out.println(2-a); System.out.println(-2-a); System.out.println(2*a); System.out.println(4*a); System.out.println("The discrepancies of the expected values are due to the limitations of the precision of the computer. a is \nthe max value that can be stored, so any case that would result in a larger number would be incorrectly \nrepresented. For example for 2 * a, the result is negative two because the number is stored in two's \ncomplement, when multiplied by two, it overflows to the binary representation of -2."); } public static void piOutput(){ // Exercise 1.2.11 - Experiments with outputting different numbers close to pi double a = 3.141519; System.out.println(a); System.out.println(a+1); System.out.println(8/(int) a); System.out.println(8/a); System.out.println((int) (8/a)); System.out.println("The first output is what is expected. \nThe second output has small error due to adding floating point numbers. 8 / 3 is 2 as expected. \nWhen 8 is divided by a, it is an operation of an int divided by a double. The compiler casts the \nnumerator as a double to compensate and the resulting number is the quotient of 8/3.141519. \nThe final output is just the integer-type cast of the double from the previous output."); } public static boolean isEvenDivide(int num1, int num2){ // Exercise 1.2.14 - Checks to see if two positive integers evenly divide each other. return (num1 % num2 == 0); } public static boolean isTriangle(int num1, int num2, int num3){ // Exercise 1.2.15 - Checks to see if the three numbers could be lengths to the sides of a triangle. return ((num1 >= num2 + num3) || (num2 >= num1 + num3) || (num3 >= num1 + num2)); } public static int randomInt(int a, int b){ // Exercise 1.2.19 - Prints a random integer between a and b double randNum = Math.random(); // Random number between 0 and 1 randNum = (int)(randNum * ((b - a) + 1)) + a; // Multiplies it by the end of interval and rounds up. return (int) randNum; } public static void sumDice(){ // Exercuse 1.2.20 - Prints the sum of two random numbers between 1 and 6 int randNum1 = randomInt(1,6); int randNum2 = randomInt(1,6); System.out.println(randNum1 + randNum2); } public static double sineOutput(double t){ // Exercise 1.2.21 - Takes in a double, t, from the command line arguments and outputs sin(2t) + sin(3t) return Math.sin(2*t) + Math.sin(3*t); } public static double displacement(double x, double v, double t){ // Exercise 1.2.22 - Outputs the displacement of an object thrown straight up double g = 9.78033; return x + v*t + g*(t*t)/2; } public static boolean isBtwnDates(int m, int d){ // Exercise 1.2.23 - Checks if a date is between 3/20 and 6/20 return (m == 3 && d >= 20) || (m > 3 && m < 6) || (m == 6 && d <=20); } }
true
9b4dd4de238fe5f725a96e62941df8ea3d679ff3
Java
gigayou/reservation-app
/pojo/src/main/java/com/ices/pojo/code/Address.java
UTF-8
741
1.835938
2
[]
no_license
package com.ices.pojo.code; import com.ices.reservation.common.sql.Column; import com.ices.reservation.common.sql.Table; import com.ices.reservation.common.utils.Page; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.List; @Getter @Setter @Table(name = "addr_code") public class Address extends Page { @Column(column = "id", isId = true) public Long id; @Column(column = "address_id") public String addressId; @Column(column = "pre_id") public String preId; @Column(column = "address_name", isUseLike = true) public String addressName; @Column(column = "level") public String level; public List children = new ArrayList<>(); }
true
e8bcf5ee8c17bb96f38370b79c0d152385ef509c
Java
md-5/SpecialSource
/src/main/java/net/md_5/specialsource/AccessMap.java
UTF-8
7,671
2.234375
2
[ "BSD-3-Clause" ]
permissive
/** * Copyright (c) 2012, md_5. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * The name of the author may not be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package net.md_5.specialsource; import net.md_5.specialsource.util.FileLocator; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import lombok.Getter; /** * Access mapper - for modifying access flags on symbols * * Supports loading _at.cfg files in the following format: * <ul> * <li>comments beginning with '#' extending to end of line</li> * <li>symbol pattern, space, then access changes</li> * </ul> * * Symbol pattern format: * <pre> * foo class * foo/bar field * foo/bar ()desc method * foo/* fields in class * foo/* ()desc methods in class * * all classes * *&#47;* all fields * *&#47;*() all methods * ** all classes, fields, and methods * </pre> * Internal ('/') and source ('.') conventions are accepted, * and the space preceding the method descriptor is optional. * * Access change format: visibility (required) + access flags * @see AccessChange */ public class AccessMap { @Getter private Map<String, AccessChange> map = new HashMap<String, AccessChange>(); @Getter private Set<String> appliedMaps = new HashSet<String>(); public AccessMap() { } public void loadAccessTransformer(BufferedReader reader) throws IOException { String line; while ((line = reader.readLine()) != null) { // strip comments and trailing whitespace int n = line.indexOf('#'); if (n != -1) { line = line.substring(0, n); } line = line.trim(); if (line.isEmpty()) { continue; } addAccessChange(line); } } public void loadAccessTransformer(File file) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(file))) { loadAccessTransformer(reader); } } /** * Load an access transformer into this AccessMap. * * @param filename Location of AT data, one of: - local filename - remote * HTTP URL - "pattern:" followed by one transformer line * @throws IOException */ public void loadAccessTransformer(String filename) throws IOException { if (filename.startsWith("pattern:")) { addAccessChange(filename.substring("pattern:".length())); } else { loadAccessTransformer(FileLocator.getFile(filename)); } } /** * Convert a symbol name pattern from AT config to internal format */ public static String convertSymbolPattern(String s) { // source name to internal name s = s.replace('.', '/'); // method descriptor separated from name by a space if (s.indexOf('(') != -1) { s = s.replaceFirst("(?=[^ ])[(]", " ("); } // now it matches the symbol name format used in the rest of SpecialSource // (but also possibly with wildcards) return s; } public void addAccessChange(String line) { // _at.cfg format: // protected/public/private[+/-modifiers] symbol int n = line.indexOf(' '); if (n == -1) { throw new IllegalArgumentException("loadAccessTransformer invalid line: " + line); } String accessString = line.substring(0, n); String symbolString = line.substring(n + 1); addAccessChange(symbolString, accessString); } public void addAccessChange(String symbolString, String accessString) { addAccessChange(convertSymbolPattern(symbolString), new AccessChange(accessString)); } public void addAccessChange(String key, AccessChange accessChange) { if (map.containsKey(key)) { System.out.println("INFO: merging AccessMap " + key + " from " + map.get(key) + " with " + accessChange); map.get(key).merge(accessChange); } else { map.put(key, accessChange); } } public int applyClassAccess(String className, int access) { int old = access; access = apply("**", access); access = apply("*", access); access = apply(className, access); //System.out.println("AT: class: "+className+" "+old+" -> "+access); // TODO: debug logging return access; } public int applyFieldAccess(String className, String fieldName, int access) { int old = access; access = apply("**", access); access = apply("*/*", access); access = apply(className + "/*", access); access = apply(className + "/" + fieldName, access); //System.out.println("AT: field: "+className+"/"+fieldName+" "+old+" -> "+access); return access; } public int applyMethodAccess(String className, String methodName, String methodDesc, int access) { int old = access; access = apply("**", access); access = apply("*/* ()", access); access = apply(className + "/* ()", access); access = apply(className + "/" + methodName + " " + methodDesc, access); // if (access!= old) System.out.println("AT: method: "+className+"/"+methodName+" "+methodDesc+" "+old+" -> "+access); return access; } private int apply(String key, int existing) { AccessChange change = map.get(key); if (change == null) { return existing; } else { int newAccess = change.apply(existing); if (newAccess != existing) { appliedMaps.add(key); } accessApplied(key, existing, newAccess); return newAccess; } } /** * Called when an access mapping is applied. * * @param key the key which caused the mapping to be matched and applied * @param oldAccess the access which was replaced * @param newAccess the new access which was applied by the mapping */ protected void accessApplied(String key, int oldAccess, int newAccess) { // Override } }
true
e91987d4138cf4fe4e01ba3e8cd6d67328d3b69b
Java
yuhang123wo/sp
/src/main/java/com/yh/st/base/config/aop/LoggerControllerAdvice.java
UTF-8
2,261
2.421875
2
[]
no_license
package com.yh.st.base.config.aop; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.log4j.Logger; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Service; /** * * @author yh * @Date 2017年10月17日 * @desc controller日志 */ @Aspect @Service public class LoggerControllerAdvice { private Logger logger = Logger.getLogger(this.getClass()); @Before("within(com.yh.st.web.controller..*)") public void addBeforeLogger(JoinPoint joinPoint) { logger.info("执行 " + joinPoint.getSignature().getName() + " 开始"); logger.info("方法:" + joinPoint.getSignature().toString()); logger.info(parseParames(joinPoint.getArgs())); } @Pointcut("execution(* com.yh.st.web.controller..*.*(..))") private void pointCutMethod() { } @Around("pointCutMethod()") public Object doAround(ProceedingJoinPoint pjp) throws Throwable { long begin = System.currentTimeMillis(); Object o = pjp.proceed(); long end = System.currentTimeMillis(); logger.info("执行 " + pjp.getSignature().getName() + "结束,耗时:" + (end - begin)); return o; } @AfterReturning(returning = "rvt", pointcut = "within(com.yh.st.web.controller..*)") public void addAfterReturningLogger(JoinPoint joinPoint, Object rvt) { logger.info("执行 " + joinPoint.getSignature().getName() + "返回结果:" + rvt); } @AfterThrowing(pointcut = "within(com.yh.st.web.controller..*)", throwing = "ex") public void addAfterThrowingLogger(JoinPoint joinPoint, Exception ex) { logger.error("执行 " + joinPoint.getSignature().getName() + "异常", ex); } private String parseParames(Object[] parames) { if (null == parames || parames.length <= 0) { return "传入参数[{}]"; } StringBuffer param = new StringBuffer("传入参数[{}] "); for (Object obj : parames) { param.append(ToStringBuilder.reflectionToString(obj)).append(" "); } return param.toString(); } }
true
7de5bf3ea2361130eb8fcda19b71008866d3cff9
Java
2016IMIEL3B/2016
/Groupe3/Insurance/dao/src/main/java/repository/DriverRepository.java
UTF-8
221
1.789063
2
[]
no_license
package repository; import model.Driver; import org.springframework.data.repository.CrudRepository; /** * Created by Enzo on 18/04/2016. */ public interface DriverRepository extends CrudRepository<Driver,Integer> { }
true
75b9fef6e138065d7f4d3762a88bfb89cdc86b45
Java
DiegoSant0s/DWR2
/DWR2SeguroAutomotivo/src/main/java/br/com/dwr2/seguroAutomotivo/repository/TelefoneRepository.java
UTF-8
320
1.648438
2
[]
no_license
package br.com.dwr2.seguroAutomotivo.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import br.com.dwr2.seguroAutomotivo.entidades.Telefone; @Repository public interface TelefoneRepository extends JpaRepository<Telefone, Long> { }
true
6ac6095356ae133d7cf780a39514b1a2e051034f
Java
chiakilalala/JAVAProject
/src/main/java/com/train/Ticket.java
UTF-8
365
2.78125
3
[]
no_license
package com.train; public class Ticket { int tickets; int round; public Ticket(int round, int tickets) { this.tickets = tickets; this.round = round; } public void print(){ System.out.println("Total tickets:"+tickets+"\t"+"Round-trip:"+round+"\t"+"Total"+"\t"+(int)((tickets - round)*1000+round*2000*0.9)); } }
true
24bccb925971563d3e874193f05ff9d08429a8f7
Java
Cobbe/notaql
/src/main/java/notaql/parser/antlr/NotaQL2ColumnInVisitor.java
UTF-8
12,956
2.21875
2
[ "Apache-2.0" ]
permissive
// Generated from notaql\parser\antlr\NotaQL2ColumnIn.g4 by ANTLR 4.2.1 package notaql.parser.antlr; import org.antlr.v4.runtime.misc.NotNull; import org.antlr.v4.runtime.tree.ParseTreeVisitor; /** * This interface defines a complete generic visitor for a parse tree produced * by {@link NotaQL2ColumnInParser}. * * @param <T> The return type of the visit operation. Use {@link Void} for * operations with no return type. */ public interface NotaQL2ColumnInVisitor<T> extends ParseTreeVisitor<T> { /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#inEngine}. * @param ctx the parse tree * @return the visitor result */ T visitInEngine(@NotNull NotaQL2ColumnInParser.InEngineContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#genericFunctionVData}. * @param ctx the parse tree * @return the visitor result */ T visitGenericFunctionVData(@NotNull NotaQL2ColumnInParser.GenericFunctionVDataContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#relativePathExistencePredicate}. * @param ctx the parse tree * @return the visitor result */ T visitRelativePathExistencePredicate(@NotNull NotaQL2ColumnInParser.RelativePathExistencePredicateContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#genericFunction}. * @param ctx the parse tree * @return the visitor result */ T visitGenericFunction(@NotNull NotaQL2ColumnInParser.GenericFunctionContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#notaql}. * @param ctx the parse tree * @return the visitor result */ T visitNotaql(@NotNull NotaQL2ColumnInParser.NotaqlContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#colIdInputPathStep}. * @param ctx the parse tree * @return the visitor result */ T visitColIdInputPathStep(@NotNull NotaQL2ColumnInParser.ColIdInputPathStepContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#path}. * @param ctx the parse tree * @return the visitor result */ T visitPath(@NotNull NotaQL2ColumnInParser.PathContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#negatedPredicate}. * @param ctx the parse tree * @return the visitor result */ T visitNegatedPredicate(@NotNull NotaQL2ColumnInParser.NegatedPredicateContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#cellInputPathStep}. * @param ctx the parse tree * @return the visitor result */ T visitCellInputPathStep(@NotNull NotaQL2ColumnInParser.CellInputPathStepContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#absoluteOutputPath}. * @param ctx the parse tree * @return the visitor result */ T visitAbsoluteOutputPath(@NotNull NotaQL2ColumnInParser.AbsoluteOutputPathContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#trueAtom}. * @param ctx the parse tree * @return the visitor result */ T visitTrueAtom(@NotNull NotaQL2ColumnInParser.TrueAtomContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#colId}. * @param ctx the parse tree * @return the visitor result */ T visitColId(@NotNull NotaQL2ColumnInParser.ColIdContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#absoluteGenericOutputPath}. * @param ctx the parse tree * @return the visitor result */ T visitAbsoluteGenericOutputPath(@NotNull NotaQL2ColumnInParser.AbsoluteGenericOutputPathContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#objectConstructorFunction}. * @param ctx the parse tree * @return the visitor result */ T visitObjectConstructorFunction(@NotNull NotaQL2ColumnInParser.ObjectConstructorFunctionContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#index}. * @param ctx the parse tree * @return the visitor result */ T visitIndex(@NotNull NotaQL2ColumnInParser.IndexContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#multiplicatedVData}. * @param ctx the parse tree * @return the visitor result */ T visitMultiplicatedVData(@NotNull NotaQL2ColumnInParser.MultiplicatedVDataContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#numberAtom}. * @param ctx the parse tree * @return the visitor result */ T visitNumberAtom(@NotNull NotaQL2ColumnInParser.NumberAtomContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#aggregateVData}. * @param ctx the parse tree * @return the visitor result */ T visitAggregateVData(@NotNull NotaQL2ColumnInParser.AggregateVDataContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#rowInputPathStep}. * @param ctx the parse tree * @return the visitor result */ T visitRowInputPathStep(@NotNull NotaQL2ColumnInParser.RowInputPathStepContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#pathToken}. * @param ctx the parse tree * @return the visitor result */ T visitPathToken(@NotNull NotaQL2ColumnInParser.PathTokenContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#constructorVData}. * @param ctx the parse tree * @return the visitor result */ T visitConstructorVData(@NotNull NotaQL2ColumnInParser.ConstructorVDataContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#absolutePathExistencePredicate}. * @param ctx the parse tree * @return the visitor result */ T visitAbsolutePathExistencePredicate(@NotNull NotaQL2ColumnInParser.AbsolutePathExistencePredicateContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#bracedVData}. * @param ctx the parse tree * @return the visitor result */ T visitBracedVData(@NotNull NotaQL2ColumnInParser.BracedVDataContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#stringAtom}. * @param ctx the parse tree * @return the visitor result */ T visitStringAtom(@NotNull NotaQL2ColumnInParser.StringAtomContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#falseAtom}. * @param ctx the parse tree * @return the visitor result */ T visitFalseAtom(@NotNull NotaQL2ColumnInParser.FalseAtomContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#bracedPredicate}. * @param ctx the parse tree * @return the visitor result */ T visitBracedPredicate(@NotNull NotaQL2ColumnInParser.BracedPredicateContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#relativeInputPath}. * @param ctx the parse tree * @return the visitor result */ T visitRelativeInputPath(@NotNull NotaQL2ColumnInParser.RelativeInputPathContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#genericConstructorFunction}. * @param ctx the parse tree * @return the visitor result */ T visitGenericConstructorFunction(@NotNull NotaQL2ColumnInParser.GenericConstructorFunctionContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#splittedInputPath}. * @param ctx the parse tree * @return the visitor result */ T visitSplittedInputPath(@NotNull NotaQL2ColumnInParser.SplittedInputPathContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#atomVData}. * @param ctx the parse tree * @return the visitor result */ T visitAtomVData(@NotNull NotaQL2ColumnInParser.AtomVDataContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#simpleInputPath}. * @param ctx the parse tree * @return the visitor result */ T visitSimpleInputPath(@NotNull NotaQL2ColumnInParser.SimpleInputPathContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#attributeId}. * @param ctx the parse tree * @return the visitor result */ T visitAttributeId(@NotNull NotaQL2ColumnInParser.AttributeIdContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#outEngine}. * @param ctx the parse tree * @return the visitor result */ T visitOutEngine(@NotNull NotaQL2ColumnInParser.OutEngineContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#engine}. * @param ctx the parse tree * @return the visitor result */ T visitEngine(@NotNull NotaQL2ColumnInParser.EngineContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#relativeOutputPath}. * @param ctx the parse tree * @return the visitor result */ T visitRelativeOutputPath(@NotNull NotaQL2ColumnInParser.RelativeOutputPathContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#relativeCurrentCellPathStep}. * @param ctx the parse tree * @return the visitor result */ T visitRelativeCurrentCellPathStep(@NotNull NotaQL2ColumnInParser.RelativeCurrentCellPathStepContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#absoluteInputPathVData}. * @param ctx the parse tree * @return the visitor result */ T visitAbsoluteInputPathVData(@NotNull NotaQL2ColumnInParser.AbsoluteInputPathVDataContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#genericPathToken}. * @param ctx the parse tree * @return the visitor result */ T visitGenericPathToken(@NotNull NotaQL2ColumnInParser.GenericPathTokenContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#standalonePredicate}. * @param ctx the parse tree * @return the visitor result */ T visitStandalonePredicate(@NotNull NotaQL2ColumnInParser.StandalonePredicateContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#orPredicate}. * @param ctx the parse tree * @return the visitor result */ T visitOrPredicate(@NotNull NotaQL2ColumnInParser.OrPredicateContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#outPredicate}. * @param ctx the parse tree * @return the visitor result */ T visitOutPredicate(@NotNull NotaQL2ColumnInParser.OutPredicateContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#relativeInputPathVData}. * @param ctx the parse tree * @return the visitor result */ T visitRelativeInputPathVData(@NotNull NotaQL2ColumnInParser.RelativeInputPathVDataContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#inPredicate}. * @param ctx the parse tree * @return the visitor result */ T visitInPredicate(@NotNull NotaQL2ColumnInParser.InPredicateContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#attributeSpecification}. * @param ctx the parse tree * @return the visitor result */ T visitAttributeSpecification(@NotNull NotaQL2ColumnInParser.AttributeSpecificationContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#relativeGenericOutputPath}. * @param ctx the parse tree * @return the visitor result */ T visitRelativeGenericOutputPath(@NotNull NotaQL2ColumnInParser.RelativeGenericOutputPathContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#transformation}. * @param ctx the parse tree * @return the visitor result */ T visitTransformation(@NotNull NotaQL2ColumnInParser.TransformationContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#aggregationFunction}. * @param ctx the parse tree * @return the visitor result */ T visitAggregationFunction(@NotNull NotaQL2ColumnInParser.AggregationFunctionContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#relationalPredicate}. * @param ctx the parse tree * @return the visitor result */ T visitRelationalPredicate(@NotNull NotaQL2ColumnInParser.RelationalPredicateContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#absoluteInputPath}. * @param ctx the parse tree * @return the visitor result */ T visitAbsoluteInputPath(@NotNull NotaQL2ColumnInParser.AbsoluteInputPathContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#addedVData}. * @param ctx the parse tree * @return the visitor result */ T visitAddedVData(@NotNull NotaQL2ColumnInParser.AddedVDataContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#andPredicate}. * @param ctx the parse tree * @return the visitor result */ T visitAndPredicate(@NotNull NotaQL2ColumnInParser.AndPredicateContext ctx); /** * Visit a parse tree produced by {@link NotaQL2ColumnInParser#resolvedInputPathStep}. * @param ctx the parse tree * @return the visitor result */ T visitResolvedInputPathStep(@NotNull NotaQL2ColumnInParser.ResolvedInputPathStepContext ctx); }
true
b220f90daba7015773f57dd556f025166548032d
Java
rainishjj/afterClass
/20200301/prototype/src/main/java/com/rainish/proxy/IPerson.java
UTF-8
85
1.757813
2
[]
no_license
package com.rainish.proxy; public interface IPerson { public void findLove(); }
true
a5d471ab8a9e4a607b0c79ad60e0208c0f48d4cc
Java
arekop100/LAB_5
/src/main/java/pl/edu/pwsztar/service/serviceImpl/MovieServiceImpl.java
UTF-8
2,217
2.4375
2
[]
no_license
package pl.edu.pwsztar.service.serviceImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.edu.pwsztar.domain.dto.CreateMovieDto; import pl.edu.pwsztar.domain.dto.MovieDto; import pl.edu.pwsztar.domain.entity.Movie; import pl.edu.pwsztar.domain.mapper.MovieListMapperToDto; import pl.edu.pwsztar.domain.mapper.MovieMapperFromCreateMovieDto; import pl.edu.pwsztar.domain.repository.MovieRepository; import pl.edu.pwsztar.exception.MovieNotFoundException; import pl.edu.pwsztar.service.MovieService; import java.util.List; import java.util.Optional; @Service public class MovieServiceImpl implements MovieService { private static final Logger LOGGER = LoggerFactory.getLogger(MovieServiceImpl.class); private final MovieRepository movieRepository; private final MovieListMapperToDto movieListMapperToDto; private final MovieMapperFromCreateMovieDto movieMapperFromCreateMovieDto; @Autowired public MovieServiceImpl(MovieRepository movieRepository, MovieListMapperToDto movieListMapperToDto, MovieMapperFromCreateMovieDto movieMapperFromCreateMovieDto) { this.movieRepository = movieRepository; this.movieListMapperToDto = movieListMapperToDto; this.movieMapperFromCreateMovieDto = movieMapperFromCreateMovieDto; } @Override public List<MovieDto> findAll() { List<Movie> movies = movieRepository.findAll(); return movieListMapperToDto.convert(movies); } @Override public void creatMovie(CreateMovieDto createMovieDto) { Movie movie = movieMapperFromCreateMovieDto.convert(createMovieDto); movieRepository.save(movie); } @Override public void deleteMovie(Long movieId) throws MovieNotFoundException { checkIfMovieExists(movieId); movieRepository.deleteById(movieId); } private void checkIfMovieExists(Long movieId) throws MovieNotFoundException { movieRepository.findById(Optional.ofNullable(movieId).orElse(0L)) .orElseThrow(MovieNotFoundException::new); } }
true
b81326331263b2e7d6c365a57e9ebce56748e479
Java
BashayrYahya/Smart-Messenger
/app/src/main/java/com/example/root/smartmessenger/activity/ThirdFregment.java
UTF-8
6,480
1.984375
2
[]
no_license
package com.example.root.smartmessenger.activity; import android.content.Context; import android.content.SharedPreferences; 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.TextView; import android.widget.EditText; import android.widget.Toast; import com.example.root.smartmessenger.Models.Registrationfeedback; import com.example.root.smartmessenger.Models.Status; import com.example.root.smartmessenger.R; import com.google.firebase.messaging.FirebaseMessaging; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static com.example.root.smartmessenger.activity.MainActivity.api; import static com.example.root.smartmessenger.activity.MainActivity.call; import static com.example.root.smartmessenger.activity.MainActivity.typeface_awsome; import static com.example.root.smartmessenger.activity.MainActivity.typeface_poiret; import static com.example.root.smartmessenger.activity.SecondFregment.messageReq; import static com.example.root.smartmessenger.activity.SecondFregment.ret; /** * Created by ROOT on 2/3/2018. */ public class ThirdFregment extends Fragment { // Store instance variables private String title; private int page; private String token=""; TextView codeicon,banner; Registrationfeedback retval; EditText code; Button confirm; public static final String PREFS_NAME = "preferences"; public static final String PREF_CODE = "session"; // newInstance constructor for creating fragment with arguments public static ThirdFregment newInstance(int page, String title) { ThirdFregment thirdFregment = new ThirdFregment(); Bundle args = new Bundle(); args.putInt("someInt", page); args.putString("someTitle", title); thirdFregment.setArguments(args); return thirdFregment; } // Store instance variables based on arguments passed @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); page = getArguments().getInt("someInt", 0); title = getArguments().getString("someTitle"); retval=new Registrationfeedback(); Toast.makeText(getActivity(),title,Toast.LENGTH_SHORT).show(); } // Inflate the view for the fragment based on layout XML @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.confirmation, container, false); codeicon=(TextView) view.findViewById(R.id.codeicon); codeicon.setTypeface(typeface_awsome); code=(EditText)view.findViewById(R.id.code); banner=(TextView) view.findViewById(R.id.conbanner); banner.setTypeface(typeface_poiret); confirm=(Button) view.findViewById(R.id.confirm); confirm.setTypeface(typeface_awsome); confirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(code.getText().toString().equals(ret.getCode())) { messageReq.setSession(ret.getSession()); call=api.register(messageReq); call.enqueue(new Callback<Registrationfeedback>() { @Override public void onResponse(Call<Registrationfeedback> call, Response<Registrationfeedback> response) { retval = response.body(); if(retval.getExists()) { Toast.makeText(getActivity(),"Already Registered!!!",Toast.LENGTH_SHORT).show(); ((MainActivity) getActivity()).getVpPager().setCurrentItem(0); } else { if(retval.getFlag()) { Toast.makeText(getActivity(),"Successfully Registered!!!",Toast.LENGTH_SHORT).show(); FirebaseMessaging.getInstance().subscribeToTopic(ret.getSession()); String temp=messageReq.getEmail(); token=""; for(int i=0;i<temp.length();i++) { if(temp.charAt(i)!='@') token+=temp.charAt(i); } Toast.makeText(getActivity(),token,Toast.LENGTH_SHORT).show(); FirebaseMessaging.getInstance().subscribeToTopic(token); savePreferences(getActivity(),ret.getSession(),messageReq.getEmail(),messageReq.getPassword()); ((MainActivity) getActivity()).getVpPager().setCurrentItem(0); } else { Toast.makeText(getActivity(),"Try Again!!!",Toast.LENGTH_SHORT).show(); } } } @Override public void onFailure(Call<Registrationfeedback> call, Throwable t) { Toast.makeText(getActivity(),"Internet Connection Failed!!",Toast.LENGTH_SHORT).show(); } }); } else { Toast.makeText(getActivity(),"Code didn't matched!!!",Toast.LENGTH_SHORT).show(); } } }); return view; } public static void savePreferences(Context context,String session,String email,String pass) { SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); // Edit and commit editor.putString(PREF_CODE,session); editor.putString("email",email); editor.putString("password",pass); editor.apply(); } }
true
966a5bef18c6e339911e723e35e59aaeb10c6018
Java
kys4548/2020_Simple_Web_Project
/스프링 기반 REST API 개발_인프런 백기선/rest-api-with-spring/src/test/java/com/example/demoinflearnrestapi/events/EventControllerTests.java
UTF-8
16,466
1.796875
2
[]
no_license
package com.example.demoinflearnrestapi.events; import com.example.demoinflearnrestapi.accounts.Account; import com.example.demoinflearnrestapi.accounts.AccountRepository; import com.example.demoinflearnrestapi.accounts.AccountRole; import com.example.demoinflearnrestapi.accounts.AccountService; import com.example.demoinflearnrestapi.common.AppProperties; import com.example.demoinflearnrestapi.common.BaseTest; import com.example.demoinflearnrestapi.common.RestDocsConfiguration; import com.fasterxml.jackson.databind.ObjectMapper; import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Import; import org.springframework.hateoas.MediaTypes; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.oauth2.common.util.Jackson2JsonParser; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import java.time.LocalDateTime; import java.util.Set; import java.util.stream.IntStream; import static org.springframework.restdocs.headers.HeaderDocumentation.*; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.links; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.payload.PayloadDocumentation.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; public class EventControllerTests extends BaseTest { @Autowired EventRepository eventRepository; @Autowired AccountService accountService; @Autowired AccountRepository accountRepository; @Autowired AppProperties appProperties; @BeforeEach public void setUp() { eventRepository.deleteAll(); accountRepository.deleteAll(); } @Test @DisplayName("정상적인 Event 생성 성공") void createEvent() throws Exception { EventDto event = EventDto.builder() .name("birthDay") .description("happy birthday to you!") .beginEnrollmentDateTime(LocalDateTime.of(2020, 8, 13, 7, 11)) .closeEnrollmentDateTime(LocalDateTime.of(2020, 11, 1, 0, 0)) .beginEventDateTime(LocalDateTime.of(2020, 9, 1, 0, 0)) .endEventDateTime(LocalDateTime.of(2020, 12, 1, 0, 0)) .basePrice(100) .maxPrice(200) .limitOfEnrollment(100) .location("강남역 D2 스타텁 팩토리") .build(); mockMvc.perform(post("/api/events") .header(HttpHeaders.AUTHORIZATION, getBearerToken()) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(event)) .accept(MediaTypes.HAL_JSON)) .andDo(print()) .andExpect(status().isCreated()) .andExpect(jsonPath("id").exists()) .andExpect(header().exists(HttpHeaders.LOCATION)) .andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaTypes.HAL_JSON_VALUE)) .andExpect(jsonPath("id").value(Matchers.not(100))) .andExpect(jsonPath("free").value(Matchers.not(true))) .andExpect(jsonPath("eventStatus").value(EventStatus.DRAFT.name())) .andExpect(jsonPath("_links.self").exists()) .andExpect(jsonPath("_links.query-events").exists()) .andExpect(jsonPath("_links.update-event").exists()) .andDo(document("create-event", links( linkWithRel("self").description("link to self"), linkWithRel("query-events").description("link to query events"), linkWithRel("update-event").description("link to update an existing event"), linkWithRel("profile").description("link to profile") ), requestHeaders( headerWithName(HttpHeaders.ACCEPT).description("accept header"), headerWithName(HttpHeaders.CONTENT_TYPE).description("content type header") ), relaxedRequestFields( fieldWithPath("name").description("Name of event") ), responseHeaders( headerWithName(HttpHeaders.LOCATION).description("location"), headerWithName(HttpHeaders.CONTENT_TYPE).description("hal+json") ), relaxedResponseFields( fieldWithPath("id").description("Id of event"), fieldWithPath("_links.profile.href").description("link to profile") ) )) ; } private String getBearerToken() throws Exception { return "Bearer " + getAccessToken(); } private String getAccessToken() throws Exception { //Given final String username = appProperties.getUserUsername(); final String password = appProperties.getUserPassword(); final Account account = Account.builder() .username(username) .password(password) .roles(Set.of(AccountRole.ADMIN, AccountRole.USER)) .build(); accountService.saveAccount(account); String clientId = appProperties.getClientId(); String clientSecret = appProperties.getClientSecret(); final ResultActions perform = mockMvc.perform(post("/oauth/token") .with(httpBasic(clientId, clientSecret)) .param("username", username) .param("password", password) .param("grant_type", "password") ); final MockHttpServletResponse response = perform.andReturn().getResponse(); final String contentAsBody = response.getContentAsString(); final Jackson2JsonParser parser = new Jackson2JsonParser(); return parser.parseMap(contentAsBody).get("access_token").toString(); } @Test @DisplayName("createEvent 요구하지 않은값 들어올때 요청 실패") void createEvent_Bad_Request() throws Exception { Event event = Event.builder() .id(100L) .name("birthDay") .description("happy birthday to you!") .beginEnrollmentDateTime(LocalDateTime.of(2020, 8, 13, 7, 11)) .closeEnrollmentDateTime(LocalDateTime.of(2021, 1, 1, 0, 0)) .beginEventDateTime(LocalDateTime.of(2020, 9, 1, 0, 0)) .endEventDateTime(LocalDateTime.of(2020, 12, 1, 0, 0)) .basePrice(100) .maxPrice(200) .limitOfEnrollment(100) .location("강남역 D2 스타텁 팩토리") .free(true) .offline(false) .eventStatus(EventStatus.PUBLISHED) .build(); mockMvc.perform(post("/api/events") .header(HttpHeaders.AUTHORIZATION, getBearerToken()) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(event)) .accept(MediaTypes.HAL_JSON)) .andDo(print()) .andExpect(status().isBadRequest()) ; } @Test @DisplayName("createEvent Empty Validation 검증") void createEvent_Bad_Request_Empty_Input() throws Exception { EventDto eventDto = EventDto.builder().build(); mockMvc.perform(post("/api/events") .header(HttpHeaders.AUTHORIZATION, getBearerToken()) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(eventDto))) .andExpect(status().isBadRequest()); } @Test @DisplayName("createEvent Wrong Validation 검증") void createEvent_Bad_Request_Wrong_Input() throws Exception { EventDto eventDto = EventDto.builder() .name("birthDay") .description("happy birthday to you!") .beginEnrollmentDateTime(LocalDateTime.of(2020, 8, 13, 7, 11)) .closeEnrollmentDateTime(LocalDateTime.of(2021, 1, 1, 0, 0)) .beginEventDateTime(LocalDateTime.of(2020, 9, 1, 0, 0)) .endEventDateTime(LocalDateTime.of(2020, 1, 1, 0, 0)) .basePrice(10000) .maxPrice(200) .limitOfEnrollment(100) .location("강남역 D2 스타텁 팩토리") .build(); mockMvc.perform(post("/api/events") .header(HttpHeaders.AUTHORIZATION, getBearerToken()) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(eventDto))) .andExpect(status().isBadRequest()) .andExpect(jsonPath("content[0].objectName").exists()) .andExpect(jsonPath("content[0].defaultMessage").exists()) .andExpect(jsonPath("content[0].code").exists()) .andExpect(jsonPath("_links.index").exists()) ; } @Test @DisplayName("30개의 이벤트를 10개씩 두번째 페이지 조회하기") public void queryEvents() throws Exception { //Given IntStream.range(0, 30).forEach(this::generatedEvent); //When mockMvc.perform(get("/api/events") .param("page", "1") .param("size", "10") .param("sort", "name,DESC") ) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("_embedded.eventList[0]._links.self").exists()) .andExpect(jsonPath("_links.self").exists()) .andExpect(jsonPath("_links.profile").exists()) .andDo(document("query-events")) ; } @Test @DisplayName("30개의 이벤트를 10개씩 두번째 페이지 조회하기 인증") public void queryEventsWithAuthentication() throws Exception { //Given IntStream.range(0, 30).forEach(this::generatedEvent); //When mockMvc.perform(get("/api/events") .header(HttpHeaders.AUTHORIZATION, getBearerToken()) .param("page", "1") .param("size", "10") .param("sort", "name,DESC") ) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("_embedded.eventList[0]._links.self").exists()) .andExpect(jsonPath("_links.self").exists()) .andExpect(jsonPath("_links.profile").exists()) .andDo(document("query-events")) ; } @Test @DisplayName("기존의 이벤트를 하나 조회하기") public void getEvent() throws Exception { //Given Event event = this.generatedEvent(100); //When mockMvc.perform(get("/api/events/{id}", event.getId())) .andExpect(status().isOk()) .andExpect(jsonPath("name").exists()) .andExpect(jsonPath("id").exists()) .andExpect(jsonPath("_links.self").exists()) .andExpect(jsonPath("_links.profile").exists()) .andDo(document("get-an-event")) ; } @Test @DisplayName("없는 이벤트 조회했을 때 404 응답받기") public void getEvent404() throws Exception { // Given When Then mockMvc.perform(get("/api/events/{id}", 1324L)) .andExpect(status().isNotFound()); } @Test @DisplayName("이벤트를 정삭적으로 수정하기") public void updateEvent() throws Exception { Event event = this.generatedEvent(200); final EventDto eventDto = this.modelMapper.map(event, EventDto.class); final String eventName = "Updated Event"; eventDto.setName(eventName); mockMvc.perform(put("/api/events/{id}", event.getId()) .header(HttpHeaders.AUTHORIZATION, getBearerToken()) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(eventDto)) ) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("name").value(eventName)) .andExpect(jsonPath("_links.self").exists()) .andDo(document("update-event")) ; } @Test @DisplayName("입력값이 비어있는 경우에 이벤트 수정 실패") public void updateEvent400Empty() throws Exception { Event event = this.generatedEvent(200); EventDto eventDto = new EventDto(); mockMvc.perform(put("/api/events/{id}", event.getId()) .header(HttpHeaders.AUTHORIZATION, getBearerToken()) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(eventDto)) ) .andExpect(status().isBadRequest()); } @Test @DisplayName("입력값이 잘못된 경우에 이벤트 수정 실패") public void updateEvent400Wrong() throws Exception { Event event = this.generatedEvent(200); EventDto eventDto = modelMapper.map(event, EventDto.class); eventDto.setBasePrice(20000); eventDto.setMaxPrice(1000); mockMvc.perform(put("/api/events/{id}", event.getId()) .header(HttpHeaders.AUTHORIZATION, getBearerToken()) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(eventDto)) ) .andExpect(status().isBadRequest()); } @Test @DisplayName("존재하지 않는 이벤트 수정 실패") public void updateEvent404() throws Exception { final Event event = this.generatedEvent(200); final EventDto eventDto = this.modelMapper.map(event, EventDto.class); mockMvc.perform(put("/api/events/234242342") .header(HttpHeaders.AUTHORIZATION, getBearerToken()) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(eventDto)) ) .andDo(print()) .andExpect(status().isNotFound()); } private Event generatedEvent(int index) { Event event = Event.builder() .name("event" + index) .description("test event") .beginEnrollmentDateTime(LocalDateTime.of(2020, 8, 13, 7, 11)) .closeEnrollmentDateTime(LocalDateTime.of(2020, 11, 1, 0, 0)) .beginEventDateTime(LocalDateTime.of(2020, 9, 1, 0, 0)) .endEventDateTime(LocalDateTime.of(2020, 12, 1, 0, 0)) .basePrice(100) .maxPrice(200) .limitOfEnrollment(100) .location("강남역 D2 스타텁 팩토리") .free(false) .offline(true) .eventStatus(EventStatus.DRAFT) .build(); return eventRepository.save(event); } }
true
405235ec8aa7b935ef8003d5c7fb6e333022b1a3
Java
kpomier777/Patronesexam2
/src/main/java/state/basic/Prendido.java
UTF-8
748
2.828125
3
[]
no_license
package state.basic; public class Prendido implements IStateComputadora { @Override public void handler(Computadora computadora) { System.out.println("** Estado: Prendido**"); int cantidadProg=(int)(Math.random()*20+1); computadora.setProgramasAbiertos(""+cantidadProg); computadora.setMemoriaRam(new MemoriaRam(cantidadProg*5)); computadora.setCpu(new CPU(cantidadProg*5)); System.out.println("%Programas abiertos:"+computadora.getProgramasAbiertos()); System.out.println("%Meoria Ram:"+computadora.getMemoriaRam().getPercentageUse()+"%"); System.out.println("%Consumo CPU:"+computadora.getCpu().getPercentageUse()+"%"); System.out.println("********"); } }
true
8791a2bf08949feb1a5de662cbd67ea8f4dcabb8
Java
MaryRosariaTaft/cse219_javafx-software-development
/Project2_PoseMaker/PoseMakerApp/src/pm/data/DataManager.java
UTF-8
931
2.640625
3
[]
no_license
package pm.data; import pm.gui.Workspace; import saf.components.AppDataComponent; import saf.AppTemplate; /** * This class serves as the data management component for this application. * * @author Richard McKenna * @author Mary R. Taft * @version 1.0 */ public class DataManager implements AppDataComponent { // THIS IS A SHARED REFERENCE TO THE APPLICATION AppTemplate app; Workspace workspace; /** * THis constructor creates the data manager and sets up the * * * @param initApp The application within which this data manager is serving. */ public DataManager(AppTemplate initApp) throws Exception { // KEEP THE APP FOR LATER app = initApp; } @Override public void reset() { getWorkspace().resetWorkspace(); } public Workspace getWorkspace(){ return workspace; } public void setWorkspace(Workspace w){ workspace = w; } }
true
0f28baddafde2cf78a5f2e040172faba62bae00e
Java
lmr1109665009/oa
/java/service-oa/src/main/java/com/suneee/eas/oa/service/car/impl/CarInsuranceServiceImpl.java
UTF-8
4,383
2.1875
2
[]
no_license
/** * Copyright (C), 2015-2018, XXX有限公司 * FileName: CarInsuranceServiceImpl * Author: lmr * Date: 2018/8/16 13:41 * Description: * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ package com.suneee.eas.oa.service.car.impl; import com.suneee.eas.common.service.impl.BaseServiceImpl; import com.suneee.eas.common.utils.BeanUtils; import com.suneee.eas.common.utils.ContextSupportUtil; import com.suneee.eas.common.utils.IdGeneratorUtil; import com.suneee.eas.oa.dao.car.CarInsuranceDao; import com.suneee.eas.oa.model.car.CarInsurance; import com.suneee.eas.oa.service.car.CarInsuranceService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * 〈一句话功能简述〉<br> * 〈〉 * * @author lmr * @create 2018/8/16 * @since 1.0.0 */ @Service public class CarInsuranceServiceImpl extends BaseServiceImpl<CarInsurance> implements CarInsuranceService { private static final Logger LOGGER = LogManager.getLogger(CarInsuranceServiceImpl.class); private CarInsuranceDao carInsuranceDao; @Autowired public void setCarInsuranceDao(CarInsuranceDao carInsuranceDao) { this.carInsuranceDao = carInsuranceDao; setBaseDao(carInsuranceDao); } /** * 查看添加时是否有相同的保险单号 * @param insurNum * @return */ @Override public boolean isInsurNumRepeatForAdd(String insurNum) { if(BeanUtils.isEmpty(insurNum)){ LOGGER.error("insurNum can not be empty."); } Map<String,Object> params = new HashMap<>(); params.put("insurNum",insurNum); int count = carInsuranceDao.isInsurNumRepeatForAdd(params); if (count > 0) { return true; } return false; } /** * 查看更新时是否有相同的保险单号 * @param insurId * @param insurNum * @return */ @Override public boolean isInsurNumRepeatForUpdate(Long insurId, String insurNum) { if(BeanUtils.isEmpty(insurNum)||BeanUtils.isEmpty(insurId)){ LOGGER.error("insurNum and insurId can not be empty."); } Map<String,Object> params = new HashMap<>(); params.put("insurId",insurId); params.put("insurNum",insurNum); int count = carInsuranceDao.isInsurNumRepeatForUpdate(params); if (count > 0) { return true; } return false; } @Override public void deleteByIds(Long[] insurIds) { if(BeanUtils.isEmpty(insurIds)||insurIds.length==0){ LOGGER.error("parameter cannot be empty."); } for (Long insurId: insurIds) { deleteById(insurId); } } @Override public int deleteById(Long id) { Map<String,Object> params = new HashMap<>(); params.put("updateBy", ContextSupportUtil.getCurrentUserId()); params.put("updateTime",new Date()); params.put("insurId",id); return carInsuranceDao.deleteById(params); } @Override public int save(CarInsurance carInsurance) { //生成唯一主键ID Long id = IdGeneratorUtil.getNextId(); carInsurance.setInsurId(id); carInsurance.setEnterpriseCode(ContextSupportUtil.getCurrentEnterpriseCode()); //设置创建人、更新人 Long currrentUserId = ContextSupportUtil.getCurrentUserId(); String aliasName = ContextSupportUtil.getCurrentUser().getAliasName(); carInsurance.setCreateBy(currrentUserId); carInsurance.setUpdateBy(currrentUserId); //获取当前时间 Date date = new Date(); carInsurance.setCreateTime(date); carInsurance.setUpdateTime(date); return carInsuranceDao.save(carInsurance); } @Override public int update(CarInsurance carInsurance) { //设置更新人更新人 carInsurance.setUpdateBy(ContextSupportUtil.getCurrentUserId()); //设置更新时间 carInsurance.setUpdateTime(new Date()); return carInsuranceDao.update(carInsurance); } }
true
5ba88e10b62c50e43a4f6c90065fd2ee246b6ef0
Java
OnClickListener2048/Fapiaobao
/app/src/main/java/com/pilipa/fapiaobao/ui/fragment/UploadNormalReceiptFragment.java
UTF-8
19,734
1.539063
2
[]
no_license
package com.pilipa.fapiaobao.ui.fragment; import android.Manifest; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v7.util.DiffUtil; 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.example.mylibrary.utils.TLog; import com.pilipa.fapiaobao.R; import com.pilipa.fapiaobao.adapter.supply.UploadReceiptAdapter; import com.pilipa.fapiaobao.base.BaseApplication; import com.pilipa.fapiaobao.base.BaseFragment; import com.pilipa.fapiaobao.compat.MediaStoreCompat; import com.pilipa.fapiaobao.ui.FillUpActivity; import com.pilipa.fapiaobao.ui.PreviewActivity; import com.pilipa.fapiaobao.ui.UploadReceiptActivity; import com.pilipa.fapiaobao.ui.deco.GridInset; import com.pilipa.fapiaobao.ui.model.Image; import com.pilipa.fapiaobao.ui.receipt_folder_image_select.ReceiptActivityToken; import com.pilipa.fapiaobao.utils.BitmapUtils; import com.pilipa.fapiaobao.utils.DialogUtil; import com.pilipa.fapiaobao.utils.ReceiptDiff; import com.tbruyelle.rxpermissions2.RxPermissions; import com.zhihu.matisse.Matisse; import com.zhihu.matisse.MimeType; import com.zhihu.matisse.engine.impl.GlideEngine; import com.zhihu.matisse.internal.entity.CaptureStrategy; import java.io.File; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import static android.app.Activity.RESULT_OK; /** * Created by edz on 2017/10/21. */ public class UploadNormalReceiptFragment extends BaseFragment implements UploadReceiptAdapter.OnImageClickListener, UploadReceiptAdapter.OnImageSelectListener, UploadReceiptAdapter.OnPhotoCapture, View.OnClickListener { public static final int REQUEST_CODE_CAPTURE = 10; public static final int REQUEST_CODE_CHOOSE = 20; public static final String EXTRA_ALL_DATA = "EXTRA_ALL_DATA"; public static final String EXTRA_CURRENT_POSITION = "EXTRA_CURRENT_POSITION"; public static final String EXTRA_BUNDLE = "EXTRA_BUNDLE"; public static final int REQUEST_CODE_IMAGE_CLICK = 30; public static final int RESULT_CODE_BACK = 40; public static final int REQUEST_CODE_FROM_ELEC = 50; public static final int REQUEST_CODE_AMOUNT = 60; private static final String TAG = "UploadNormalReceiptFragment"; @Bind(R.id.rv_upload_receipt) RecyclerView rvUploadReceipt; private int mImageResize; private ArrayList<Image> images; private MediaStoreCompat mediaStoreCompat; private int mPreviousPosition = -1; private Dialog mCameraDialog; private boolean is_elec_data; private Dialog mDialog; public static UploadNormalReceiptFragment newInstance(Bundle b) { UploadNormalReceiptFragment u = new UploadNormalReceiptFragment(); u.setArguments(b); return u; } @Override protected int getLayoutId() { return R.layout.fragment_upload_receipt; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO: inflate a fragment view Bundle arguments = getArguments(); is_elec_data = arguments.getBoolean(UploadReceiptActivity.IS_ELEC_RECEIPT_DATA, false); View rootView = super.onCreateView(inflater, container, savedInstanceState); ButterKnife.bind(this, rootView); return rootView; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } private void openMedia() { RxPermissions rxPermissions = new RxPermissions(getActivity()); rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Boolean aBoolean) { if (aBoolean) { Matisse.from(UploadNormalReceiptFragment.this) .choose(MimeType.of(MimeType.JPEG, MimeType.PNG)) .countable(true) .captureStrategy( new CaptureStrategy(true, MediaStoreCompat.authority)) .maxSelectable(9) .gridExpectedSize( getResources().getDimensionPixelSize(R.dimen.grid_expected_size)) .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) .thumbnailScale(0.4f) .imageEngine(new GlideEngine()) .theme(R.style.Matisse_Pilipa) .forResult(REQUEST_CODE_CHOOSE); } } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); } @Override protected void initWidget(View root) { super.initWidget(root); mediaStoreCompat = new MediaStoreCompat(getActivity(),this); GridLayoutManager grid = new GridLayoutManager(getActivity(), 3){ @Override public boolean canScrollVertically() { return false; } }; rvUploadReceipt.setLayoutManager(grid); int spacing = getResources().getDimensionPixelOffset(R.dimen.spacing); rvUploadReceipt.addItemDecoration(new GridInset(3, spacing, true)); Image image = new Image(); image.isFromNet = false; image.isCapture = true; images = new ArrayList<>(); images.add(image); mPreviousPosition = images.size(); UploadReceiptAdapter uploadReceiptAdapter = new UploadReceiptAdapter(images, getImageResize(getActivity())); uploadReceiptAdapter.setOnImageClickListener(this); uploadReceiptAdapter.setOnImageSelectListener(this); uploadReceiptAdapter.setOnPhotoCapture(this); rvUploadReceipt.setAdapter(uploadReceiptAdapter); } private int getImageResize(Context context) { if (mImageResize == 0) { RecyclerView.LayoutManager lm = rvUploadReceipt.getLayoutManager(); int spanCount = ((GridLayoutManager) lm).getSpanCount(); int screenWidth = context.getResources().getDisplayMetrics().widthPixels; int availableWidth = screenWidth - context.getResources().getDimensionPixelSize( R.dimen.spacing) * (spanCount - 1); mImageResize = availableWidth / spanCount; mImageResize = (int) (mImageResize * 0.5); } return mImageResize; } @Override public void onImageClick(ArrayList<Image> allItemList, int position) { Image image = allItemList.get(position); Intent intent = new Intent(mContext, PreviewActivity.class); Bundle bundle = new Bundle(); bundle.putParcelableArrayList(EXTRA_ALL_DATA, allItemList); TLog.log("position" + position); TLog.log("image.position" + image.position); bundle.putInt(EXTRA_CURRENT_POSITION, position); // intent.putExtra(EXTRA_BUNDLE, bundle); startActivityForResult(intent, REQUEST_CODE_IMAGE_CLICK); } @Override public void onImageSelect(Image image) { } @Override public void capture() { if (is_elec_data) { showElecDialog(); } else { showDialog(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_CAPTURE&&resultCode == RESULT_OK) { Uri contentUri = mediaStoreCompat.getCurrentPhotoUri(); String path = mediaStoreCompat.getCurrentPhotoPath(); // try { // TLog.log("path"+path); // MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), path, new File(path).getName(), null); // getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri)); // } catch (NullPointerException e) { // e.printStackTrace(); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } Image image = new Image(); image.isFromNet = false; image.name = new File(path).getName(); image.isCapture = false; image.path = path; image.position = mPreviousPosition; image.uri = contentUri; ArrayList<Image> arrayList = new ArrayList<>(); arrayList.add(image); Intent intent = new Intent(); intent.setClass(mContext, FillUpActivity.class); intent.putParcelableArrayListExtra("images", arrayList); startActivityForResult(intent,REQUEST_CODE_AMOUNT); // images.add(image); // UploadReceiptAdapter uploadReceiptAdapter = (UploadReceiptAdapter) rvUploadReceipt.getAdapter(); // uploadReceiptAdapter.notifyItemInserted(mPreviousPosition); // mPreviousPosition = images.size(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { getActivity().revokeUriPermission(contentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION); } } else if (REQUEST_CODE_IMAGE_CLICK == requestCode) { switch (resultCode) { case RESULT_CODE_BACK: Bundle bundleExtra = data.getBundleExtra(EXTRA_BUNDLE); ArrayList<Image> images = bundleExtra.getParcelableArrayList(EXTRA_ALL_DATA); UploadReceiptAdapter uploadReceiptAdapter = (UploadReceiptAdapter) rvUploadReceipt.getAdapter(); uploadReceiptAdapter.refresh(images); DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new ReceiptDiff(this.images, images), true); diffResult.dispatchUpdatesTo(uploadReceiptAdapter); this.images = images; mPreviousPosition = images.size(); break; default: } } else if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) { List<Uri> uris = Matisse.obtainResult(data); ArrayList<Image> arrayList = new ArrayList<>(); for (Uri uri : uris) { if (uri == null) { BaseApplication.showToast("图片格式不符,请上传其他的发票~"); return; } String path = BitmapUtils.getRealFilePath(getActivity(),uri); Image image = new Image(); image.isCapture = false; image.position = mPreviousPosition; mPreviousPosition++; image.uri = uri; image.path = path; image.isFromNet = false; arrayList.add(image); } Intent intent = new Intent(); intent.putParcelableArrayListExtra("images", arrayList); intent.setClass(mContext, FillUpActivity.class); startActivityForResult(intent,REQUEST_CODE_AMOUNT); } else if (requestCode ==REQUEST_CODE_FROM_ELEC && resultCode == RESULT_OK) { resultFromElec(data); } else if (requestCode == REQUEST_CODE_AMOUNT) { if (resultCode == RESULT_OK) { ArrayList<Image> arrayList = data.getParcelableArrayListExtra("images"); mPreviousPosition += arrayList.size(); images.addAll(arrayList); UploadReceiptAdapter uploadReceiptAdapter = (UploadReceiptAdapter) rvUploadReceipt.getAdapter(); uploadReceiptAdapter.notifyItemRangeInserted(mPreviousPosition,arrayList.size()); } } } public void resultFromElec(Intent data) { Bundle bundleExtra = data.getBundleExtra(ReceiptActivityToken.EXTRA_DATA_FROM_TOKEN); ArrayList<Image> parcelableArrayList = bundleExtra.getParcelableArrayList(ReceiptActivityToken.RESULT_RECEIPT_FOLDER); if (parcelableArrayList == null) return; if (parcelableArrayList.size() == 0) return; ArrayList<Image> arrayList = new ArrayList<>(); for (Image image : parcelableArrayList) { image.position = mPreviousPosition; arrayList.add(image); mPreviousPosition++; } Intent intent = new Intent(); intent.setClass(mContext, FillUpActivity.class); intent.putParcelableArrayListExtra("images", arrayList); startActivityForResult(intent, REQUEST_CODE_AMOUNT); } private void showDialog() { mDialog = DialogUtil.getInstance().createBottomDialog(mContext, new DialogUtil.OnDialogDismissListener() { @Override public void onDialogDismiss(View view) { mDialog.dismiss(); } }, new DialogUtil.OnMediaOpenListener() { @Override public void onMediaOpen(View view) { openMedia(); mDialog.dismiss(); } }, null, new DialogUtil.OnPhotoTakeListener() { @Override public void onPhotoTake(View view) { takePhoto(); mDialog.dismiss(); } }, null); showDialog(mDialog); } private void showElecDialog() { mDialog = DialogUtil.getInstance().createBottomDialog(mContext, new DialogUtil.OnDialogDismissListener() { @Override public void onDialogDismiss(View view) { mDialog.dismiss(); } }, new DialogUtil.OnMediaOpenListener() { @Override public void onMediaOpen(View view) { openMedia(); mDialog.dismiss(); } }, new DialogUtil.OnReceiptFolderOpenListener() { @Override public void onReceiptFolderOpen(View view) { startActivityForResult(new Intent(mContext, ReceiptActivityToken.class), REQUEST_CODE_FROM_ELEC); mDialog.dismiss(); } }, null, new DialogUtil.OnShoppingStampOpenListener() { @Override public void onShoppingStampOpen(View view) { UploadReceiptActivity activity = (UploadReceiptActivity) getActivity(); activity.scan(); mDialog.dismiss(); } }); showDialog(mDialog); } // private void setDialog() { // mCameraDialog = new Dialog(getActivity(), R.style.BottomDialog); // LinearLayout root = (LinearLayout) LayoutInflater.from(getActivity()).inflate( // R.layout.dialog_bottom, null); // //初始化视图 // root.findViewById(R.id.btn_choose_img).setOnClickListener(this); // root.findViewById(R.id.btn_open_camera).setOnClickListener(this); // root.findViewById(R.id.btn_cancel).setOnClickListener(this); // mCameraDialog.setContentView(root); // Window dialogWindow = mCameraDialog.getWindow(); // dialogWindow.setGravity(Gravity.BOTTOM); //// dialogWindow.setWindowAnimations(R.style.dialogstyle); // 添加动画 // WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值 // lp.x = 0; // 新位置X坐标 // lp.y = 0; // 新位置Y坐标 // lp.width = getResources().getDisplayMetrics().widthPixels; // 宽度 // root.measure(0, 0); // lp.height = root.getMeasuredHeight(); // // lp.alpha = 9f; // 透明度 // dialogWindow.setAttributes(lp); // mCameraDialog.show(); // } // private void setElecDialog() { // mCameraDialog = new Dialog(getActivity(), R.style.BottomDialog); // LinearLayout root = (LinearLayout) LayoutInflater.from(getActivity()).inflate( // R.layout.elec_data_bottom, null); // //初始化视图 // root.findViewById(R.id.btn_choose_img).setOnClickListener(this); // root.findViewById(R.id.btn_cancel).setOnClickListener(this); // root.findViewById(R.id.btn_choose_img_receipt_folder).setOnClickListener(this); // root.findViewById(R.id.btn_shopping_stamp).setOnClickListener(this); // // mCameraDialog.setContentView(root); // Window dialogWindow = mCameraDialog.getWindow(); // dialogWindow.setGravity(Gravity.BOTTOM); //// dialogWindow.setWindowAnimations(R.style.dialogstyle); // 添加动画 // WindowManager.LayoutParams lp = dialogWindow.getAttributes(); // 获取对话框当前的参数值 // lp.x = 0; // 新位置X坐标 // lp.y = 0; // 新位置Y坐标 // lp.width = (int) getResources().getDisplayMetrics().widthPixels; // 宽度 // root.measure(0, 0); // lp.height = root.getMeasuredHeight(); // // lp.alpha = 9f; // 透明度 // dialogWindow.setAttributes(lp); // mCameraDialog.show(); // } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } private void takePhoto() { if (MediaStoreCompat.hasCameraFeature(getActivity())) { onSaveInstanceState(getArguments()); RxPermissions rxPermissions = new RxPermissions(getActivity()); rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA).subscribe(new Observer<Boolean>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Boolean aBoolean) { if (aBoolean) { mediaStoreCompat.dispatchCaptureIntent(getActivity(), REQUEST_CODE_CAPTURE); } } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_choose_img: openMedia(); mCameraDialog.dismiss(); break; case R.id.btn_open_camera: takePhoto(); mCameraDialog.dismiss(); break; case R.id.btn_cancel: mCameraDialog.dismiss(); break; case R.id.btn_choose_img_receipt_folder: startActivityForResult(new Intent(mContext, ReceiptActivityToken.class),REQUEST_CODE_FROM_ELEC); mCameraDialog.dismiss(); break; case R.id.btn_shopping_stamp: UploadReceiptActivity activity = (UploadReceiptActivity) getActivity(); activity.scan(); mCameraDialog.dismiss(); break; default: } } public ArrayList<Image> getCurrentImages(){ if (images!= null) { return images; } return null; } }
true
9d88b6aca646bb38db63032d27b4d2b609a8eb42
Java
AndroidTestingWorkshop/Pokedex
/app/src/main/java/gojek/pokedex/main/PokemonsPresenter.java
UTF-8
827
2.375
2
[]
no_license
package gojek.pokedex.main; import java.util.List; import gojek.pokedex.common.NetworkError; import gojek.pokedex.model.Pokemon; public class PokemonsPresenter { private PokemonsView view; private PokemonService pokemonService; public PokemonsPresenter(PokemonsView view, PokemonService pokemonService) { this.view = view; this.pokemonService = pokemonService; } public void loadPokemons() { pokemonService.loadPokemons(new PokemonLoadCallback() { @Override public void onLoadFailed(NetworkError expectedError) { view.showError(expectedError.getMessage()); } @Override public void onLoadSuccess(List<Pokemon> pokemons) { view.showPokemons(pokemons); } }); } }
true
2f7a6a7c9d7c96dc7be8f3321aba3a8a107b1b84
Java
Mqwere/Name-Compiler
/src/Core/Generator.java
UTF-8
1,611
2.984375
3
[]
no_license
package Core; import java.util.ArrayList; import java.util.Random; public class Generator { private static Random ladyLuck = new Random(); private static ArrayList<String> content = new ArrayList<>(); private static int fuckups = 0; public static void generate(int noGen, int minLen, int maxLen) { for(int i=0; i<noGen;i++) generate(minLen, maxLen); toConsole(); content = new ArrayList<>(); } private static void generate(int minLen, int maxLen) { String output = new String(""); int tar = ladyLuck.nextInt(Evaluator.start.getMax()+1), size = ladyLuck.nextInt(maxLen - minLen + 1) + minLen; char bef = Evaluator.start.get(tar); output += (char)((int)bef - 32); try { /// For some unknown reason, it throws NullPointers, and it needs to have like... one restart? Weird, I know for(int i = 0; i<size; i++) { tar = ladyLuck.nextInt(Evaluator.flow.get(bef).getMax()+1); bef = Evaluator.flow.get(bef).get(tar); output += bef; } fuckups = 0; content.add(output); } catch(Exception e) { if(fuckups++>9) Program.error("Generator.generate(int,int) - 10 attempts failed, ditching the output..."); else Generator.generate(minLen, maxLen); } } public static void ranGen(int noGen, int minLen, int maxLen) { Evaluator.randomMap(); Generator.generate(noGen, minLen, maxLen); } public static void toConsole() { String output = new String("Generation completed:"); for(String s: content) { output +="\n" + s; } communicate(output); } public static void communicate(Object message) {Program.write("GEN",message);} }
true
1515911b78c3942968700dfad4afaa4a0b9c5273
Java
ironcolumn/guitarSys
/api/src/main/java/com/example/demo/dao/BuilderRepository.java
UTF-8
371
1.757813
2
[]
no_license
package com.example.demo.dao; import com.example.demo.model.Builder; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository @EnableAutoConfiguration public interface BuilderRepository extends JpaRepository<Builder, Integer> { }
true
323c9a827fbaec05545d97dc70d45a3951532590
Java
pubnub/chat-examples-java
/app/snippets/chatresourcecenter/EncryptionTest.java
UTF-8
2,042
2.125
2
[ "MIT" ]
permissive
package chatresourcecenter; import com.pubnub.api.PNConfiguration; import com.pubnub.api.PubNub; import com.pubnub.api.PubNubException; import org.junit.Test; import java.util.UUID; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class EncryptionTest extends TestHarness { @Test public void testEnableEncryption() { // tag::ENCR-1[] PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.setSubscribeKey(SUB_KEY); pnConfiguration.setPublishKey(PUB_KEY); pnConfiguration.setSecure(true); PubNub pubNub = new PubNub(pnConfiguration); // end::ENCR-1[] assertNotNull(pubNub); assertTrue(pubNub.getConfiguration().isSecure()); } @Test public void testCipherKey() throws PubNubException { final String expectedCipherKey = UUID.randomUUID().toString(); final String expectedString = UUID.randomUUID().toString(); // tag::ENCR-2[] PNConfiguration pnConfiguration = new PNConfiguration(); pnConfiguration.setSubscribeKey(SUB_KEY); pnConfiguration.setPublishKey(PUB_KEY); // tag::ignore[] /* // end::ignore[] pnConfiguration.setCipherKey("myCipherKey"); // tag::ignore[] */ // end::ignore[] // tag::ignore[] pnConfiguration.setCipherKey(expectedCipherKey); // end::ignore[] PubNub pubNub = new PubNub(pnConfiguration); // end::ENCR-2[] assertNotNull(pubNub); assertEquals(expectedCipherKey, pubNub.getConfiguration().getCipherKey()); String encrypted = pubNub.encrypt(expectedString, expectedCipherKey); String decrypted = pubNub.decrypt(encrypted, expectedCipherKey); assertEquals(expectedString, decrypted); } @Test public void testSendSignedMessage() { // tag::ENCR-3[] // in progress // end::ENCR-3[] } }
true
1cf3f04734107fc0b8858e79781c7f98765925f4
Java
QuantumImmortality/Auto-System-Input
/src/Manager.java
UTF-8
639
2.75
3
[]
no_license
import Input.Keyboard; import java.awt.*; public class Manager { private static Robot robot; public static void main(String[] args){ final Robot ROBOT = initialiseRobot(); Keyboard keyboard = new Keyboard(); keyboard.keyboardInput(robot); } private static Robot initialiseRobot(){ if(GraphicsEnvironment.isHeadless()) return null; try { robot = new Robot(); } catch (AWTException e){ System.out.println(" [ AWTException ] the platform configuration does not allow low-level input control"); } return robot; } }
true
e4d473e10fdb4b7eab79561c440a7c8514e2ea7a
Java
tanyujie/base-easymis
/txlcn-easymis/src/main/java/org/easymis/base/txlcn/TxlcnEasymisApplication.java
UTF-8
470
1.570313
2
[]
no_license
package org.easymis.base.txlcn; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.codingapi.txlcn.tm.config.EnableTransactionManagerServer; @SpringBootApplication @EnableTransactionManagerServer public class TxlcnEasymisApplication { //https://github.com/codingapi/txlcn-demo public static void main(String[] args) { SpringApplication.run(TxlcnEasymisApplication.class, args); } }
true
fcc004464fc88813b8071361793ec5da7ff28d5a
Java
divannn/eclipse
/plain-gef/com.dob.property/src/com/dob/property/editor/StringCellEditor.java
UTF-8
458
2.421875
2
[]
no_license
package com.dob.property.editor; import org.eclipse.jface.viewers.TextCellEditor; import org.eclipse.swt.widgets.Composite; /** * @author idanilov * */ public class StringCellEditor extends TextCellEditor { public StringCellEditor(Composite parent) { super(parent); } @Override protected void doSetValue(Object value) { //check for null value. Bypass assert in super. if (value == null) { value = ""; } super.doSetValue(value); } }
true
2454278297265b592c25a8067fe77de3c4567a68
Java
JetBrains/intellij-community
/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowWatcher.java
UTF-8
10,890
2.234375
2
[ "Apache-2.0" ]
permissive
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl; import com.intellij.ide.DataManager; import com.intellij.ide.impl.ProjectUtil; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.FocusWatcher; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.ex.WindowManagerEx; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentEvent; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.ref.WeakReference; import java.util.*; public final class WindowWatcher implements PropertyChangeListener { private static final Logger LOG = Logger.getInstance(WindowWatcher.class); private final Object myLock = new Object(); private final Map<@NotNull Window, WindowInfo> windowToInfo = new WeakHashMap<>(); /** * Currently focused window (window which has focused component). Can be {@code null} if there is no focused * window at all. */ private Window myFocusedWindow; /** * Contains last focused window for each project. */ private final Set<Window> myFocusedWindows = new HashSet<>(); private static final @NonNls String FOCUSED_WINDOW_PROPERTY = "focusedWindow"; WindowWatcher() {} /** * This method should get notifications about changes of focused window. * Only {@code focusedWindow} property is acceptable. * * @throws IllegalArgumentException if property name isn't {@code focusedWindow}. */ @Override public void propertyChange(@NotNull PropertyChangeEvent e) { if (LOG.isDebugEnabled()) { LOG.debug("enter: propertyChange(" + e + ")"); } if (!FOCUSED_WINDOW_PROPERTY.equals(e.getPropertyName())) { throw new IllegalArgumentException("unknown property name: " + e.getPropertyName()); } synchronized (myLock) { final Window window = (Window)e.getNewValue(); if (window == null || ApplicationManager.getApplication().isDisposed()) { return; } if (!windowToInfo.containsKey(window)) { windowToInfo.put(window, new WindowInfo(window, true)); } myFocusedWindow = window; final Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(myFocusedWindow)); for (Iterator<Window> i = myFocusedWindows.iterator(); i.hasNext(); ) { final Window w = i.next(); final DataContext dataContext = DataManager.getInstance().getDataContext(w); if (project == CommonDataKeys.PROJECT.getData(dataContext)) { i.remove(); } } myFocusedWindows.add(myFocusedWindow); // Set new root frame JFrame frame; if (window instanceof JFrame) { frame = (JFrame)window; } else { frame = (JFrame)SwingUtilities.getAncestorOfClass(IdeFrameImpl.class, window); } if (frame != null) { JOptionPane.setRootFrame(frame); } } if (LOG.isDebugEnabled()) { LOG.debug("exit: propertyChange()"); } } void dispatchComponentEvent(final ComponentEvent e) { int id = e.getID(); if (WindowEvent.WINDOW_CLOSED == id || (ComponentEvent.COMPONENT_HIDDEN == id && e.getSource() instanceof Window)) { dispatchHiddenOrClosed((Window)e.getSource()); } // clear obsolete reference on root frame if (WindowEvent.WINDOW_CLOSED == id) { Window window = (Window)e.getSource(); if (JOptionPane.getRootFrame() == window) { JOptionPane.setRootFrame(null); } } } private void dispatchHiddenOrClosed(final Window window) { if (LOG.isDebugEnabled()) { LOG.debug("enter: dispatchClosed(" + window + ")"); } synchronized (myLock) { WindowInfo info = window == null ? null : windowToInfo.get(window); if (info != null) { final FocusWatcher focusWatcher = info.myFocusWatcherRef.get(); if (focusWatcher != null) { focusWatcher.deinstall(window); } windowToInfo.remove(window); } } // Now, we have to recalculate focused window if currently focused // window is being closed. if (myFocusedWindow == window) { if (LOG.isDebugEnabled()) { LOG.debug("currently active window should be closed"); } myFocusedWindow = myFocusedWindow.getOwner(); if (LOG.isDebugEnabled()) { LOG.debug("new active window is " + myFocusedWindow); } } for (Iterator<Window> i = myFocusedWindows.iterator(); i.hasNext(); ) { Window activeWindow = i.next(); if (activeWindow == window) { final Window newActiveWindow = activeWindow.getOwner(); i.remove(); if (newActiveWindow != null) { myFocusedWindows.add(newActiveWindow); } break; } } // Remove invalid infos for garbage collected windows for (Iterator<WindowInfo> i = windowToInfo.values().iterator(); i.hasNext(); ) { final WindowInfo info = i.next(); if (info.myFocusWatcherRef.get() == null) { if (LOG.isDebugEnabled()) { LOG.debug("remove collected info"); } i.remove(); } } } public @Nullable Window getFocusedWindow() { synchronized (myLock) { return myFocusedWindow; } } public @Nullable Component getFocusedComponent(@Nullable Project project) { synchronized (myLock) { Window window = getFocusedWindowForProject(project); if (window == null) { return null; } return getFocusedComponent(window); } } public @Nullable Component getFocusedComponent(@NotNull Window window) { synchronized (myLock) { WindowInfo info = windowToInfo.get(window); if (info == null) { // it means that we don't manage this window, so just return standard focus owner // return window.getFocusOwner(); // TODO[vova,anton] usage of getMostRecentFocusOwner is experimental. But it seems suitable here. return window.getMostRecentFocusOwner(); } FocusWatcher focusWatcher = info.myFocusWatcherRef.get(); if (focusWatcher != null) { final Component focusedComponent = focusWatcher.getFocusedComponent(); if (focusedComponent != null && focusedComponent.isShowing()) { return focusedComponent; } else { return window == KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow() ? window : null; } } else { // info isn't valid, i.e. window was garbage collected, so we need the remove invalid info // and return null windowToInfo.remove(window); return null; } } } public @Nullable FocusWatcher getFocusWatcherFor(Component c) { final Window window = SwingUtilities.getWindowAncestor(c); final WindowInfo info = window == null ? null : windowToInfo.get(window); return info == null ? null : info.myFocusWatcherRef.get(); } /** * @param project may be null (for example, if no projects are opened) */ public @Nullable Window suggestParentWindow(@Nullable Project project, @NotNull WindowManagerEx windowManager) { synchronized (myLock) { Window window = getFocusedWindowForProject(project); if (window == null) { if (project == null) { Project[] projects = ProjectUtil.getOpenProjects(); if (projects.length == 1) { project = projects[0]; } } if (project == null) { return null; } else { IdeFrame frame = windowManager.findFrameFor(project); if (frame == null) { return null; } else if (frame instanceof Window) { return (Window)frame; } else { return ((ProjectFrameHelper)frame).getFrame(); } } } LOG.assertTrue(window.isDisplayable()); LOG.assertTrue(window.isShowing()); while (window != null) { // skip not visible and disposed/not shown windows if (!window.isDisplayable() || !window.isShowing()) { window = window.getOwner(); continue; } // skip windows that have not associated WindowInfo final WindowInfo info = windowToInfo.get(window); if (info == null) { window = window.getOwner(); continue; } if (info.mySuggestAsParent) { return window; } else { window = window.getOwner(); } } return null; } } public boolean isNotSuggestAsParent(@NotNull Window window) { synchronized (myLock) { WindowInfo info = windowToInfo.get(window); return info != null && !info.mySuggestAsParent; } } public void doNotSuggestAsParent(@NotNull Window window) { if (LOG.isDebugEnabled()) { LOG.debug("enter: doNotSuggestAsParent(" + window + ")"); } synchronized (myLock) { final WindowInfo info = windowToInfo.get(window); if (info == null) { windowToInfo.put(window, new WindowInfo(window, false)); } else { info.mySuggestAsParent = false; } } } /** * @return active window for specified {@code project}. There is only one window * for project can be at any point of time. */ private @Nullable Window getFocusedWindowForProject(final @Nullable Project project) { //todo[anton,vova]: it is possible that returned wnd is not contained in myFocusedWindows; investigate outer: for (Window window : myFocusedWindows) { while (!window.isDisplayable() || !window.isShowing()) { // if window isn't visible then gets its first visible ancestor window = window.getOwner(); if (window == null) { continue outer; } } final DataContext dataContext = DataManager.getInstance().getDataContext(window); if (project == CommonDataKeys.PROJECT.getData(dataContext)) { return window; } } return null; } private static final class WindowInfo { final WeakReference<FocusWatcher> myFocusWatcherRef; boolean mySuggestAsParent; WindowInfo(final Window window, final boolean suggestAsParent) { final FocusWatcher focusWatcher = new FocusWatcher(); focusWatcher.install(window); myFocusWatcherRef = new WeakReference<>(focusWatcher); mySuggestAsParent = suggestAsParent; } } }
true
1bc8de431f3f50fd395c9a3a7ae12db6bf7d9624
Java
patryk35/KorkoAndoridApp
/app/src/main/java/com/example/patryk/korko/containers/BoxesContainer.java
UTF-8
1,302
3.234375
3
[]
no_license
package com.example.patryk.korko.containers; import java.util.ArrayList; import java.util.List; /** * Created by Patryk on 2017-04-24. */ public class BoxesContainer { List<String> name; List<Boolean> value; public BoxesContainer() { name = new ArrayList<>(); value = new ArrayList<>(); } public void add(String name, boolean value) { this.name.add(name); this.value.add(value); } public boolean getValue(String name) { int n = this.name.indexOf(name); return value.get(n); } public String getName(int i) { return name.get(i); } public boolean getValue(int i) { return value.get(i); } @Override public boolean equals(Object o){ if(o instanceof BoxesContainer){ BoxesContainer b = (BoxesContainer) o; for(int i = 0; i < this.name.size() ; i++){ if(!((this.name.get(i)).equals(b.getName(i)))) return false; } for(int i = 0; i < this.value.size() ; i++){ if(!((this.value.get(i)).equals(b.getValue(i)))) return false; } return true; } return false; } }
true
7cbbaa848a51ac9e70816a98fd98dd4c94d4274d
Java
xSegFaultx/Photos
/Photos91/src/controller/userPListController.java
UTF-8
29,458
2.484375
2
[]
no_license
package controller; import java.util.*; import java.nio.file.*; import java.io.*; import java.text.SimpleDateFormat; import model.album; import model.albumList; import model.userlist; import model.imgR; import model.tag; import model.taglist; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.layout.AnchorPane; import javafx.scene.paint.Color; import javafx.stage.FileChooser; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.util.Duration; import javafx.scene.control.ListCell; import javafx.scene.image.Image; import javafx.scene.image.ImageView; /** * controls the view of the list of photos * @author Ran Sa, Jami Nicastro * */ public class userPListController{ @FXML private ListView<imgR> listView; @FXML private ListView<tag> tagList; @FXML private ComboBox<album> selectAB; @FXML private Label nameInfo; @FXML private Label logInfo; @FXML private Label captionInfo; @FXML private Label ADDStatus; @FXML private Label dateInfo; @FXML private Label capStatus; @FXML private Label tagStatus; @FXML private TextField captionField; @FXML private TextField catField; @FXML private TextField valueField; private ObservableList<imgR> obsList; private ObservableList<tag> obstagList; private ObservableList<album> option; private userlist ul; private Stage pstage; private albumList al; private album ab; private int index; /** * start the GUI and the controller by filling the following data * @param mainstage the stage it is on * @param us a list of all users * @param as an albumlist of this user * @param a an album of this user you want to diplay * @param index the index of the user in the userlist */ public void start(Stage mainstage,userlist us,albumList as,album a,int index){ pstage = mainstage; al = as; ab=a; this.index = index; ul = us; al = us.getUser(index).getAlbumList(); String userName = us.getUser(index).getName(); // create an ObservableList from an ArrayList obsList = FXCollections.observableArrayList(ab.getList()); listView.setItems(obsList); option = FXCollections.observableArrayList(al.getList()); selectAB.setItems(option); this.updateImage(); //check if the list contains any album if(ab.getSize()>0){ //if the list is not empty //select the first item listView.getSelectionModel().select(0); nameInfo.setText(listView.getItems().get(0).getName()); dateInfo.setText(listView.getItems().get(0).getDate()); captionInfo.setText(listView.getItems().get(0).getCap()); captionField.setText(listView.getItems().get(0).getCap()); if(listView.getItems().get(0).getList().getList().size()<=0){ tagList.setPlaceholder(new Label("No Content In List")); }else{ obstagList = FXCollections.observableArrayList(listView.getItems().get(0).getList().getList()); tagList.setItems(obstagList); tagList.refresh(); tagList.getSelectionModel().select(0); } }else{ //if the list is empty nameInfo.setText(""); captionInfo.setText(""); dateInfo.setText(""); captionField.setText(""); tagList.setPlaceholder(new Label("No Content In List")); } //set all status bar to default ADDStatus.setText(""); //set login user name logInfo.setText(userName); //add listener for the list listView.getSelectionModel().selectedIndexProperty().addListener((obs,oldV,newV)->showInfo(mainstage)); } /** * show the information of the selected image * @param mainStage the stage it is on */ private void showInfo(Stage mainStage){ int i = listView.getSelectionModel().getSelectedIndex(); if(i>=0){ nameInfo.setText(listView.getItems().get(i).getName()); dateInfo.setText(listView.getItems().get(i).getDate()); captionInfo.setText(listView.getItems().get(i).getCap()); captionField.setText(listView.getItems().get(i).getCap()); if(listView.getItems().get(i).getList().getSize()<=0){ ObservableList<tag> ept = FXCollections.observableArrayList(new ArrayList<tag>()); tagList.setItems(ept); }else{ obstagList = FXCollections.observableArrayList(listView.getItems().get(i).getList().getList()); tagList.setItems(obstagList); tagList.refresh(); tagList.getSelectionModel().select(0); } }else{ nameInfo.setText(""); dateInfo.setText(""); captionInfo.setText(""); ADDStatus.setText(""); captionField.setText(""); tagList.setPlaceholder(new Label("No Content In List")); tagList.refresh(); } } /** * An event handler to handle the move image event, move from one album to another * @param e the action that has been triggered * @throws Exception */ public void move(ActionEvent e)throws Exception{ int ai = selectAB.getSelectionModel().getSelectedIndex(); if(ab.getSize()<=0){ ADDStatus.setTextFill(Color.web("#ff0000")); ADDStatus.setText("Album is empty. No photo can be move"); //display the text for 3 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(3), evt -> ADDStatus.setText(""))); timeline.play(); }else if(ai<0){ ADDStatus.setTextFill(Color.web("#ff0000")); ADDStatus.setText("Plase choose an album to move to"); //display the text for 3 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(3), evt -> ADDStatus.setText(""))); timeline.play(); }else{ //if not empty set the alert window int i = listView.getSelectionModel().getSelectedIndex(); album tab = al.getList().get(ai); imgR tmp = ab.getList().get(i).clone(); //check if the photo already exist in the traget album for(int x =0; x<tab.getSize(); x++){ if(tab.getList().get(x).equals(tmp)){ ADDStatus.setTextFill(Color.web("#ff0000")); ADDStatus.setText("Photo already exist in traget album"); //display the text for 3 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(3), evt -> ADDStatus.setText(""))); timeline.play(); return; } } Alert dc = new Alert(AlertType.CONFIRMATION); dc.setTitle("Deletion Confirmation"); dc.setHeaderText("Are you sure you want to move the following photo?"); dc.setContentText("Photo Name: "+listView.getItems().get(i).getName()+"\n"+"Date: "+listView.getItems().get(i).getDate()+"\nThis photo will be removed from this album"); //set the button that user can choose ButtonType buttonTypeDelete = new ButtonType("Move", ButtonData.OK_DONE); ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE); dc.getButtonTypes().setAll(buttonTypeDelete,buttonTypeCancel); Optional<ButtonType> result = dc.showAndWait(); //select song after deletion if(result.get()==buttonTypeDelete){ tab.addP(tmp); int s; if(i==al.getSize()-1 && i!=0){ s = i-1; }else if(i==al.getSize()-1 && i==0){ s = -1; }else{ s = i; } ab.remove(i); //refresh listView obsList = FXCollections.observableArrayList(ab.getList()); listView.setItems(obsList); this.updateImage(); listView.refresh(); listView.getSelectionModel().select(s); //notice the user that their deletion is successful ADDStatus.setTextFill(Color.web("#32CD32")); ADDStatus.setText("Successfully Moved"); //display the text for 1.5 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1.5), evt -> ADDStatus.setText(""))); timeline.play(); } } } /** * An event handler to handle the add to pool event, add a image from system to the program * @param e the action that has been triggered */ public void addToPool(ActionEvent e){ FileChooser fileChooser = new FileChooser(); FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG"); FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG"); fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG); fileChooser.setTitle("Add Photo"); Stage cpstage = (Stage) ((Node) e.getSource()).getScene().getWindow(); File file = fileChooser.showOpenDialog(cpstage); if(file==null){ return; } Path src = file.toPath(); Path imgPath = Paths.get(ul.getUser(index).getPool()+"/"+file.getName()); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); String date = sdf.format(file.lastModified()); try{ Files.copy(src, imgPath); }catch(IOException ioe){ //file already exist NEED TO TELL USER TO RENAME ADDStatus.setTextFill(Color.web("#ff0000")); ADDStatus.setText("Failed to add Photo: Photo already exist"); Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(3), evt -> ADDStatus.setText(""))); timeline.play(); return; } imgR image = new imgR(file.getName(),date,imgPath); //add to album int result = ab.addP(image); obsList = FXCollections.observableArrayList(ab.getList()); listView.setItems(obsList); this.updateImage(); //select photo after addition listView.refresh(); listView.getSelectionModel().select(result); //notice the user that their addition is successful ADDStatus.setTextFill(Color.web("#32CD32")); ADDStatus.setText("Successfully Added"); //display the text for 1.5 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1.5), evt -> ADDStatus.setText(""))); timeline.play(); } /** * An event handler to handle the delete event, delete the photo reference if this is the last reference delete the physical photo from the pool * @param e the action that has been triggered */ public void delete(ActionEvent e){ //first delete from the album //check if the list is empty if(ab.getSize()<=0){ ADDStatus.setTextFill(Color.web("#ff0000")); ADDStatus.setText("Album is empty. No photo can be deleted."); //display the text for 3 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(3), evt -> ADDStatus.setText(""))); timeline.play(); }else{ //if not empty set the alert window int i = listView.getSelectionModel().getSelectedIndex(); Alert dc = new Alert(AlertType.CONFIRMATION); dc.setTitle("Deletion Confirmation"); dc.setHeaderText("Are you sure you want to delete the following photo?"); dc.setContentText("Photo Name: "+listView.getItems().get(i).getName()+"\n"+"Date: "+listView.getItems().get(i).getDate()); //set the button that user can choose ButtonType buttonTypeDelete = new ButtonType("Delete", ButtonData.OK_DONE); ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE); dc.getButtonTypes().setAll(buttonTypeDelete,buttonTypeCancel); Optional<ButtonType> result = dc.showAndWait(); //select song after deletion if(result.get()==buttonTypeDelete){ int s; if(i==al.getSize()-1 && i!=0){ s = i-1; }else if(i==al.getSize()-1 && i==0){ s = -1; }else{ s = i; } //check if this is the last reference point points to this photo, if yes delete from disk imgR tmp = ab.getList().get(i); int indicate = 0; for(int id=0; id<al.getSize();id++){ if(al.getList().get(id).getList().indexOf(tmp)>=0){ indicate++; } } if(indicate<=1){ //delete from disk try{ Files.delete(tmp.getPath()); }catch(NoSuchFileException x){ ab.remove(i); ADDStatus.setTextFill(Color.web("#ff0000")); ADDStatus.setText("No such file. Deleting the reference"); //display the text for 3 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(3), evt -> ADDStatus.setText(""))); timeline.play(); } catch (IOException e1) { ab.remove(i); ADDStatus.setTextFill(Color.web("#ff0000")); ADDStatus.setText("Fail to delete: Please manually delete from disk"); //display the text for 3 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(3), evt -> ADDStatus.setText(""))); timeline.play(); } } //delete from list ab.remove(i); //refresh listView obsList = FXCollections.observableArrayList(ab.getList()); listView.setItems(obsList); this.updateImage(); listView.refresh(); listView.getSelectionModel().select(s); //notice the user that their deletion is successful ADDStatus.setTextFill(Color.web("#32CD32")); ADDStatus.setText("Successfully Deleted"); //display the text for 1.5 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1.5), evt -> ADDStatus.setText(""))); timeline.play(); } } } /** * An event handler to handle the copy event, set the photo to copy * @param e the action that has been triggered */ public void copy(ActionEvent e){ //check if the list is empty if(ab.getSize()<=0){ ADDStatus.setTextFill(Color.web("#ff0000")); ADDStatus.setText("Album is empty. No photo can be copied."); //display the text for 3 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(3), evt -> ADDStatus.setText(""))); timeline.play(); }else{ //uncopy all the image for(int i=0; i<al.getSize(); i++){ for(int x = 0; x<al.getList().get(i).getSize(); x++){ al.getList().get(i).getList().get(x).setCopied(false); } } //if not empty set the alert window int i = listView.getSelectionModel().getSelectedIndex(); //set the selected on to copied ab.getList().get(i).setCopied(true); ADDStatus.setTextFill(Color.web("#32CD32")); ADDStatus.setText("Copied"); //display the text for 1.5 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1.5), evt -> ADDStatus.setText(""))); timeline.play(); } } /** * An event handler to handle the paste event, paste the copied photo to the target album * @param e the action that has been triggered */ public void paste(ActionEvent e){ //check if there is anything be copied imgR tmp = null; for(int i=0; i<al.getSize(); i++){ for(int x = 0; x<al.getList().get(i).getSize(); x++){ if(al.getList().get(i).getList().get(x).getCopied()){ try{ tmp = al.getList().get(i).getList().get(x).clone(); }catch(CloneNotSupportedException cns){ break; } break; } } } if(tmp==null){ ADDStatus.setTextFill(Color.web("#ff0000")); ADDStatus.setText("Nothing has been copied yet"); //display the text for 3 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(3), evt -> ADDStatus.setText(""))); timeline.play(); }else{ if(ab.getList().indexOf(tmp)>=0){ //photo already exist ADDStatus.setTextFill(Color.web("#ff0000")); ADDStatus.setText("Photo Already Exist"); //display the text for 3 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(3), evt -> ADDStatus.setText(""))); timeline.play(); }else{ int result = ab.addP(tmp); obsList = FXCollections.observableArrayList(ab.getList()); listView.setItems(obsList); this.updateImage(); //select photo after addition listView.refresh(); listView.getSelectionModel().select(result); //notice the user that their addition is successful ADDStatus.setTextFill(Color.web("#32CD32")); ADDStatus.setText("Successfully Pasted"); //display the text for 1.5 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1.5), evt -> ADDStatus.setText(""))); timeline.play(); } } } /** * An event handler to handle the save the caption event, save the caption to the photo * @param e the action that has been triggered */ public void saveC(ActionEvent e){ if(ab.getSize()<=0){ capStatus.setTextFill(Color.web("#ff0000")); capStatus.setText("Album is empty"); //display the text for 3 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(3), evt -> ADDStatus.setText(""))); timeline.play(); return; } //edit the caption int i = listView.getSelectionModel().getSelectedIndex(); String cap = captionField.getText(); int result = listView.getItems().get(i).setCaption(cap,false); if(result==-1){ capStatus.setTextFill(Color.web("#ff0000")); capStatus.setText("Caption cannot be Empty"); }else if(result==0){ capStatus.setTextFill(Color.web("#ff0000")); capStatus.setText("Nothing has Changed"); }else{ Alert ec = new Alert(AlertType.CONFIRMATION); ec.setTitle("Caption Confirmation"); ec.setHeaderText("Are you sure you want to save caption?"); //set the button that user can choose ButtonType buttonTypeRename = new ButtonType("Save", ButtonData.OK_DONE); ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE); ec.getButtonTypes().setAll(buttonTypeRename,buttonTypeCancel); Optional<ButtonType> r = ec.showAndWait(); if(r.get()==buttonTypeRename){ listView.getItems().get(i).setCaption(cap,true); obsList = FXCollections.observableArrayList(ab.getList()); listView.setItems(obsList); this.updateImage(); //select song after addition listView.refresh(); listView.getSelectionModel().select(result); //notice the user that their addition is successful capStatus.setTextFill(Color.web("#32CD32")); capStatus.setText("Successfully Edited"); //display the text for 1.5 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1.5), evt -> capStatus.setText(""))); timeline.play(); } } } /** * An event handler to handle the cancel save event, cancel the save caption * @param e the action that has been triggered */ public void cancelC(ActionEvent e){ if(ab.getSize()>0){ int i = listView.getSelectionModel().getSelectedIndex(); captionField.setText(listView.getItems().get(i).getCap()); } capStatus.setText(""); } /** * An event handler to handle the add tag event * @param e the action that has been triggered */ public void addTag(ActionEvent e){ //check the original selected album int o = listView.getSelectionModel().getSelectedIndex(); taglist tl = listView.getItems().get(o).getList(); String cat = catField.getText(); String value = valueField.getText(); int result = tl.add(cat, value,false); //check if the information user provided are valid if(result==-1){ tagStatus.setTextFill(Color.web("#ff0000")); tagStatus.setText("Tag already exist"); }else if(result==0){ tagStatus.setTextFill(Color.web("#ff0000")); tagStatus.setText("None of category or value can be empty"); }else{ Alert ac = new Alert(AlertType.CONFIRMATION); ac.setTitle("Add Tag Confirmation"); ac.setHeaderText("Are you sure you want to add the following tag to your photo?"); ac.setContentText("Tag Category: "+cat+"\nTag Value: "+value); //set the button that user can choose ButtonType buttonTypeAdd = new ButtonType("Add", ButtonData.OK_DONE); ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE); ac.getButtonTypes().setAll(buttonTypeAdd,buttonTypeCancel); Optional<ButtonType> r = ac.showAndWait(); if(r.get()==buttonTypeAdd){ result = tl.add(cat, value,true); obstagList = FXCollections.observableArrayList(listView.getItems().get(o).getList().getList()); tagList.setItems(obstagList); tagList.refresh(); //select album after addition tagList.getSelectionModel().select(result); //set text field to empty catField.setText(""); valueField.setText(""); //notice the user that their addition is successful tagStatus.setTextFill(Color.web("#32CD32")); tagStatus.setText("Successfully Added"); //display the text for 1.5 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1.5), evt -> tagStatus.setText(""))); timeline.play(); } } } /** * An event handler to handle the delete tag event * @param e the action that has been triggered */ public void deleteTag(ActionEvent e){ int o = listView.getSelectionModel().getSelectedIndex(); taglist tl = listView.getItems().get(o).getList(); //check if the list is empty if(tl.getSize()<=0){ tagStatus.setTextFill(Color.web("#ff0000")); tagStatus.setText("No tag can be deleted."); //display the text for 3 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(3), evt -> tagStatus.setText(""))); timeline.play(); }else{ //if not empty set the alert window int i = tagList.getSelectionModel().getSelectedIndex(); Alert dc = new Alert(AlertType.CONFIRMATION); dc.setTitle("Deletion Confirmation"); dc.setHeaderText("Are you sure you want to delete the following tag?"); dc.setContentText("Category: "+tl.getList().get(i).getCat()+"\nValue: "+tl.getList().get(i).getValue()); //set the button that user can choose ButtonType buttonTypeDelete = new ButtonType("Delete", ButtonData.OK_DONE); ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE); dc.getButtonTypes().setAll(buttonTypeDelete,buttonTypeCancel); Optional<ButtonType> result = dc.showAndWait(); //select song after deletion if(result.get()==buttonTypeDelete){ int s; if(i==tl.getSize()-1 && i!=0){ s = i-1; }else if(i==tl.getSize()-1 && i==0){ s = -1; }else{ s = i; } //delete from list tl.remove(i); //refresh listView obstagList = FXCollections.observableArrayList(listView.getItems().get(o).getList().getList()); tagList.setItems(obstagList); tagList.refresh(); //select album after addition tagList.getSelectionModel().select(s); //notice the user that their addition is successful tagStatus.setTextFill(Color.web("#32CD32")); tagStatus.setText("Successfully Deleted"); //display the text for 1.5 seconds Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1.5), evt -> tagStatus.setText(""))); timeline.play(); } } } /** * An event handler to handle the view album event, open up a new window to view the photo * @param e the action that has been triggered * @throws Exception */ public void view(ActionEvent e)throws Exception{ //check if the list is empty if(ab.getSize()<=0){ ADDStatus.setTextFill(Color.web("#ff0000")); ADDStatus.setText("Nothing can be viewed"); Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(3), evt -> ADDStatus.setText(""))); timeline.play(); return; } FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/view/photoView.fxml")); // initializing the controller AnchorPane root = (AnchorPane)loader.load(); photoViewController pvc = loader.getController(); pvc.start(ab,listView.getSelectionModel().getSelectedIndex()); Scene scene = new Scene(root); // this is the popup stage Stage popupStage = new Stage(); pvc.setStage(popupStage); // Giving the popup controller access to the popup stage (to allow the controller to close the stage) popupStage.initOwner(pstage); popupStage.initModality(Modality.WINDOW_MODAL); popupStage.setTitle("Photos-Search"); popupStage.setScene(scene); popupStage.setResizable(false); popupStage.showAndWait(); } /** * An event handler to handle the search event, open up a new window for search * @param e the action that has been triggered * @throws Exception */ public void search(ActionEvent e)throws Exception{ //check if the list is empty if(ab.getSize()<=0){ ADDStatus.setTextFill(Color.web("#ff0000")); ADDStatus.setText("Nothing can be searched"); Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(3), evt -> ADDStatus.setText(""))); timeline.play(); return; } FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/view/searchView.fxml")); // initializing the controller AnchorPane root = (AnchorPane)loader.load(); searchViewController svc = loader.getController(); Scene scene = new Scene(root); // this is the popup stage Stage popupStage = new Stage(); svc.start(popupStage,al); // Giving the popup controller access to the popup stage (to allow the controller to close the stage) popupStage.initOwner(pstage); popupStage.initModality(Modality.WINDOW_MODAL); popupStage.setTitle("Photos-Search"); popupStage.setScene(scene); popupStage.setResizable(false); popupStage.showAndWait(); } /** * An event handler to handle the back event, switch back to the prev windows * @param e the action that has been triggered * @throws Exception */ public void back(ActionEvent e)throws Exception{ FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/view/usersubAlbum.fxml")); AnchorPane root = (AnchorPane)loader.load(); userAlbumController uac = loader.getController(); uac.start(pstage,ul,index); uac.setSelect(ab); Scene scene = new Scene(root); pstage.setScene(scene); pstage.setTitle("Photos-UserSystem"); pstage.setResizable(false); pstage.show(); } /** * An event handler to handle the log out event * @param e the action that has been triggered * @throws Exception */ public void logout(ActionEvent e) throws Exception{ //set the alert window Alert dc = new Alert(AlertType.CONFIRMATION); dc.setTitle("Logout Confirmation"); dc.setHeaderText("Are you sure you want to logout?\nAll the changes will be saved."); //set the button that user can choose ButtonType buttonTypeLogout = new ButtonType("Logout", ButtonData.OK_DONE); ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE); dc.getButtonTypes().setAll(buttonTypeLogout,buttonTypeCancel); Optional<ButtonType> result = dc.showAndWait(); if(result.get()==buttonTypeLogout){ try{ userlist.writeData(ul); }catch(IOException ioe){ //set error alert Alert er = new Alert(AlertType.ERROR); er.setTitle("Error"); er.setHeaderText("Fail to save changes"); er.setContentText("An error occured when the program tried to save the changes\nPlease try logout again\nIf you have encountered this error multiple times, please try exit"); er.showAndWait(); return; } FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/view/login.fxml")); AnchorPane root = (AnchorPane)loader.load(); loginController log = loader.getController(); log.start(pstage); Scene scene = new Scene(root); pstage.setScene(scene); pstage.setTitle("Photos-Login"); pstage.setResizable(false); pstage.show(); } } /** * An event handler to handle the exit event * @param e the action that has been triggered */ public void exit(ActionEvent e){ //set the alert window Alert dc = new Alert(AlertType.CONFIRMATION); dc.setTitle("Exit Confirmation"); dc.setHeaderText("Are you sure you want to exit?\nAll the changes will be saved."); //set the button that user can choose ButtonType buttonTypeExit = new ButtonType("Exit", ButtonData.OK_DONE); ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE); dc.getButtonTypes().setAll(buttonTypeExit,buttonTypeCancel); Optional<ButtonType> result = dc.showAndWait(); if(result.get()==buttonTypeExit){ try{ userlist.writeData(ul); }catch(IOException ioe){ //set error alert Alert er = new Alert(AlertType.CONFIRMATION); er.setTitle("Error"); er.setHeaderText("Fail to save changes"); er.setContentText("An error occured when the program tried to save the changes\nPlease try exit again\nIf you have encountered this error multiple times or you fail to logout multiple times\n" + "please try Force exit and all the changes will not be safed"); ButtonType buttonTypeFExit = new ButtonType("FORCE Exit", ButtonData.OK_DONE); ButtonType buttonTypeRetry = new ButtonType("Retry", ButtonData.CANCEL_CLOSE); er.getButtonTypes().setAll(buttonTypeFExit,buttonTypeCancel); Optional<ButtonType> re = er.showAndWait(); if(re.get()==buttonTypeRetry){ return; }else if(re.get()==buttonTypeFExit){ System.exit(0); } } System.exit(0); } } /** * update the list with thumbnail on the left */ private void updateImage(){ listView.setCellFactory(param -> new ListCell<imgR>(){ private ImageView imageView = new ImageView(); @Override public void updateItem(imgR img, boolean empty) { super.updateItem(img, empty); if (empty) { setText(null); setGraphic(null); } else { try{ FileInputStream input = new FileInputStream(img.getPath().toString()); Image image = new Image(input); imageView.setFitHeight(100); imageView.setFitWidth(100); imageView.setImage(image); input.close(); }catch(IOException ioe){ setGraphic(null); }finally{ setText(img.getName()); } setGraphic(imageView); } } }); } }
true
0ad201fefac3ae8af4cfde677c4cca32b7bf7f44
Java
sztony/newsellinggas
/src/main/java/com/aote/rs/charge/enddate/IEndDate.java
GB18030
315
1.78125
2
[]
no_license
package com.aote.rs.charge.enddate; import java.util.Calendar; import org.springframework.orm.hibernate3.HibernateTemplate; /** * 㳭ѽֹ * @author Administrator * */ public interface IEndDate { Calendar enddate(String userid,HibernateTemplate hibernateTemplate); }
true
17f226648f2ded293159c9ac5845f8e704d68211
Java
ThirdIInc/Third-I-Portal
/hrsaas/src/org/struts/action/vendor/VendorRegistrationAction.java
UTF-8
8,968
1.9375
2
[ "Apache-2.0" ]
permissive
package org.struts.action.vendor; /** @ Author : Archana Salunkhe * @ purpose : Developed for Vendor Registration * @ Date : 08-May-2012 */ import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Map; import javax.imageio.ImageIO; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import org.apache.struts2.util.ServletContextAware; import org.paradyne.bean.vendor.VendorLogin; import org.paradyne.lib.MyCaptchaService; import org.paradyne.lib.StringEncrypter; import org.paradyne.model.vendor.VendorRegistrationModel; import com.octo.captcha.service.CaptchaServiceException; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.Preparable; public class VendorRegistrationAction extends ActionSupport implements ModelDriven, Preparable, ServletRequestAware, ServletResponseAware, ServletContextAware { public ActionContext actionContext = ActionContext.getContext(); public HttpServletRequest request; public HttpServletResponse response; public ServletContext context; private static final long serialVersionUID = 1L; String sImgType = "png"; VendorLogin vendorBean; public void prepare() throws Exception { vendorBean =new VendorLogin(); } public Object getModel() { return vendorBean; } public VendorLogin getVendorBean() { return vendorBean; } public void setVendorBean(VendorLogin vendorBean) { this.vendorBean = vendorBean; } public void setServletRequest(HttpServletRequest httpservletrequest) { this.request = httpservletrequest; } public void setServletResponse(HttpServletResponse httpservletresponse) { this.response= httpservletresponse; } public void setServletContext(ServletContext servletContext) { this.context = servletContext; } public ServletContext getServletContext() { return context; } public String input() { String poolName = ""; try { poolName = new StringEncrypter( StringEncrypter.DESEDE_ENCRYPTION_SCHEME, StringEncrypter.URL_ENCRYPTION_KEY).decrypt(vendorBean .getInfoId()); HttpSession session = request.getSession(); session.setAttribute("session_pool", poolName); VendorRegistrationModel model = new VendorRegistrationModel(); model.initiate(context, session); Object[][] logo = null; logo = model.getComponyLogo(); request.setAttribute("logo", String.valueOf(logo[0][0])); request.setAttribute("comanyName", String.valueOf(logo[0][1])); } catch (Exception e) { e.printStackTrace(); } return INPUT; } /** * following function is used to display the characters. * @return * @throws Exception */ public void getKeyCode() throws Exception { try { getImage(request, response); } catch (Exception e) { e.printStackTrace(); } } /** * following function is called to display the characters in the jsp page. * @param request,response * @throws ServletException,IOException */ public void getImage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream(); byte[] captchaBytes; if (request.getQueryString() != null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "GET request should have no query string."); return; } try { // Session ID is used to identify the particular captcha. String captchaId = request.getSession().getId(); // Generate the captcha image. BufferedImage challengeImage = MyCaptchaService.getInstance() .getImageChallengeForID(captchaId, request.getLocale()); ImageIO.write(challengeImage, sImgType, imgOutputStream); captchaBytes = imgOutputStream.toByteArray(); // Clear any existing flag. request.getSession().removeAttribute("PassedCaptcha"); } catch (CaptchaServiceException cse) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem generating captcha image."); return; } catch (IOException ioe) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem generating captcha image."); return; } // Set appropriate http headers. response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/" + (sImgType.equalsIgnoreCase("png") ? "png" : "jpeg")); // Write the image to the client. ServletOutputStream outStream = response.getOutputStream(); outStream.write(captchaBytes); outStream.flush(); outStream.close(); } public String reset() { try { VendorRegistrationModel model = new VendorRegistrationModel(); HttpSession session = request.getSession(); model.initiate(context, session); Object[][] logo = null; logo = model.getComponyLogo(); request.setAttribute("logo", String.valueOf(logo[0][0])); request.setAttribute("comanyName", String.valueOf(logo[0][1])); vendorBean.setPartnerName(""); vendorBean.setEmailId(""); vendorBean.setPartnerCode(""); vendorBean.setLoginName(""); } catch (Exception e) { e.printStackTrace(); } return SUCCESS; } /** * following function is called when the Submit button is clicked * @return */ public String save() { String message = ""; try { VendorRegistrationModel model = new VendorRegistrationModel(); HttpSession session = request.getSession(); model.initiate(context, session); boolean result = false; Object[][] logo = null; logo = model.getComponyLogo(); request.setAttribute("logo", String.valueOf(logo[0][0])); request.setAttribute("comanyName", String.valueOf(logo[0][1])); boolean res = checkKeyCode(request, response); if (!res) { addActionMessage("The entered characters and the characters appearing in the image below are not same."); message= "success"; } else { result = model.saveData(vendorBean, request); if (result) { vendorBean.setSubmitFlag("true"); } } model.terminate(); } catch (Exception e) { e.printStackTrace(); } return SUCCESS; } /** * following function is called to check whether the characters appearing in the image * and the typed characters are same or not. * @param request, response * @throws ServletException,IOException */ protected boolean checkKeyCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean passedCaptchaTest = false; try { Map paramMap = request.getParameterMap(); if (paramMap.isEmpty()) { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Post method not allowed without parameters."); return false; } String[] arr1 = (String[]) paramMap.get("hidCaptchaID"); String[] arr2 = (String[]) paramMap.get("inCaptchaChars"); if (arr1 == null || arr2 == null) { response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Expected parameters were not found."); return false; } String sessId = request.getSession().getId(); String incomingCaptchaId = arr1.length > 0 ? arr1[0] : ""; String inputChars = arr2.length > 0 ? arr2[0] : ""; // Check validity and consistency of the data. if (sessId == null || incomingCaptchaId == null || !sessId.equals(incomingCaptchaId)) { response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Browser must support session cookies."); return false; } // Validate whether input from user is correct. passedCaptchaTest = validateCaptcha(incomingCaptchaId, inputChars); // Set flag into session. request.getSession().setAttribute("PassedCaptcha", new Boolean(passedCaptchaTest)); } catch (Exception e) { e.printStackTrace(); } return passedCaptchaTest; } /** Following method checks the input characters and the * the characters those appears in the image. * @param captchaId, inputChars * @ return boolean */ private boolean validateCaptcha(String captchaId, String inputChars) { boolean bValidated = false; try { bValidated = MyCaptchaService.getInstance().validateResponseForID( captchaId, inputChars); } catch (CaptchaServiceException cse) { cse.printStackTrace(); } return bValidated; } }
true
395ef4f2cc5af87744f7c8ba8d80c68d94e373cd
Java
0niconico0/TestTool2
/TestTool2/src/orgin/regex.java
UTF-8
168
2.0625
2
[]
no_license
package orgin; public class regex { public static void main(String args[]){ float result = (float) 1/3; System.out.println(Math.round(result)); } }
true
8238b0ba4f4bb82e4623420a136b3dd06b9af12b
Java
uca-m1informatique-softeng/s2-gestiondeprojet-jokr
/java/moteur/src/main/java/sw_aventure/seven_wonders/DeroulementJeu.java
UTF-8
11,807
2.71875
3
[]
no_license
package sw_aventure.seven_wonders; import objet_commun.Carte; import exception.NegativeNumberException; import sw_aventure.objetjeu.*; import metier.EnumRessources; import utilitaire_jeu.Inventaire; import utilitaire_jeu.Plateau; import utilitaire_jeu.SetInventaire; import utils.affichage.Colors; import utils.affichage.LoggerSevenWonders; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * toutes les étapes du jeu guerres ages etc... */ public class DeroulementJeu { private final List<SetInventaire> inv; private final ArrayList<Carte> paquetDefausse = new ArrayList<>(); private List<MainJoueur> mainJoueurs = new ArrayList<>(); private final SecureRandom r = new SecureRandom(); private MoteurWebController webController; public DeroulementJeu(MoteurWebController webController, List<SetInventaire> inv){ this.inv = inv; this.webController = webController; } /** * Initialise la List "mainJoueur" en fonction du nombre de joueur * @param nbJoueurs le nombre de joueur */ public void initMainJoueur(int nbJoueurs) { mainJoueurs = new ArrayList<>(); for (int i = 0; i < nbJoueurs; i++) { mainJoueurs.add(new MainJoueur()); } } /** * Set la graine du SecureRandom à une valeur fixe * @param mySeed la valeur initiale auquel on préfixe le SecureRandom */ public void setTheSeed( int mySeed ) { r.nextBytes(new byte[8]); r.setSeed(mySeed); } /** * Méthode qui renvoie le joueur gagnant avec son nombre de points * @param nbjoueurs le nombre de joueur * @param plateau le plateau de jeu */ public String gagnante(int nbjoueurs, Plateau plateau) { int[] liste = new int[nbjoueurs]; List<Inventaire> joueurs = plateau.getListeInventaire(); for(int i = 0 ; i<nbjoueurs ; i++){ for (SetInventaire s : inv) { if(s.getId()==i){ liste[s.getId()] = s.compteFinalScore(plateau.joueurGauche(s),plateau.joueurDroit(s), false); joueurs.add(s); } } } return decisionGagnant(liste,joueurs); } /** * Décide de qui est le gagnant en fonction des points et des pièces, en cas d'égalité renvoie un au hasard * @param liste tableau de joueurs * @param joueurs liste des joueurs */ public String decisionGagnant(int[] liste , List<Inventaire> joueurs ){ int max = 0; int piece = 0; Inventaire unJoueur = null; ArrayList<Inventaire> gagnant = new ArrayList<>(); for (int i = 0; i < liste.length; i++) { for(Inventaire j : joueurs){ if(j.getId() == i){ unJoueur = j; break; } } if (liste[i] > max) { max = liste[i]; piece = unJoueur.getValue(EnumRessources.PIECE); gagnant.clear(); gagnant.add(unJoueur); }else if(liste[i] == max && unJoueur.getValue(EnumRessources.PIECE)>piece) { piece = unJoueur.getValue(EnumRessources.PIECE); gagnant.clear(); gagnant.add(unJoueur); }else if(liste[i] == max && unJoueur.getValue(EnumRessources.PIECE)==piece) { gagnant.add(unJoueur); } } int rand = r.nextInt(gagnant.size()); LoggerSevenWonders.ajoutln(Colors.gJaune("Le Vainqueur est ") + gagnant.get(rand).getJoueurName() + Colors.gJaune(" avec " + max + " points !!!")); for (SetInventaire s : inv) { if (s.getUrl().equals(gagnant.get(rand).getUrl())) s.getSac().put(EnumRessources.VICTOIRETOTAL, 1); else s.getSac().put(EnumRessources.VICTOIRETOTAL, 0); } return gagnant.get(rand).getJoueurName(); } /** * @return toutes les mains des joueurs */ public List<MainJoueur> getMainJoueurs() { return mainJoueurs; } /** * @return la liste des setInventaire */ public List<SetInventaire> getSetInventaire() { return inv; } /** * Méthode qui permet de distribuer les cartes * @param paquetCarte le paquet à distribuer */ public void distribution(List<Carte> paquetCarte) { Collections.shuffle(paquetCarte); Collections.shuffle(paquetCarte); //Collections.shuffle(paquetCarte,new Random(146)); for (int i = 6; i >= 0; i--) { for (MainJoueur main : mainJoueurs) { main.add(paquetCarte.get(0)); paquetCarte.remove(0); } } } /** * Echange la main des joueurs : * On décale d'un index toute les mains dans la List "mainJoueur". * Pour ce faire on supprime le dernier élément de la liste puis * on le rajoute en début de liste. * @param age l'age actuel */ public void echangerMain(int age) { if (age == 2) { MainJoueur temp = mainJoueurs.remove(0); mainJoueurs.add(temp); } else{ MainJoueur temp = mainJoueurs.remove(mainJoueurs.size() - 1); mainJoueurs.add(0, temp); } for (int i = 0; i < inv.size(); i++) { if (age == 2) LoggerSevenWonders.ajoutln(inv.get((i+1)%inv.size()).getJoueurName() + " donne ses cartes à " + inv.get(i).getJoueurName()); else LoggerSevenWonders.ajoutln(inv.get(i).getJoueurName() + " donne ses cartes à " + inv.get((i + 1) % inv.size()).getJoueurName()); } } /** * Méthode permettant de lancer un Age en fonction du nombre de joueur * @param age l'age actuel * @param nbJoueurs le nombre de joueur * @param plateau le plateau de jeu */ public void joueAge(int age, int nbJoueurs, Plateau plateau) throws NegativeNumberException { plateau.restartTour(); ActionDeJeu action = new ActionDeJeu(webController,inv,mainJoueurs,paquetDefausse); for (int carteParMains = 7 ;carteParMains > 1 ; carteParMains--) { int tour = 7 - carteParMains+1 ; LoggerSevenWonders.ajoutln(Colors.gBleu("\n--------------------- DEBUT TOUR N°" + tour + " ---------------------\n")); plateau.incrementeTour(); int[][] choix = action.decisionDeJeu(nbJoueurs,plateau); for (int j = nbJoueurs-1; j>=0; j--) { int i = nbJoueurs-1-j; SetInventaire s = inv.get(i); if (choix[i][0] != 1) { // si il ne veut pas construire sa merveille // jouer ou défausser une carte Carte choixCarte = mainJoueurs.get(s.getId()).getMain().get(choix[i][1]); if (choix[i][0]==3) { // défausser s.casDefausse(); paquetDefausse.add(choixCarte); } else { // jouer une carte s.afficheChoixCarte(choixCarte); action.basicConstruire(choixCarte, s, plateau); } mainJoueurs.get(s.getId()).getMain().remove(choix[i][1]); // retirer la carte de la main } } ///////////// SI QUELQU'UN PEUT JOUER UNE CARTE DE LA DEFAUSSE /////////////// action.jouerLaDefausse(nbJoueurs, plateau); LoggerSevenWonders.ajoutln(Colors.gBleu("--------------------- FIN TOUR N°" + tour + " ---------------------\n")); if (tour < 6) echangerMain(age); } ///////////// SI QUELQU'UN PEUT JOUER SA 7ème CARTE /////////////// action.jouerLa7emeCarte(nbJoueurs, plateau); } /** * Méthode permettant de déclarer une guerre en fonction de l'époque (AGE) * @param age l'age actuel */ public void guerre(int age) { LoggerSevenWonders.ajoutln(Colors.gRouge("##################### La GUERRE n°"+age+" est déclarée ######################\n")); int reward; if(age==1) { reward = 1; } else if(age==2) { reward = 3; } else{ reward = 5; } for (int i = 0; i < inv.size(); i++) { LoggerSevenWonders.ajoutln(inv.get(i).getJoueurName() + " ("+ inv.get(i).getValue(EnumRessources.BOUCLIER) + " Boucliers) a engagé le combat contre " + inv.get((i + 1) % inv.size()).getJoueurName() +" (" + inv.get((i + 1) % inv.size()).getValue(EnumRessources.BOUCLIER)+" Boucliers)."); if(inv.get(i).getValue(EnumRessources.BOUCLIER) > inv.get((i + 1) % inv.size()).getValue(EnumRessources.BOUCLIER)){ LoggerSevenWonders.ajoutln(inv.get(i).getJoueurName() + " gagne la bataille et remporte " + reward + " Pts de Victoire."); LoggerSevenWonders.ajoutln(inv.get((i + 1) % inv.size()).getJoueurName() + " perd et remporte 1 Pts de Défaite\n"); inv.get(i).increaseValue(EnumRessources.VICTOIRE, reward); inv.get((i + 1) % inv.size()).increaseValue(EnumRessources.DEFAITE, 1); } else if(inv.get(i).getValue(EnumRessources.BOUCLIER) < inv.get((i + 1) % inv.size()).getValue(EnumRessources.BOUCLIER)){ LoggerSevenWonders.ajoutln(inv.get((i + 1) % inv.size()).getJoueurName() + " gagne la bataille et remporte " + reward + " Pts de Victoire."); LoggerSevenWonders.ajoutln(inv.get(i).getJoueurName() + " perd et remporte 1 Pts de Défaite.\n"); inv.get((i + 1) % inv.size()).increaseValue(EnumRessources.VICTOIRE, reward); inv.get(i).increaseValue(EnumRessources.DEFAITE, 1); } else{ LoggerSevenWonders.ajoutln("Egalité des Boucliers, personne ne gagne.\n"); } } LoggerSevenWonders.ajoutln(Colors.gRouge("##################### Fin de la GUERRE n°"+age+" ######################\n")); } /** * lancement de la partie un fois que tout est initialisé * @param plateau le plateau de jeu * @param nbJoueurs le nombre de joueur */ public void laPartie(Plateau plateau , int nbJoueurs ) throws NegativeNumberException { for (int age = 1; age <= 3; age++) { plateau.incrementeAge(); initMainJoueur(nbJoueurs); LoggerSevenWonders.ajoutln(Colors.gVert("\n\n########################## DEBUT Age N°" + age + " ###########################\n")); GenererCarte carte = new GenererCarte(age, nbJoueurs); distribution(carte.getCards()); joueAge(age, nbJoueurs, plateau); initMainJoueur(nbJoueurs); LoggerSevenWonders.ajoutln(Colors.gVert("########################## Fin Age N°" + age + " ###########################\n")); guerre(age); } LoggerSevenWonders.ajoutln("\n"); LoggerSevenWonders.ajoutln(Colors.gJaune("########################## SCORE FINAL ###########################\n")); for (int i = 0; i < nbJoueurs; i++) { SetInventaire s = inv.get(i); s.compteFinalScore(plateau.joueurGauche(s),plateau.joueurDroit(s),true); LoggerSevenWonders.ajoutln("Inventaire de Cartes : " +s.getListeCarte()); LoggerSevenWonders.ajoutln(Colors.gStandard("----------------------------------------------------------------------------------------------------------------------------------------------------------------------------")); } gagnante(nbJoueurs, plateau); } }
true
59ab11afbdf162aaef1829b3d5bf5247e6188136
Java
tjh-git/qq
/SuperClient/src/comm/langsin/msg_file/MsgVoiceResp.java
UTF-8
530
2.265625
2
[]
no_license
package comm.langsin.msg_file; import java.util.Arrays; import comm.langsin.msg_log_reg.MsgHead; public class MsgVoiceResp extends MsgHead { private String Name; private byte[] Voice; @Override public String toString() { return super.toString() + "MsgVoiceResp [Voice=" + Arrays.toString(Voice) + "]"; } public String getName() { return Name; } public void setName(String name) { Name = name; } public byte[] getVoice() { return Voice; } public void setVoice(byte[] voice) { Voice = voice; } }
true
7286a8a966d109aa7e7b9b8eb7bb07c56fef6c53
Java
kschulst/julekalender-api
/src/main/java/no/juleluka/api/calendar/participant/CalendarParticipantService.java
UTF-8
3,036
2.421875
2
[]
no_license
package no.juleluka.api.calendar.participant; import no.juleluka.api.calendar.Calendar; import no.juleluka.api.calendar.CalendarException; import no.juleluka.api.calendar.CalendarRepository; import no.juleluka.api.user.UserInfo; import no.juleluka.api.user.UserInfoRepository; import no.juleluka.api.user.UserInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import static java.util.Objects.requireNonNull; @Service public class CalendarParticipantService { private final UserInfoRepository userDetailsRepository; private final UserInfoService userInfoService; private final CalendarRepository calendarRepository; @Autowired public CalendarParticipantService(UserInfoRepository userDetailsRepository, UserInfoService userInfoService, CalendarRepository calendarRepository) { this.userDetailsRepository = requireNonNull(userDetailsRepository); this.userInfoService = requireNonNull(userInfoService); this.calendarRepository = requireNonNull(calendarRepository); } /** * Retrieves all calendars that the given user has participant privileges for. * Returns empty set if none. * * @param username the user's username as registered in auth0 */ public Set<Calendar> getParticipantCalendarsForUser(String username) { UserInfo user = userInfoService.get(username); return user.getParticipantOf().stream() .map(new Function<Long, Calendar>() { public Calendar apply(Long calendarId) { return calendarRepository.findById(calendarId).orElse(null); } }) .collect(Collectors.toSet()); } public Calendar joinCalendar(String username, Long calendarId) { Calendar calendar = getCalendar(calendarId); if (calendar.isJoinable()) { return addParticipant(username, calendarId); } else { throw new CalendarException("Calendar " + calendarId + " does not allow joining"); } } public Calendar addParticipant(String username, Long calendarId) { userInfoService.addParticipant(username, calendarId); Calendar calendar = getCalendar(calendarId); calendar.getParticipants().add(username); return calendarRepository.save(calendar); } public Calendar removeParticipant(String username, Long calendarId) { userInfoService.removeParticipant(username, calendarId); Calendar calendar = getCalendar(calendarId); calendar.getParticipants().remove(username); return calendarRepository.save(calendar); } private Calendar getCalendar(Long calendarId) { return calendarRepository.findById(calendarId) .orElseThrow(() -> new CalendarException("No calendar with id " + calendarId + " found")); } }
true
6ff327cb4c1b01434f62f5697ceefbc0d91906bf
Java
NotSoMadMax/PuzzlesForFun
/src/Medium/CountCompleteTreeNodes.java
UTF-8
1,775
3.46875
3
[]
no_license
package medium; public class CountCompleteTreeNodes { // 98%, but why ??? public int countNodes_fast(TreeNode root) { if(root==null) return 0; if (root.val != Integer.MIN_VALUE) { root.val = Integer.MIN_VALUE; return 1 + countNodes(root.left) + countNodes(root.right); } else return 0; } // 86% public int countNodes2(TreeNode root){ if(root == null) return 0; TreeNode l = root.left, r = root.right; int num = 2; while (l != null && r != null){ l = l.left; r = r.right; num = num << 1; } if(l == r) return num - 1; else return 1 + countNodes(root.left) + countNodes(root.right); } // 70% public int countNodes(TreeNode root) { if (root == null) return 0; int left_hight = 1, right_hight = 1; TreeNode l = root.left, r = root.right; while (l != null){ // left height left_hight++; l = l.left; } while (r != null){ // right height right_hight++; r = r.right; } if(left_hight == right_hight) // if is a perfect binary tree return (1<<left_hight) - 1; //67ms // return (int)Math.pow(2, left_hight) - 1; // 130ms else return countNodes(root.left) + countNodes(root.right) + 1; } // brutal force: time limit exceeds public int countNodes_brutal(TreeNode root){ if(root == null) return 0; return 1 + countNodes(root.left) + countNodes(root.right); } }
true
69fa094b034c31492e6548a5497c6ae50744d390
Java
majpyi/cs
/src/main/java/MyHttpSessionListener.java
UTF-8
695
2.875
3
[]
no_license
import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; /* * HttpSessionListener实现类 * sessionCreated() -- 在HttpSession对象被创建后被调用 * sessionDestroyed() -- -- 在HttpSession对象被销毁前调用 * HttpSessionEvent -- 事件类对象 * 该类有getSession(),用来获取当前HttpSession对象,即获取事件源对象 */ public class MyHttpSessionListener implements HttpSessionListener { public void sessionCreated(HttpSessionEvent evt) { System.out.println("创建session对象"); } public void sessionDestroyed(HttpSessionEvent evt) { System.out.println("销毁session对象"); } }
true
b95293ed779c3c7d96d1b0b02d0ee45ed3ef5d74
Java
rimmugygr/Customer-Credit
/Credit/src/main/java/springboot/credit/dto/CreditDto.java
UTF-8
187
1.78125
2
[]
no_license
package springboot.credit.dto; import lombok.*; @Data @AllArgsConstructor @NoArgsConstructor @Builder public class CreditDto { private Integer id; private String creditName; }
true
c56eaed2b2f28bfdbbc52f7dca975173801290dc
Java
USF-CS245-09-2017/practice-assignment-05-safyao
/MergeSort.java
UTF-8
2,331
4.3125
4
[]
no_license
import java.util.Arrays; public class MergeSort implements SortingAlgorithm { //Sort function splits given array into a left and right side. //Recursively calls itself to continue splitting the arrays in half. //Calls merge to put arrays back together. public void sort (int[] a) { if (a.length > 1) { int[] left = getLeft(a); int[] right = getRight(a); sort(left); sort(right); merge (a, left, right); } } //Merge function merges elements of two arrays together in the correct order. private void merge (int[] a, int[] left, int[] right) { int a_i = 0; //Index of the array. int left_i = 0; //Index of the left array. int right_i = 0; //Index of the right array. //While loop iterates through the array so long as the left/right's index don't go out of bounds. while (left_i < left.length && right_i < right.length) { //If the left element is less than the right element, the left element is assigned into the sorted array. if (left[left_i] <= right[right_i]) { a[a_i] = left[left_i]; left_i++; a_i++; } //In any other case, the right element is assigned to the sorted array, and both indeces are incremented. else { a[a_i] = right[right_i]; right_i++; a_i++; } } //Last two while-loops merge whatever is remaining in either array. while (left_i < left.length) { a[a_i++] = left[left_i++]; } while (right_i < right.length) { a[a_i++] = right[right_i++]; } } //getLeft function creates an array that goes from 0 to the middle of the given array. //The values of the left side of the given array is copied into "left". //"Left" is returned. private int[] getLeft (int[] a) { int leftlength = (a.length)/2; int[] left = new int[leftlength]; for (int i = 0; i < leftlength; i++) { left[i] = a[i]; } return left; } //getRight function creates an array that starts after the middle of the given array to the given array's end. //The values of the right side of the given array is copied into "right". //"Right" is returned. private int[] getRight (int[] a) { int leftlength = (a.length)/2; int rightlength = a.length - leftlength; int[] right = new int [rightlength]; for (int i = 0; i < (rightlength); i++) { right[i] = a[i + leftlength]; } return right; } }
true
69ef28fcf87ca4d8f74c722557069d8c37a309e9
Java
cristianoflima/bibliotecaApi
/src/main/java/br/com/obpc/livrariaObpcApi/daos/LivroDao.java
UTF-8
3,305
2.640625
3
[]
no_license
package br.com.obpc.livrariaObpcApi.daos; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.obpc.livrariaObpcApi.interfaces.ILivroDao; import br.com.obpc.livrariaObpcApi.models.Livro; import br.com.obpc.livrariaObpcApi.reponse.ResponseBuilder; import br.com.obpc.livrariaObpcApi.reponse.ResponseDto; import br.com.obpc.livrariaObpcApi.repository.LivroRepository; @Service public class LivroDao implements ILivroDao{ @Autowired private LivroRepository repositoryService; @Autowired private EntityManager em; @Override public ResponseDto salvar(Livro livro) throws Exception { Livro itemSalvo = repositoryService.save(livro); if(itemSalvo.getId() != null) return new ResponseBuilder().comSucesso().comMensagem("Livro "+itemSalvo.getTitulo()+" salvo com sucesso, ID gerado: "+itemSalvo.getId()).comItem(itemSalvo).build(); else return new ResponseBuilder().comSucesso().comMensagem("Livro "+livro.getTitulo()+" NÃO salvo!").build(); } @Override public ResponseDto buscarTodosLivros() throws Exception { Iterable<Livro> interable = repositoryService.findAll(); List<Livro> livros = new ArrayList<>(); interable.forEach(livros::add); if(livros.isEmpty()) return new ResponseBuilder().comSucesso().comMensagem("Nenhum livro encontrado").build(); else return new ResponseBuilder().comSucesso().comMensagem("Total de livros encontrados: "+livros.size()).comLista(livros).build(); } @Override public ResponseDto buscarLivroPorId(Integer id) throws Exception { Livro item = repositoryService.findOne(id); if(item != null) return new ResponseBuilder().comSucesso().comMensagem("Livro com ID: "+id+" encontrado.").comItem(item) .build(); else return new ResponseBuilder().comSucesso().comMensagem("Livro com ID: "+id+" NÂO encontrado.").build(); } @Override @SuppressWarnings("unchecked") public ResponseDto buscarLivroComFiltro(Livro livro) throws Exception { if(livro.isNull()) throw new RuntimeException("Livro não pode ser NULL."); Session s = em.unwrap(Session.class); Criteria c = s.createCriteria(Livro.class); if(livro.getAutor() != null) c.add(Restrictions.like("autor", "%"+livro.getAutor()+"%")); if(livro.getEditora() != null) c.add(Restrictions.like("editora", "%"+livro.getEditora()+"%")); if(livro.getLivrariaId() != null) c.add(Restrictions.like("livrariaId", livro.getLivrariaId())); if(livro.getTitulo() != null) c.add(Restrictions.like("titulo", "%"+livro.getTitulo()+"%")); if(livro.getAno() != null) c.add(Restrictions.like("ano", livro.getAno())); if(livro.getTema() != null) c.add(Restrictions.like("tema", "%"+livro.getTema()+"%")); List<Livro> livros = (List<Livro>) c.list(); if(livros.isEmpty()) return new ResponseBuilder().comSucesso().comMensagem("Nenhum livro encontrado com Título: "+livro.getTitulo()).build(); else return new ResponseBuilder().comSucesso().comMensagem("Total de livros encontrados: "+livros.size()).comLista(livros).build(); } }
true
d95fa165d896ebc39f90975754f0385633b7cd73
Java
MikhailKlimenko/redmine-java-api
/src/main/java/com/taskadapter/redmineapi/RedmineProcessingException.java
UTF-8
810
2.71875
3
[ "Apache-2.0" ]
permissive
package com.taskadapter.redmineapi; import java.util.List; public class RedmineProcessingException extends RedmineException { private static final long serialVersionUID = 1L; private final List<String> errors; private String text = ""; // TODO Refactor this to get rid of adding "\n". it should be up to the UI layer how to format all this public RedmineProcessingException(List<String> errors) { this.errors = errors; final StringBuilder builder = new StringBuilder(); for (String s : errors) { builder.append(s); builder.append("\n"); } this.text = builder.toString(); } public List<String> getErrors() { return errors; } @Override public String getMessage() { return text; } }
true
25eab4659c29dee619d6189184f32751211867d6
Java
Nitijkatiyar/coreyclient_android_studio
/app/src/main/java/com/coremobile/coreyhealth/analytics/CMN_GraphModel.java
UTF-8
1,074
1.9375
2
[]
no_license
package com.coremobile.coreyhealth.analytics; import java.io.Serializable; /** * Created by ireslab on 1/6/2016. */ public class CMN_GraphModel implements Serializable { CMN_GraphOptionsModel graphOptions; CMN_DetailGraphDataModel detailGraphDataValuesModel; CMN_GraphDataModel graphDataValuesModel; public CMN_GraphOptionsModel getGraphOptions() { return graphOptions; } public void setGraphOptions(CMN_GraphOptionsModel graphOptions) { this.graphOptions = graphOptions; } public CMN_DetailGraphDataModel getDetailGraphDataValuesModel() { return detailGraphDataValuesModel; } public void setDetailGraphDataValuesModel(CMN_DetailGraphDataModel detailGraphDataValuesModel) { this.detailGraphDataValuesModel = detailGraphDataValuesModel; } public CMN_GraphDataModel getGraphDataValuesModel() { return graphDataValuesModel; } public void setGraphDataValuesModel(CMN_GraphDataModel graphDataValuesModel) { this.graphDataValuesModel = graphDataValuesModel; } }
true
d416d9179ff182fbc29074bbb4607fc0fd06691e
Java
zohreb71/DecryptorExtension
/src/burp/BurpExtender.java
UTF-8
5,367
2.4375
2
[]
no_license
package burp; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; public class BurpExtender implements IBurpExtender, IMessageEditorTabFactory , ITab{ private IBurpExtenderCallbacks callbacks; private IExtensionHelpers helpers; private PrintWriter stdout; private ConfigurationGUI configurationTabGui; private static String encryptionAlg; List headers; byte[] msgBody; private static String secretKey ; private static String iv ; private AES aes; private DES des; public static void setSecretKey(String key) { secretKey = key; } public static void setIv(String IV) { iv = IV; } public static void setEncryptionAlg(String encAlg) { BurpExtender.encryptionAlg = encAlg; } @Override public void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks) { this.callbacks = callbacks; helpers = callbacks.getHelpers(); this.callbacks.issueAlert("Decryptor Extension Loaded Successfully."); stdout = new PrintWriter(callbacks.getStdout(),true); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { callbacks.setExtensionName("Decryptor Extension"); callbacks.registerMessageEditorTabFactory(BurpExtender.this); } }); configurationTabGui = new ConfigurationGUI(); callbacks.addSuiteTab(this); } @Override public IMessageEditorTab createNewInstance(IMessageEditorController controller, boolean editable) { return new Decryption(controller, editable); } @Override public String getTabCaption() { return "Decryptor Configuration"; } @Override public Component getUiComponent() { return configurationTabGui; } class Decryption implements IMessageEditorTab { private boolean editable; private ITextEditor txtInput; private byte[] currentMessage; public Decryption(IMessageEditorController controller, boolean editable) { this.editable = editable; txtInput = callbacks.createTextEditor(); txtInput.setEditable(editable); } @Override public String getTabCaption() { return "Decryption"; } @Override public Component getUiComponent() { return txtInput.getComponent(); } @Override public boolean isEnabled(byte[] content, boolean isRequest) { return true; } @Override public void setMessage(byte[] content, boolean isRequest){ String newBody = ""; String messageBody; IRequestInfo reqInfo = helpers.analyzeRequest(content); headers = reqInfo.getHeaders(); byte[] body = Arrays.copyOfRange(content,reqInfo.getBodyOffset(),content.length); messageBody = new String(body); try { newBody = decrypt(messageBody); } catch (Exception e) { e.printStackTrace(); } byte[] body2 = newBody.getBytes(); if (content == null) { txtInput.setText(null); txtInput.setEditable(false); } else { txtInput.setText(body2); txtInput.setEditable(editable); } currentMessage = content; } @Override public byte[] getMessage() { String res = ""; if (txtInput.isTextModified()) { byte[] input = txtInput.getText(); try { res = encrypt(new String (input)); }catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } msgBody = res.getBytes(); return helpers.buildHttpMessage(headers,msgBody); } else return currentMessage; } @Override public boolean isModified() { return txtInput.isTextModified(); } @Override public byte[] getSelectedData() { return txtInput.getSelectedText(); } } public String decrypt(String message) throws Exception { message = message.replace("\n",""); switch (encryptionAlg) { case "AES":{ aes = new AES (secretKey.getBytes(),iv); return aes.decrypt(message); } case "DES": { des = new DES(secretKey.getBytes()); return des.decrypt(message); } } return ""; } private String encrypt(String message) throws Exception { switch (encryptionAlg) { case "AES": { aes = new AES (secretKey.getBytes(),iv); return aes.encrypt(message); } case "DES":{ des = new DES(secretKey.getBytes()); return des.encrypt(message); } } return ""; } }
true
8fff7d8099eac08e08fc016cf9ff5d58f66edfdd
Java
danielleon/elleon-public
/elleon-core/elleon-core-application/src/main/java/de/elleon/dbca/util/persistence/DAOCommand.java
UTF-8
129
1.625
2
[]
no_license
package de.elleon.dbca.util.persistence; interface DAOCommand { Object execute(DAOManager daoManager) throws Exception; }
true
a1f4badf21114b6d59914924c543c7d92db173a7
Java
FamilyPop/FamilyPop_j2y
/FamilyPop/FamilyPop/src/main/java/com/j2y/familypop/activity/popup/Popup_messageBox_shareImage.java
UTF-8
1,930
2.078125
2
[]
no_license
package com.j2y.familypop.activity.popup; import android.app.Activity; import android.app.Dialog; import android.media.Image; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.nclab.familypop.R; /** * Created by lsh on 2016-08-20. */ public class Popup_messageBox_shareImage extends Dialog implements android.view.View.OnClickListener { public Activity _activity; public Button _ok; public Button _cancel; public TextView _content; public ImageView _imageView; //public EditText _editText; private String _okTXT; private String _cancelTXT; public Popup_messageBox_shareImage(Activity activity) { //Do you want to share a ramdom picture? super(activity,R.style.Theme_Dialog); _okTXT = new String("YES"); _cancelTXT = new String("NO"); _activity = activity; } @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); //setContentView(R.layout.custom_dialog); setContentView(R.layout.popup_messagebox_shareimage); _ok = (Button) findViewById(R.id.button_popupmessagebox_ok); //_ok.setBackground(R.style.Theme_Dialog); _cancel = (Button) findViewById(R.id.button_popupmessagebox_cancel); _content = (TextView) findViewById(R.id.txt_popupmessagebox_content); _imageView = (ImageView)findViewById(R.id.imageView_popupmessagebox_shareimage); //_editText = (EditText) findViewById(R.id.editText_messageBox_ok_cancel); _ok.setText(_okTXT); _cancel.setText(_cancelTXT); _ok.setOnClickListener(this); _cancel.setOnClickListener(this); } @Override public void onClick(View v) { } }
true
3d9fe9b6b5e30f7fd8646a58d59721953dfa7c3d
Java
neerajprasad/DSA
/src/com/interview/dp/Stairs.java
UTF-8
442
3.515625
4
[]
no_license
package interview.dp; public class Stairs { public static int climbStairs(int n) { int f[] = new int[n+2]; // 1 extra to handle case, n = 0 int i; /* 0th and 1st number of the series are 0 and 1*/ f[0] = 0; f[1] = 1; if(n==0) return 0; if(n==1) return 1; for (i = 2; i <= n+1; i++) { f[i] = f[i-1] + f[i-2]; } return f[n+1]; } }
true
4e9762566efc5e24fdd61726b9c4c2199a2713ef
Java
ecs160ss12019/OneB
/app/src/main/java/com/example/breakout/BONoPowerUp.java
UTF-8
681
2.171875
2
[]
no_license
package com.example.breakout; import android.graphics.Canvas; import android.graphics.Paint; public class BONoPowerUp extends BOPowerUp { public BOGameController gc; public BONoPowerUp (BOGameController gc) { this.gc = gc; } @Override public void apply(BOGameController gc) { // does nothing. } public String type(){ return "No PowerUp"; } public BOObject getMember() { return null; } @Override public void time() { } public void draw(Canvas mCanvas, Paint mPaint) { Point dim = gc.getMeta().getDim(); mCanvas.drawText("", dim.x / 55,dim.y / 4, mPaint); } }
true
19474fc56456e8d61128b53a5979ef303dc6440a
Java
CKubinec/Games
/src/RockPaperScissors/Player.java
UTF-8
1,530
3.4375
3
[]
no_license
package RockPaperScissors; import java.util.concurrent.ThreadLocalRandom; /** * The type Player. * * @author Craig Kubinec ID:3433193 * @assignment FINAL EXAM * @date July 29 2020 */ public class Player implements Runnable { /** * The Attack name. */ String attackName; /** * Instantiates a new Player. */ public Player() { } /** * Method that calls the player to get an attack! */ public synchronized void run() { boolean noAttack = true; while (noAttack) { try { getAttack(); noAttack = false; wait(); } catch (Exception e) { e.printStackTrace(); } } notify(); } /** * Gets a random number and chooses the attack for user. */ public synchronized void getAttack() { int random = ThreadLocalRandom.current().nextInt(1, 6); switch (random) { case 1: attackName = "Rock"; break; case 2: attackName = "Paper"; break; case 3: attackName = "Scissors"; break; case 4: attackName = "Lizard"; break; case 5: attackName = "Spock"; break; default: attackName = "Nothing"; } } }
true
3cb37d2279861957b15eb386ceaf778abbcfd3f6
Java
jtlai0921/XB1812-
/XB1812_教學資源/XB1812_範例程式/Sample/CH07/CalendarSet_1.java
BIG5
296
3.3125
3
[]
no_license
import java.util.*; class CalendarSet_1{ public static void main(String args[]){ Calendar now=Calendar.getInstance(); now.set(Calendar.YEAR,2020); System.out.println("{b~סG"+now.get(Calendar.YEAR)); System.out.println("{bG"+ (now.get(Calendar.MONTH)+1) ); } }
true
ada2747c1d8539ae8dd378e405a8515fd4488af5
Java
prashant31191/oat-android
/src/com/worth/oat/TakePhoto.java
UTF-8
3,724
2.515625
3
[]
no_license
package com.worth.oat; import java.io.IOException; import android.app.Activity; import android.content.Intent; import android.hardware.Camera; import android.hardware.Camera.PictureCallback; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.FrameLayout; import com.worth.utils.CameraPreview; import com.worth.utils.Constants; public class TakePhoto extends Activity { String LOGTAG = "TakePhoto"; Button photoInfo; FrameLayout preview; byte[] photoData; private int UPLOAD_PHOTO = 2; private Camera mCamera; private CameraPreview mPreview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.take_photo); // Get the camera mCamera = getCamera(); // Get the button that sends the user to fill in photo metadata and hide it photoInfo = (Button) findViewById(R.id.launch_metadata); photoInfo.setVisibility(View.GONE); // Create the camera preview mPreview = new CameraPreview(this, mCamera); preview = (FrameLayout) findViewById(R.id.camera_preview); preview.addView(mPreview); } @Override protected void onPause() { super.onPause(); if (Constants.debug) Log.i(LOGTAG, "onPause()"); mCamera.stopPreview(); mCamera.setPreviewCallback(null); mPreview.getHolder().removeCallback(mPreview); mCamera.release(); mCamera = null; } @Override protected void onResume() { super.onResume(); if (Constants.debug) Log.i(LOGTAG, "onResume()"); if (mCamera == null) { if (Constants.debug) Log.i(LOGTAG, "camera is null"); mCamera = getCamera(); mCamera.setPreviewCallback(null); mPreview = new CameraPreview(this, mCamera); preview.addView(mPreview); } } /** * This function is called when the user presses the 'capture' button. * The camera takes a picture and uses the JPEG callback. */ public void takePhoto(View v) { // Take the picture and use the jpeg callback mCamera.takePicture(null, null, jpegCallback); } /** * This function is called when the user presses the 'proceed' button after * he has taken a picture and would like to fill out metadata. */ public void launchPhotoInfo(View v) { Intent intent = new Intent(this, UploadPhoto.class); intent.putExtra("photo", photoData); startActivityForResult(intent, UPLOAD_PHOTO); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == UPLOAD_PHOTO) { if (resultCode == RESULT_OK) { // Receive data from UploadPhoto (caption and photo) String caption = data.getStringExtra("caption"); byte[] photoData = data.getByteArrayExtra("photo"); String photoId = data.getStringExtra("photoId"); // Send the same data to the parent activity Intent returnIntent = new Intent(); returnIntent.putExtra("caption", caption); returnIntent.putExtra("photo", photoData); returnIntent.putExtra("photoId", photoId); setResult(RESULT_OK, returnIntent); finish(); } } } /** * Get the Camera instance */ private Camera getCamera() { Camera c = null; try { c = Camera.open(); } catch (Exception e) { Log.i(LOGTAG, e.getMessage()); } return c; } /** * Callback for when the captured picture is ready in JPEG format. * Launch the PhotoInfo activity which allows the user to fill in metadata * about the photo. Send the bytearray to the activity as well. */ private PictureCallback jpegCallback = new PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { photoInfo.setVisibility(View.VISIBLE); photoData = data; } }; }
true
053c50640353a4ec2092cc05333ddd5a8b768c4a
Java
Rayworld8/Privalia
/app/src/main/java/com/simbiotic/privalia/views/activities/MainActivity.java
UTF-8
4,817
2.125
2
[]
no_license
package com.simbiotic.privalia.views.activities; import android.app.SearchManager; import android.content.Context; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import com.simbiotic.privalia.R; import com.simbiotic.privalia.common.Constants; import com.simbiotic.privalia.domain.events.GetMoviesEvent; import com.simbiotic.privalia.domain.events.GetSearchMoviesEvent; import com.simbiotic.privalia.domain.usecases.GetMoviesUsecase; import com.simbiotic.privalia.domain.usecases.SearchMoviesUsecase; import com.simbiotic.privalia.model.entities.Movie; import com.simbiotic.privalia.views.fragments.MovieFragment; import java.util.ArrayList; import de.greenrobot.event.EventBus; public class MainActivity extends BaseActivity { private MovieFragment moviesFragment = null; private SearchManager searchManager; private SearchView searchView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); moviesFragment = new MovieFragment(); showFragment(moviesFragment); EventBus.getDefault().post(new GetMoviesUsecase(Constants.FIRST_TIME)); } public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_search, menu); searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); searchView.setMaxWidth(Integer.MAX_VALUE); searchView.setLayoutParams(new ActionBar.LayoutParams(Gravity.RIGHT)); //searchView.setQueryHint(hint); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { searchView.onActionViewCollapsed(); moviesFragment.txtNoResults.setVisibility(View.GONE); moviesFragment.getSwipe().setRefreshing(true); EventBus.getDefault().post(new SearchMoviesUsecase(query, Constants.FIRST_TIME)); return false; } @Override public boolean onQueryTextChange(String query) { /*if (query.length() > 2) { searchView.onActionViewCollapsed(); moviesFragment.txtNoResults.setVisibility(View.GONE); moviesFragment.getSwipe().setRefreshing(true); EventBus.getDefault().post(new SearchMoviesUsecase(query, Constants.FIRST_TIME)); }*/ return false; } }); searchView.setOnCloseListener(new SearchView.OnCloseListener() { @Override public boolean onClose() { return false; } }); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_search: return true; default: return super.onOptionsItemSelected(item); } } public void showFragment(MovieFragment fragment) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.container, fragment); fragmentTransaction.commit(); } public void onEventMainThread(GetMoviesEvent event) { EventBus.getDefault().removeStickyEvent(event); Log.d("GetMoviesEvent", "ok"); ArrayList<Movie> mov = event.getMovies(); int token = event.getToken(); moviesFragment.setData(mov, token); if (mov.isEmpty()){ moviesFragment.txtNoResults.setVisibility(View.VISIBLE); } else { moviesFragment.txtNoResults.setVisibility(View.GONE); } } public void onEventMainThread(GetSearchMoviesEvent event) { EventBus.getDefault().removeStickyEvent(event); Log.d("GetSearchMoviesEvent", "ok"); ArrayList<Movie> mov = event.getSearchMovies(); int token = event.getToken(); moviesFragment.setData(mov, token); if (mov.isEmpty()){ moviesFragment.txtNoResults.setVisibility(View.VISIBLE); } else { moviesFragment.txtNoResults.setVisibility(View.GONE); } } }
true
9f107b781e16b02197d2186acfb731defc57d329
Java
175272511/valinor-parent
/valinor-note/valinor-note-api/src/main/java/com/ninesale/valinor/note/api/model/response/album/DubboGetAlbumContentResponse.java
UTF-8
670
1.804688
2
[]
no_license
package com.ninesale.valinor.note.api.model.response.album; import java.util.List; import com.pubpi.valinor.dubbo.base.model.DubboBasicResponse; /** * 添加评论返回类 * * @author skyhawk wthuan@foxmail.com * @date 2015年11月21日 下午2:04:09 * */ public class DubboGetAlbumContentResponse extends DubboBasicResponse { private static final long serialVersionUID = 1L; private List<Long> noteIdList; /** * @return the noteIdList */ public List<Long> getNoteIdList() { return noteIdList; } /** * @param noteIdList * the noteIdList to set */ public void setNoteIdList(List<Long> noteIdList) { this.noteIdList = noteIdList; } }
true
c4bdb9904e188236fcac1ca1ccab0d2ccc815c7c
Java
wolox-training/ss-java
/src/main/java/wolox/training/integration/dto/Classifications.java
UTF-8
1,323
2.015625
2
[]
no_license
package wolox.training.integration.dto; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.HashMap; import java.util.List; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) public class Classifications { private List<String> deweyDecimalClass = null; private List<String> lcClassifications = null; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); public List<String> getDeweyDecimalClass() { return deweyDecimalClass; } public void setDeweyDecimalClass(List<String> deweyDecimalClass) { this.deweyDecimalClass = deweyDecimalClass; } public List<String> getLcClassifications() { return lcClassifications; } public void setLcClassifications(List<String> lcClassifications) { this.lcClassifications = lcClassifications; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
true
80d5326f44563f724f0c91f35841c17335199f38
Java
zjlwmz/java-web
/SchoolService/src/cn/emay/common/response/ResponeResultClasses.java
UTF-8
302
1.859375
2
[]
no_license
package cn.emay.common.response; import java.util.List; import cn.emay.model.Classes; public class ResponeResultClasses extends ResponseResultBase{ private List<Classes>list; public List<Classes> getList() { return list; } public void setList(List<Classes> list) { this.list = list; } }
true
9bcdca39bbdab239a98ee23fa2353615292fc419
Java
PrateekSharma1712/FUT18PackOpener
/app/src/main/java/com/prateek/fut17packopener/ui/PackDetailsActivity.java
UTF-8
5,159
2.125
2
[ "Apache-2.0" ]
permissive
package com.prateek.fut17packopener.ui; import android.databinding.DataBindingUtil; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.google.android.gms.games.Games; import com.prateek.fut17packopener.AppController; import com.prateek.fut17packopener.CustomPreference; import com.prateek.fut17packopener.PackDetailsAdapter; import com.prateek.fut17packopener.PlayerManager; import com.prateek.fut17packopener.R; import com.prateek.fut17packopener.database.PlayerDAO; import com.prateek.fut17packopener.databinding.ActivityPackDetailsBinding; import com.prateek.fut17packopener.models.PackOpenerPlayer; import ru.bullyboo.text_animation.TextCounter; public class PackDetailsActivity extends AppCompatActivity implements PackDetailsAdapter.ItemClickListener { private ActivityPackDetailsBinding binding; private PackDetailsAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_pack_details); binding.packValue.setTypeface(AppController.getTypeface()); if (AppController.getGoogleApiHelper().getGoogleApiClient().isConnected()) { Games.Achievements.unlock(AppController.getGoogleApiHelper().getGoogleApiClient(), getString(R.string.achievement_open_pack)); } showPackValue(); RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false); binding.packMembersList.setLayoutManager(layoutManager); binding.packMembersList.setHasFixedSize(true); mAdapter = new PackDetailsAdapter(this, this); binding.packMembersList.setAdapter(mAdapter); binding.saveAll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { PlayerDAO playerDAO = new PlayerDAO(PackDetailsActivity.this); playerDAO.saveUserPlayer(PlayerManager.getInstance().getPackPlayers()); finish(); } }); } private void showPackValue() { int packValue = 0; for (PackOpenerPlayer player : PlayerManager.getInstance().getPackPlayers()) { packValue += player.getRating(); } packValue = (int) Math.ceil(packValue/PlayerManager.getInstance().getPackPlayers().size()); TextCounter.newBuilder() .setTextView(binding.packValue) .from(0) .to(packValue) .setDuration(packValue*20) .build() .start(); CustomPreference.updateTotalPackValue(CustomPreference.getTotalPackValue() + (long)packValue); Games.Leaderboards.submitScore(AppController.getGoogleApiHelper().getGoogleApiClient(), getString(R.string.leaderboard_total_pack_value), CustomPreference.getTotalPackValue()); Games.Leaderboards.submitScore(AppController.getGoogleApiHelper().getGoogleApiClient(), getString(R.string.leaderboard_best_pack), packValue); int bestPackValue = CustomPreference.getBestPackValue(); if (bestPackValue < packValue) { CustomPreference.updateBestPackValue(packValue); } } @Override public void onBackPressed() { if (binding.playerDetailView.getVisibility() == View.VISIBLE) { binding.playerDetailView.setVisibility(View.GONE); return; } super.onBackPressed(); } @Override public void onItemClicked(final PackOpenerPlayer player) { long sellValue = 0; binding.playerCardView.setValues(player); binding.playerDetailView.setVisibility(View.VISIBLE); if (PlayerManager.getInstance().isPlayerDuplicate(PackDetailsActivity.this, player)) { binding.sell.setVisibility(View.VISIBLE); sellValue = PlayerManager.getInstance().getSellValue(player); binding.sell.setText("Sell for " + sellValue); } final long finalSellValue = sellValue; binding.sell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { binding.playerDetailView.setVisibility(View.GONE); PlayerManager.getInstance().deleteDuplicateCard(PackDetailsActivity.this, player); CustomPreference.updateCoins(CustomPreference.getCoins()+ finalSellValue); updateAdapter(player); } }); } private void updateAdapter(PackOpenerPlayer player) { mAdapter.removePlayer(player); } @Override protected void onResume() { super.onResume(); if (AppController.getGoogleApiHelper().getGoogleApiClient().isConnected()) { Games.setViewForPopups(AppController.getGoogleApiHelper().getGoogleApiClient(), getWindow().getDecorView()); } } }
true
50c38afca6b03e9533b550d1d224dc973a4a0500
Java
navikt/common-java-modules
/client/src/main/java/no/nav/common/client/aktoroppslag/AktorregisterHttpClient.java
UTF-8
10,645
1.992188
2
[ "MIT" ]
permissive
package no.nav.common.client.aktoroppslag; import com.fasterxml.jackson.databind.type.MapType; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import no.nav.common.client.aktoroppslag.BrukerIdenter; import no.nav.common.client.aktorregister.AktorregisterClient; import no.nav.common.client.aktorregister.IngenGjeldendeIdentException; import no.nav.common.health.HealthCheckResult; import no.nav.common.health.HealthCheckUtils; import no.nav.common.json.JsonUtils; import no.nav.common.rest.client.RestClient; import no.nav.common.types.identer.AktorId; import no.nav.common.types.identer.EksternBrukerId; import no.nav.common.types.identer.Fnr; import no.nav.common.types.identer.Id; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; import java.util.*; import java.util.function.Supplier; import java.util.stream.Collectors; import static java.lang.String.valueOf; import static java.util.stream.Collectors.toList; import static no.nav.common.rest.client.RestUtils.getBodyStr; import static no.nav.common.utils.UrlUtils.joinPaths; @Slf4j public class AktorregisterHttpClient implements AktorregisterClient { private final static MapType mapType = JsonUtils.getMapper().getTypeFactory().constructMapType(HashMap.class, String.class, IdentData.class); private final String aktorregisterUrl; private final String aktorregisterIsAliveUrl; private final String consumingApplication; private final Supplier<String> tokenSupplier; private final OkHttpClient client; public AktorregisterHttpClient(String aktorregisterUrl, String consumingApplication, Supplier<String> tokenSupplier) { this.aktorregisterUrl = aktorregisterUrl; this.aktorregisterIsAliveUrl = resolveIsAliveUrl(aktorregisterUrl); this.consumingApplication = consumingApplication; this.tokenSupplier = tokenSupplier; this.client = RestClient.baseClient(); } @Override public Fnr hentFnr(AktorId aktorId) { return Fnr.of(hentEnkeltIdent(aktorId, Identgruppe.NorskIdent)); } @Override public AktorId hentAktorId(Fnr fnr) { return AktorId.of(hentEnkeltIdent(fnr, Identgruppe.AktoerId)); } @SneakyThrows @Override public Map<AktorId, Fnr> hentFnrBolk(List<AktorId> aktorIdListe) { Map<String, IdentData> oppslagMap = hentIdenter(aktorIdListe, Identgruppe.AktoerId, true); Map<AktorId, Fnr> aktorIdToFnrMap = new HashMap<>(); oppslagMap .entrySet() .stream() .map(this::tilIdentOppslag) .forEach(oppslag -> { AktorId aktorId = AktorId.of(oppslag.getIdentTilRegister()); Optional<Fnr> maybeFnr = oppslag.getIdentFraRegister().map(Fnr::of); maybeFnr.ifPresent(fnr -> aktorIdToFnrMap.put(aktorId, fnr)); }); return aktorIdToFnrMap; } @SneakyThrows @Override public Map<Fnr, AktorId> hentAktorIdBolk(List<Fnr> fnrListe) { Map<String, IdentData> oppslagMap = hentIdenter(fnrListe, Identgruppe.AktoerId, true); Map<Fnr, AktorId> fnrToAktorIdMap = new HashMap<>(); oppslagMap .entrySet() .stream() .map(this::tilIdentOppslag) .forEach(oppslag -> { Fnr fnr = Fnr.of(oppslag.getIdentTilRegister()); Optional<AktorId> maybeAktorId = oppslag.getIdentFraRegister().map(AktorId::of); maybeAktorId.ifPresent(aktorId -> fnrToAktorIdMap.put(fnr, aktorId)); }); return fnrToAktorIdMap; } @SneakyThrows @Override public List<AktorId> hentAktorIder(Fnr fnr) { return hentIdenter(Collections.singletonList(fnr), Identgruppe.AktoerId, false) .entrySet() .stream() .flatMap(e -> Optional.ofNullable(e.getValue().identer) .orElseThrow(() -> new RuntimeException("Aktør registeret feilet og fant ikke identer på bruker")) .stream() .filter(i -> i.identgruppe == Identgruppe.AktoerId && i.ident != null) .map(i -> AktorId.of(i.ident))) .collect(toList()); } @SneakyThrows @Override public BrukerIdenter hentIdenter(EksternBrukerId brukerId) { Map<String, IdentData> stringIdentDataMap = hentIdenter(Collections.singletonList(brukerId), null, false); if (!stringIdentDataMap.containsKey(brukerId.get())) { throw new RuntimeException("Fant ikke identer for bruker"); } IdentData identData = stringIdentDataMap.get(brukerId.get()); var norskeIdenter = identData.identer.stream() .filter(ident -> Identgruppe.NorskIdent.equals(ident.identgruppe)).collect(toList()); var aktorIder = identData.identer.stream() .filter(ident -> Identgruppe.AktoerId.equals(ident.identgruppe)).collect(toList()); return new BrukerIdenter( norskeIdenter.stream().filter(ident -> ident.gjeldende).findFirst().map(ident -> Fnr.of(ident.ident)).orElseThrow(), aktorIder.stream().filter(ident -> ident.gjeldende).findFirst().map(ident -> AktorId.of(ident.ident)).orElseThrow(), norskeIdenter.stream().filter(ident -> !ident.gjeldende).map(ident -> Fnr.of(ident.ident)).collect(toList()), aktorIder.stream().filter(ident -> !ident.gjeldende).map(ident -> AktorId.of(ident.ident)).collect(toList()) ); } @SneakyThrows private String hentEnkeltIdent(EksternBrukerId eksternBrukerId, Identgruppe identgruppe) { return hentIdenter(Collections.singletonList(eksternBrukerId), identgruppe, true) .entrySet() .stream() .filter(this::filtrerIkkeGjeldendeIdent) .findFirst() .flatMap(e -> finnGjeldendeIdent(e.getValue().identer)) .map(i -> i.ident) .orElseThrow(IngenGjeldendeIdentException::new); } private String createRequestUrl(String aktorregisterUrl, Identgruppe identgruppe, boolean gjeldende) { var queryParams = new HashMap<String, String>(); if (gjeldende) { queryParams.put("gjeldende", "true"); } if (identgruppe != null) { queryParams.put("identgruppe", valueOf(identgruppe)); } var queryParamsString = queryParams.entrySet().stream() .map(param -> param.getKey() + "=" + param.getValue()) .collect(Collectors.joining("&", queryParams.isEmpty() ? "" : "?", "")); return String.format("%s/identer%s", aktorregisterUrl, queryParamsString); } private boolean filtrerIkkeGjeldendeIdent(Map.Entry<String, IdentData> identEntry) { List<Ident> identer = identEntry.getValue().identer; return identer != null && finnGjeldendeIdent(identer).isPresent(); } private Optional<Ident> finnGjeldendeIdent(List<Ident> identer) { return identer.stream().filter(ident -> ident.gjeldende).findFirst(); } private IdentOppslag tilIdentOppslag(Map.Entry<String, IdentData> identEntry) { Optional<Ident> gjeldendeIdent = finnGjeldendeIdent(identEntry.getValue().identer); return new IdentOppslag(identEntry.getKey(), gjeldendeIdent.map(i -> i.ident).orElse(null)); } private Map<String, IdentData> hentIdenter( List<? extends EksternBrukerId> eksternBrukerIdList, Identgruppe identgruppe, boolean gjeldende ) throws IOException { String personidenter = eksternBrukerIdList.stream().map(Id::get).collect(Collectors.joining(",")); String requestUrl = createRequestUrl(aktorregisterUrl, identgruppe, gjeldende); Request request = new Request.Builder() .url(requestUrl) .addHeader("Nav-Call-Id", UUID.randomUUID().toString()) .addHeader("Nav-Consumer-Id", consumingApplication) .addHeader("Nav-Personidenter", personidenter) .addHeader("Authorization", "Bearer " + tokenSupplier.get()) .build(); try (Response response = client.newCall(request).execute()) { if (response.code() >= 300) { String responseStr = getBodyStr(response).orElse(""); throw new RuntimeException( String.format("Fikk uventet status %d fra %s. Respons: %s", response.code(), request, responseStr) ); } Optional<String> jsonStr = getBodyStr(response); if (jsonStr.isEmpty()) { throw new IllegalStateException("Respons mangler body"); } return JsonUtils.getMapper().readValue(jsonStr.get(), mapType); } catch (Exception e) { log.error("Klarte ikke å gjore oppslag mot aktorregister", e); throw e; } } @Override public HealthCheckResult checkHealth() { return HealthCheckUtils.pingUrl(aktorregisterIsAliveUrl, client); } enum Identgruppe { NorskIdent, AktoerId } private static class IdentData { public List<Ident> identer; public String feilmelding; } private static class Ident { public String ident; // fnr eller aktorid public Identgruppe identgruppe; public boolean gjeldende; } private static class IdentOppslag { /** * Identen(fnr/aktør id) som det ble gjort oppslag på i aktørregisteret */ private String identTilRegister; /** * Identen(fnr/aktør id) som det ble returnert fra aktørregisteret */ private String identFraRegister; public IdentOppslag(String identTilRegister, String identFraRegister) { this.identTilRegister = identTilRegister; this.identFraRegister = identFraRegister; } public String getIdentTilRegister() { return identTilRegister; } public Optional<String> getIdentFraRegister() { return Optional.ofNullable(identFraRegister); } } private String resolveIsAliveUrl(String apiUrl) { String baseUrl = apiUrl; if (apiUrl.endsWith("api/v1")) { baseUrl = apiUrl.replace("api/v1", ""); } return joinPaths(baseUrl, "/internal/isAlive"); } }
true
d18970fc8ffcc11d2ea0d9113f522d97c55fd515
Java
ashishjain1988/BCB569_Assignments
/src/main/java/Assignment1/BCB569/MainClass.java
UTF-8
17,793
2.9375
3
[]
no_license
package Assignment1.BCB569; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import Assignment2.BCB569.Atom; /** * The Class MainClass. * * @author Ashish Jain */ public class MainClass { /** The atom names. */ public static List<String> atomNames = Arrays.asList("N","CA","C"); /** * The main method. * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main( String[] args ) throws IOException { if(args.length != 1) { System.err.println("Please enter PDB file Path."); System.exit(0); } if(!new File(args[0]).exists()) { System.err.println("PDB File path is not correct"); System.exit(0); } String rName, rChain, rSequence; rName = rChain = rSequence = ""; List<AminoAcid> aminoAcids = new ArrayList<AminoAcid>(); Map<String, Atom> atoms = new HashMap<String, Atom>(); Map<String, Vector> aminoAcidBackbone = new HashMap<String, Vector>(); BufferedReader br = new BufferedReader(new FileReader(args[0])); PrintWriter pw = new PrintWriter("BCB3HW1Results.txt"); String line = br.readLine(); List<String> lineInPDBFile = new ArrayList<String>(); while(line != null) { lineInPDBFile.add(line); line = br.readLine(); } br.close(); line = ""; pw.println("Question 1:"); pw.println("Residue Sequence\tAtom Name\tCoordinate X\tCoordinate Y\tCoordinate Z"); for(int i=0;i<lineInPDBFile.size();i++) { line = lineInPDBFile.get(i); String recordType = line.substring(0, 4); if(recordType.equals("ATOM")) { String recordTypeNext = lineInPDBFile.get(i+1).substring(0, 4); String atomName = line.substring(12,16).trim(); String elementSymbol = line.substring(76,78).trim(); String resName = line.substring(17,20).trim(); String resChain = line.substring(21,22).trim(); String resSequence = line.substring(22,26).trim(); Integer atomicNumber = Integer.parseInt(line.substring(6,11).trim()); Vector coordinate = new Vector(Double.valueOf(line.substring(31,38).trim()), Double.valueOf(line.substring(38,46).trim()), Double.valueOf(line.substring(46,54).trim())); //Condition for first residue if((rName.equals("") && rChain.equals("") && rSequence.equals(""))) { rName = resName; rChain = resChain; rSequence = resSequence; }else if(!(resName.equals(rName) && resChain.equals(rChain) && resSequence.equals(rSequence))) { if(aminoAcidBackbone.size() == 3) { //if(!aminoAcids.contains(new AminoAcid(rSequence, rChain, rName, aminoAcidBackbone.get("N"), aminoAcidBackbone.get("CA"), aminoAcidBackbone.get("C")))) { aminoAcids.add(new AminoAcid(rSequence, rChain, rName, elementSymbol,aminoAcidBackbone.get("N"), aminoAcidBackbone.get("CA"), aminoAcidBackbone.get("C"),atoms)); aminoAcidBackbone = new HashMap<String, Vector>(); atoms = new HashMap<String, Atom>(); } } rName = resName; rChain = resChain; rSequence = resSequence; } //Question 1: if(atomNames.contains(atomName)) { pw.println(resSequence+"\t"+atomName+"\t"+coordinate.getX()+"\t"+coordinate.getY()+"\t"+coordinate.getZ()); aminoAcidBackbone.put(atomName, coordinate); } //if(!elementSymbol.equals("H")) //{ atoms.put(atomName, new Atom(coordinate,null,atomicNumber)); //} //Store last Residue if(!recordTypeNext.equals("ATOM")) { aminoAcids.add(new AminoAcid(rSequence, rChain, rName,elementSymbol,aminoAcidBackbone.get("N"), aminoAcidBackbone.get("CA"), aminoAcidBackbone.get("C"),atoms)); } } } //System.out.println(aminoAcids.size()); pw.println("Question 2:"); CalculateMeanAndSDofAngles(aminoAcids, pw); AminoAcid aa29 = aminoAcids.get(28); AminoAcid aa30 = aminoAcids.get(29); AminoAcid aa31 = aminoAcids.get(30); //Question 3: pw.println("Question 3:"); pw.println("The Phi, Psi and Omega angles of 30th Residue is "+AminoAcid.phiAngle(aa29, aa30)+","+AminoAcid.psiAngle(aa30, aa31)+","+AminoAcid.omegaAngle(aa30, aa29)); //Vector rot = aa30.getBackboneCA().crossProduct(aa30.getBackboneC()); //Vector id = new Vector(rot.getX()/(aa30.getBackboneC().length()*aa30.getBackboneCA().length()*Math.sin(Math.toRadians(Vector.angle(aa30.getBackboneCA(), aa30.getBackboneC())))), rot.getY()/rot.length()*Math.sin(Math.toRadians(Vector.angle(aa30.getBackboneCA(), aa30.getBackboneC()))), rot.getZ()/rot.length()*Math.sin(Math.toRadians(Vector.angle(aa30.getBackboneCA(), aa30.getBackboneC())))); //System.out.println(id); //System.out.println(aa29.getBackboneCA().crossProduct(aa29.getBackboneN()).divide(aa29.getBackboneCA().crossProduct(aa29.getBackboneN()).length())); PrintWriter pw1 = new PrintWriter("2GB1-new.pdb"); List<AminoAcid> rotatedAminoAcids = rotation(aminoAcids, Math.toRadians(AminoAcid.phiAngle(aa29, aa30)), Math.toRadians(AminoAcid.psiAngle(aa30, aa31))); for(int i=0;i<lineInPDBFile.size();i++) { line = lineInPDBFile.get(i); String recordType = line.substring(0, 4); if(recordType.equals("ATOM")) { String atomName = line.substring(12,16).trim(); String resSequence = line.substring(22,26).trim(); AminoAcid aminoAcid =rotatedAminoAcids.get(Integer.parseInt(resSequence)-1); Vector vector = aminoAcid.getAtoms().get(atomName).getPosition(); line = line.replace(line.substring(31,38).trim(), String.format( "%.3f", vector.getX())); line = line.replace(line.substring(38,46).trim(), String.format( "%.3f", vector.getY())); line = line.replace(line.substring(46,54).trim(), String.format( "%.3f", vector.getZ())); } pw1.println(line); } pw1.close(); pw.println("Question 4b:"); List<Object> result = minimumDistance(rotatedAminoAcids); pw.println("The minimum distance is "+result.get(0)+" and the pair of atoms are "+result.get(1)); pw.println("Question 5:"); calculateSideChainTorsionAngles(aminoAcids, pw); pw.close(); } /** * Calculate mean and S dof angles. * * @param aminoAcids the amino acids * @param pw the pw */ //Question 2: public static void CalculateMeanAndSDofAngles(List<AminoAcid> aminoAcids, PrintWriter pw) { List<Double> bondLengthsNCA = new ArrayList<Double>(); List<Double> bondLengthsCAC = new ArrayList<Double>(); List<Double> bondLengthsCN = new ArrayList<Double>(); List<Double> bondAnglesNCAC = new ArrayList<Double>(); List<Double> bondAnglesCACN = new ArrayList<Double>(); List<Double> bondAnglesCNCA = new ArrayList<Double>(); List<Double> distanceCA = new ArrayList<Double>(); for(int i=0;i<aminoAcids.size()-1;i++) { AminoAcid aa = aminoAcids.get(i); AminoAcid aa_next = aminoAcids.get(i+1); bondLengthsCAC.add(aa.getBackboneCA().distance(aa.getBackboneC())); bondLengthsCN.add(aa.getBackboneC().distance(aa_next.getBackboneN())); bondLengthsNCA.add(aa.getBackboneN().distance(aa.getBackboneCA())); bondAnglesNCAC.add(Vector.angle(aa.getBackboneN().subtract(aa.getBackboneCA()),aa.getBackboneCA().subtract(aa.getBackboneC()))); bondAnglesCACN.add(Vector.angle(aa.getBackboneCA().subtract(aa.getBackboneC()), aa.getBackboneC().subtract(aa_next.getBackboneN()))); bondAnglesCNCA.add(Vector.angle(aa.getBackboneC().subtract(aa_next.getBackboneN()), aa_next.getBackboneN().subtract(aa_next.getBackboneCA()))); distanceCA.add(aa.getBackboneCA().distance(aa_next.getBackboneCA())); } AminoAcid aa = aminoAcids.get(aminoAcids.size()-1); Double bondLengthNCA = aa.getBackboneN().distance(aa.getBackboneCA()); Double bondLengthCAC = aa.getBackboneCA().distance(aa.getBackboneC()); bondLengthsCAC.add(bondLengthCAC); bondLengthsNCA.add(bondLengthNCA); Double bondAngleNCAC = Vector.angle(aa.getBackboneN().subtract(aa.getBackboneCA()), aa.getBackboneCA().subtract(aa.getBackboneC())); bondAnglesNCAC.add(bondAngleNCAC); pw.println("The Mean of Bond Lengths Ni-CAi, CAi-Ci, Ci-N(i+1) "+Mean(bondLengthsNCA) +","+Mean(bondLengthsCAC)+","+Mean(bondLengthsCN)); pw.println("The Standard Deviation of Bond Lengths Ni-CAi, CAi-Ci, Ci-N(i+1) "+SDV(bondLengthsNCA) +","+SDV(bondLengthsCAC)+","+SDV(bondLengthsCN)); pw.println("The Mean of Bond Angles Ni-CAi-Ci, CAi-Ci-N(i+1), Ci-N(i+1)-CA(i+1) "+Mean(bondAnglesNCAC) +","+Mean(bondAnglesCACN)+","+Mean(bondAnglesCNCA)); pw.println("The Standard Deviation of Bond Angles Ni-CAi-Ci, CAi-Ci-N(i+1), Ci-N(i+1)-CA(i+1) "+SDV(bondAnglesNCAC) +","+SDV(bondAnglesCACN)+","+SDV(bondAnglesCNCA)); pw.println("The Mean of distance between CAi-CA(i+1) "+Mean(distanceCA)); pw.println("The Standard Deviation of of distance between CAi-CA(i+1) "+SDV(distanceCA)); } /** * Rotation. * * @param aminoAcids the amino acids * @param PhiAngle the phi angle * @param PsiAngle the psi angle * @return the list */ //Question 4a: public static List<AminoAcid> rotation(List<AminoAcid> aminoAcids,Double PhiAngle, Double PsiAngle) { List<AminoAcid> newAminoAcids = new ArrayList<AminoAcid>(); //Double [][] newRotationMatrix = {{Math.cos(-PsiAngle),Math.sin(-PsiAngle),0d},{-Math.sin(-PsiAngle)*Math.cos(-PhiAngle),Math.cos(-PsiAngle)*Math.cos(-PhiAngle),-Math.sin(-PhiAngle)},{-Math.sin(-PsiAngle)*Math.sin(-PhiAngle),Math.sin(-PsiAngle)*Math.cos(-PhiAngle),Math.cos(-PhiAngle)}}; Double [] [] xRotationMatrix = {{1d,0d,0d},{0d,Math.cos(-PhiAngle),-Math.sin(-PhiAngle)},{0d,Math.sin(-PhiAngle),Math.cos(-PhiAngle)}}; //Double [] [] yRotationMatrix = {{Math.cos(-PhiAngle),0d,Math.sin(-PhiAngle)},{0d,1d,0d},{-Math.sin(-PhiAngle),0d,Math.cos(-PhiAngle)}}; //Double [] [] zRotationMatrix = {{Math.cos(-PhiAngle),-Math.sin(-PhiAngle),0d},{Math.sin(-PhiAngle),Math.cos(-PhiAngle),0d},{0d,0d,1d}}; for(int i=0;i<30;i++) { AminoAcid aa = aminoAcids.get(i); Map<String, Atom> atoms = aa.getAtoms(); Map<String, Atom> newAtoms = new HashMap<String, Atom>(); for(Entry<String, Atom> atom : atoms.entrySet()) { String atomName = atom.getKey(); Vector atomVector = atom.getValue().getPosition(); Vector afterRotation = Vector.multiplyVectorMatrix(xRotationMatrix,atomVector.toArray()); //afterRotation = Vector.multiplyVectorMatrix(yRotationMatrix, afterRotation.toArray()); //afterRotation = Vector.multiplyVectorMatrix(zRotationMatrix, afterRotation.toArray()); newAtoms.put(atomName, new Atom(afterRotation,null,atom.getValue().getAtomicNumber())); } AminoAcid newAA = aa; newAA.setAtoms(newAtoms); newAminoAcids.add(newAA); } /*AminoAcid aa1 = aminoAcids.get(29); Map<String, Vector> atoms1 = aa1.getAtoms(); Map<String, Vector> newAtoms1 = new HashMap<String, Vector>(); for(Entry<String, Vector> atom : atoms1.entrySet()) { String atomName = atom.getKey(); Vector atomVector = atom.getValue(); if(atomNames.contains(atomName)) { Vector afterRotation = Vector.multiplyVectorMatrix(xRotationMatrix,atomVector.toArray()); //afterRotation = Vector.multiplyVectorMatrix(yRotationMatrix, afterRotation.toArray()); afterRotation = Vector.multiplyVectorMatrix(zRotationMatrix1, afterRotation.toArray()); newAtoms1.put(atomName, afterRotation); }else { newAtoms1.put(atomName, atomVector); } } AminoAcid newAA1 = aa1; newAA1.setAtoms(newAtoms1); newAminoAcids.add(newAA1);*/ //newAminoAcids.add(aminoAcids.get(29)); //Double [] [] xRotationMatrix1 = {{1d,0d,0d},{0d,Math.cos(-PsiAngle),-Math.sin(-PsiAngle)},{0d,Math.sin(-PsiAngle),Math.cos(-PsiAngle)}}; //Double [] [] yRotationMatrix1 = {{Math.cos(-PsiAngle),0d,Math.sin(-PsiAngle)},{0d,1d,0d},{-Math.sin(-PsiAngle),0d,Math.cos(-PsiAngle)}}; Double [] [] zRotationMatrix1 = {{Math.cos(-PsiAngle),-Math.sin(-PsiAngle),0d},{Math.sin(-PsiAngle),Math.cos(-PsiAngle),0d},{0d,0d,1d}}; for(int i=30;i<aminoAcids.size();i++) { AminoAcid aa = aminoAcids.get(i); Map<String, Atom> atoms = aa.getAtoms(); Map<String, Atom> newAtoms = new HashMap<String, Atom>(); for(Entry<String, Atom> atom : atoms.entrySet()) { String atomName = atom.getKey(); Vector atomVector = atom.getValue().getPosition(); Vector afterRotation = Vector.multiplyVectorMatrix(zRotationMatrix1, atomVector.toArray()); //afterRotation = Vector.multiplyVectorMatrix(yRotationMatrix1, afterRotation.toArray()); //afterRotation = Vector.multiplyVectorMatrix(zRotationMatrix1, afterRotation.toArray()); newAtoms.put(atomName, new Atom(afterRotation, null, atom.getValue().getAtomicNumber())); } AminoAcid newAA = aa; newAA.setAtoms(newAtoms); newAminoAcids.add(newAA); } return newAminoAcids; } /** * Minimum distance. * * @param rotatedAminoAcids the rotated amino acids * @return the list */ //Question 4b: public static List<Object> minimumDistance(List<AminoAcid> rotatedAminoAcids) { //Map<String, Double> atomsDistances = new HashMap<String, Double>(); Double distance = 1000d; String atomsName = ""; List<Object> result; List<Object> finalResult = new ArrayList<Object>(); for(int i=0;i<rotatedAminoAcids.size()-1;i++) { //Calculate Distance between each atom in a residue AminoAcid aa1 = rotatedAminoAcids.get(i); result = AminoAcid.getMinimumDistanceBetweenAtomsOfResidues(aa1, aa1, true); if(distance > (Double)result.get(0)) { distance = (Double)result.get(0); atomsName = (String)result.get(1); } for(int j=i+1;j<rotatedAminoAcids.size();j++) { //Calculate Distance between atoms from other residues AminoAcid aa2 = rotatedAminoAcids.get(j); result = AminoAcid.getMinimumDistanceBetweenAtomsOfResidues(aa1, aa2, false); if(distance > (Double)result.get(0)) { distance = (Double)result.get(0); atomsName = (String)result.get(1); } } } //Calculate distance between the atoms of last residue. AminoAcid aa1 = rotatedAminoAcids.get(rotatedAminoAcids.size()-1); result = AminoAcid.getMinimumDistanceBetweenAtomsOfResidues(aa1, aa1, true); if(distance > (Double)result.get(0)) { distance = (Double)result.get(0); atomsName = (String)result.get(1); } finalResult.add(distance); finalResult.add(atomsName); return finalResult; } /** * Calculate side chain torsion angles. * * @param aminoAcids the amino acids * @param pw the pw */ //Question 5: public static void calculateSideChainTorsionAngles(List<AminoAcid> aminoAcids,PrintWriter pw) { pw.println("Residue Name\tResidue Chain\tResidue Sequence\tSide Chain Angle\tValue"); for(AminoAcid aminoAcid :aminoAcids) { String residueName = aminoAcid.getrName(); //System.out.println(residueName); Map<String, Atom> atoms = aminoAcid.getAtoms(); for(Entry<String, Map<String, List<String>>> chi_atom_entry: TorsonialAnglesList.chi_atoms.entrySet()) { String angleName = chi_atom_entry.getKey(); if(chi_atom_entry.getValue().get(residueName) != null) { List<String> angleAtoms = chi_atom_entry.getValue().get(residueName); //System.out.println(angleName+", "+residueName); //System.out.println(atoms.get(angleAtoms.get(0))+","+atoms.get(angleAtoms.get(1))+","+atoms.get(angleAtoms.get(2))+","+atoms.get(angleAtoms.get(3))); Double torsionalAngle = Vector.getTorsionalAngle(atoms.get(angleAtoms.get(0)).getPosition(), atoms.get(angleAtoms.get(1)).getPosition(), atoms.get(angleAtoms.get(2)).getPosition(), atoms.get(angleAtoms.get(3)).getPosition()); pw.println(residueName+"\t"+aminoAcid.getrChain()+"\t"+aminoAcid.getrSequence()+"\t"+angleName+"\t"+torsionalAngle); } } } } /** * Mean. * * @param list the list * @return the double */ public static Double Mean(List<Double> list) { Double sum = 0d; for(Double d:list) { sum +=d; } return sum/list.size(); } /** * Sdv. * * @param list the list * @return the double */ public static Double SDV(List<Double> list) { double num=0.0; double deno = list.size() - 1; Double mean = Mean(list); for (Double d:list){ num+=Math.pow((d - mean),2); } return Math.sqrt(num/deno); } }
true
5940f9ad4ad67e22c40e8a915dc0f6020a732af9
Java
maite820/M09-cohete
/M09 cohetes fase 2/src/com/cohete/view/Uso_cohetes.java
UTF-8
1,146
3.0625
3
[]
no_license
package com.cohete.view; import com.cohete.domain.*; public class Uso_cohetes { public static void main(String[] args) { //FASE 2: // cohetes con sus codigos y numero de propulsores Cohete cohete1 = new Cohete("32WESSDS",3); Cohete cohete2 = new Cohete("LDSFJA32",6); //potencia propulsores int[] prop1= {10,30,80}; cohete1.setPotPropulsors(prop1); int[] prop2= {30,40,50,50,30,10}; cohete2.setPotPropulsors(prop2); //Mostrar codigos cohetes y propulsores.potencia maxima System.out.print(cohete1.getCode() + ": "); for (int i=0; i<cohete1.getPotPropulsors().length; i++){ System.out.print(cohete1.getPotPropulsors()[i]); if (i!=cohete1.getPotPropulsors().length-1) { System.out.print(","); } } System.out.println(); System.out.print(cohete2.getCode() + ": "); for (int i=0; i<cohete2.getPotPropulsors().length; i++){ System.out.print(cohete2.getPotPropulsors()[i]); if (i!=cohete2.getPotPropulsors().length-1) { System.out.print(","); } } } }
true
10de6dc0dfb63bcefc85b024398e1902b6597222
Java
themindfuldev/eai
/eai-cms/app/controllers/ControladorInicial.java
UTF-8
216
1.523438
2
[]
no_license
package controllers; import play.mvc.Result; import views.html.index; public class ControladorInicial extends ControladorMestre { public static Result index() { return ok(index.render(null)); } }
true
e81219dc915a76936aa16944df623234d05f6fdc
Java
apache/sling-org-apache-sling-engine
/src/main/java/org/apache/sling/engine/impl/log/RequestLoggerResponse.java
UTF-8
14,830
1.898438
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 org.apache.sling.engine.impl.log; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import javax.servlet.ServletOutputStream; import javax.servlet.WriteListener; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import org.apache.sling.engine.impl.helper.ClientAbortException; class RequestLoggerResponse extends HttpServletResponseWrapper { // the content type header name private static final String HEADER_CONTENT_TYPE = "Content-Type"; // the content length header name private static final String HEADER_CONTENT_LENGTH = "Content-Length"; /** format for RFC 1123 date string -- "Sun, 06 Nov 1994 08:49:37 GMT" */ private final static SimpleDateFormat RFC1123_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); /** * The counter for request gone through this filter. As this is the first * request level filter hit, this counter should actually count each request * which at least enters the request level component filter processing. * <p> * This counter is reset to zero, when this component is activated. That is, * each time this component is restarted (system start, bundle start, * reconfiguration), the request counter restarts at zero. */ private static AtomicLong requestCounter = new AtomicLong(); // TODO: more content related headers, namely Content-Language should // probably be supported // the request counter private long requestId; // the system time in ms when the request entered the system, this is // the time this instance was created private long requestStart; // the system time in ms when the request exited the system, this is // the time of the call to the requestEnd() method private long requestEnd; // the output stream wrapper providing the transferred byte count private LoggerResponseOutputStream out; // the print writer wrapper providing the transferred character count private LoggerResponseWriter writer; // the caches status private int status = SC_OK; // the cookies set during the request, indexed by cookie name private Map<String, Cookie> cookies; // the headers set during the request, indexed by lower-case header // name, value is string for single-valued and list for multi-valued // headers private Map<String, Object> headers; RequestLoggerResponse(HttpServletResponse response) { super(response); this.requestId = requestCounter.getAndIncrement(); this.requestStart = System.currentTimeMillis(); } /** * Called to indicate the request processing has ended. This method * currently sets the request end time returned by {@link #getRequestEnd()} * and which is used to calculate the request duration. */ void requestEnd() { this.requestEnd = System.currentTimeMillis(); } // ---------- SlingHttpServletResponse interface @Override public ServletOutputStream getOutputStream() throws IOException { if (this.out == null) { ServletOutputStream sos = super.getOutputStream(); this.out = new LoggerResponseOutputStream(sos); } return this.out; } @Override public PrintWriter getWriter() throws IOException { if (this.writer == null) { PrintWriter pw = super.getWriter(); this.writer = new LoggerResponseWriter(pw); } return this.writer; } // ---------- Error handling through Sling Error Resolver ----------------- @Override public void sendRedirect(String location) throws IOException { super.sendRedirect(location); // replicate the status code of call to base class this.status = SC_MOVED_TEMPORARILY; } @Override public void sendError(int status) throws IOException { super.sendError(status); this.status = status; } @Override public void sendError(int status, String message) throws IOException { super.sendError(status, message); this.status = status; } @Override public void setStatus(int status, String message) { super.setStatus(status, message); this.status = status; } @Override public void setStatus(int status) { super.setStatus(status); this.status = status; } @Override public void addCookie(Cookie cookie) { // register the cookie for later use if (this.cookies == null) { this.cookies = new HashMap<String, Cookie>(); } this.cookies.put(cookie.getName(), cookie); super.addCookie(cookie); } @Override public void addDateHeader(String name, long date) { this.registerHeader(name, toDateString(date), true); super.addDateHeader(name, date); } @Override public void addHeader(String name, String value) { this.registerHeader(name, value, true); super.addHeader(name, value); } @Override public void addIntHeader(String name, int value) { this.registerHeader(name, String.valueOf(value), true); super.addIntHeader(name, value); } @Override public void setContentLength(int len) { this.registerHeader(HEADER_CONTENT_LENGTH, String.valueOf(len), false); super.setContentLength(len); } @Override public void setContentType(String type) { // SLING-726 No handling required since this seems to be correct this.registerHeader(HEADER_CONTENT_TYPE, type, false); super.setContentType(type); } @Override public void setCharacterEncoding(String charset) { // SLING-726 Ignore call if getWriter() has been called if (writer == null) { super.setCharacterEncoding(charset); } } @Override public void setDateHeader(String name, long date) { this.registerHeader(name, toDateString(date), false); super.setDateHeader(name, date); } @Override public void setHeader(String name, String value) { this.registerHeader(name, value, false); super.setHeader(name, value); } @Override public void setIntHeader(String name, int value) { this.registerHeader(name, String.valueOf(value), false); this.setHeader(name, String.valueOf(value)); } @Override public void setLocale(Locale loc) { // TODO: Might want to register the Content-Language header super.setLocale(loc); } // ---------- Retrieving response information ------------------------------ public long getRequestId() { return this.requestId; } public long getRequestStart() { return this.requestStart; } public long getRequestEnd() { return this.requestEnd; } public long getRequestDuration() { return this.requestEnd - this.requestStart; } @Override public int getStatus() { return this.status; } public int getCount() { if (this.out != null) { return this.out.getCount(); } else if (this.writer != null) { return this.writer.getCount(); } // otherwise return zero return 0; } public Cookie getCookie(String name) { return (this.cookies != null) ? (Cookie) this.cookies.get(name) : null; } public String getHeadersString(String name) { // normalize header name to lower case to support case-insensitive // headers name = name.toLowerCase(); Object header = (this.headers != null) ? this.headers.get(name) : null; if (header == null) { return null; } else if (header instanceof String) { return (String) header; } else { StringBuilder headerBuf = new StringBuilder(); for (Iterator<?> hi = ((List<?>) header).iterator(); hi.hasNext();) { if (headerBuf.length() > 0) { headerBuf.append(","); } headerBuf.append(hi.next()); } return headerBuf.toString(); } } // ---------- Internal helper --------------------------------------------- /** * Stores the name header-value pair in the header map. The name is * converted to lower-case before using it as an index in the map. * * @param name The name of the header to register * @param value The value of the header to register * @param add If <code>true</code> the header value is added to the list of * potentially existing header values. Otherwise the new value * replaces any existing values. */ @SuppressWarnings("unchecked") private void registerHeader(String name, String value, boolean add) { // ensure the headers map if (this.headers == null) { this.headers = new HashMap<String, Object>(); } // normalize header name to lower case to support case-insensitive // headers name = name.toLowerCase(); // retrieve the current contents if adding, otherwise assume no current Object current = add ? this.headers.get(name) : null; if (current == null) { // set the single value (forced if !add) this.headers.put(name, value); } else if (current instanceof String) { // create list if a single value is already set List<String> list = new ArrayList<String>(); list.add((String) current); list.add(value); this.headers.put(name, list); } else { // append to the list of more than one already set ((List<Object>) current).add(value); } } /** * Converts the time value given as the number of milliseconds since January * 1, 1970 to a date and time string compliant with RFC 1123 date * specification. The resulting string is compliant with section 3.3.1, Full * Date, of <a href="http://www.faqs.org/rfcs/rfc2616.html">RFC 2616</a> and * may thus be used as the value of date header such as <code>Date</code>. * * @param date The date value to convert to a string * @return The string representation of the date and time value. */ public static String toDateString(long date) { synchronized (RFC1123_FORMAT) { return RFC1123_FORMAT.format(new Date(date)); } } // ---------- byte/character counting output channels ---------------------- // byte transfer counting ServletOutputStream private static class LoggerResponseOutputStream extends ServletOutputStream { private ServletOutputStream delegatee; private int count; LoggerResponseOutputStream(ServletOutputStream delegatee) { this.delegatee = delegatee; } public int getCount() { return this.count; } @Override public void write(int b) throws IOException { try { this.delegatee.write(b); this.count++; } catch(IOException ioe) { throw new ClientAbortException(ioe); } } @Override public void write(byte[] b) throws IOException { try { this.delegatee.write(b); this.count += b.length; } catch(IOException ioe) { throw new ClientAbortException(ioe); } } @Override public void write(byte[] b, int off, int len) throws IOException { try { this.delegatee.write(b, off, len); this.count += len; } catch(IOException ioe) { throw new ClientAbortException(ioe); } } @Override public void flush() throws IOException { try { this.delegatee.flush(); } catch(IOException ioe) { throw new ClientAbortException(ioe); } } @Override public void close() throws IOException { try { this.delegatee.close(); } catch(IOException ioe) { throw new ClientAbortException(ioe); } } @Override public boolean isReady() { return this.delegatee.isReady(); } @Override public void setWriteListener(final WriteListener writeListener) { this.delegatee.setWriteListener(writeListener); } } // character transfer counting PrintWriter private static class LoggerResponseWriter extends PrintWriter { private static final int LINE_SEPARATOR_LENGTH = System.getProperty("line.separator").length(); private int count; LoggerResponseWriter(PrintWriter delegatee) { super(delegatee); } public int getCount() { return this.count; } @Override public void write(int c) { super.write(c); this.count++; } @Override public void write(char[] buf, int off, int len) { super.write(buf, off, len); this.count += len; } @Override public void write(String s, int off, int len) { super.write(s, off, len); this.count += len; } @Override public void println() { super.println(); this.count += LINE_SEPARATOR_LENGTH; } } }
true
5bee49bd42656d94d848e6f940e717f8ffeb67f1
Java
sergotsevr/ArchivePlus
/src/main/java/com/example/demo/services/OperationTypeService.java
UTF-8
2,814
2.515625
3
[]
no_license
package com.example.demo.services; import com.example.demo.entities.OperationType; import com.example.demo.entities.OperationTypeDto; import com.example.demo.repositories.OperationTypeRepository; import com.example.demo.utils.Mapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.LinkedList; import java.util.List; import java.util.Optional; @Component public class OperationTypeService { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private OperationTypeRepository operationTypeRepository; public OperationTypeDto add(OperationTypeDto operationTypeDto) { try { OperationType operationType = Mapper.dtoToType(operationTypeDto); OperationType type = operationTypeRepository.save(operationType); OperationTypeDto operationTypeDtoBack = Mapper.typeToDto(type); return operationTypeDtoBack; } catch (Exception e) { logger.error("failed to create new OperationType with id={}", operationTypeDto.getOperationTypeId()); return null; } } public void delete(long id) { try { operationTypeRepository.deleteById(id); } catch (Exception e) { logger.error("Failed to delete OperationType with id={}", id); } } public List<OperationTypeDto> findAll() { List<OperationType> list = operationTypeRepository.findAll(); List<OperationTypeDto> listDto = new LinkedList<OperationTypeDto>(); for (OperationType operationType : list ) { listDto.add(Mapper.typeToDto(operationType)); } if (listDto.isEmpty()) { logger.warn("OperationType list is empty"); } return listDto; } public OperationTypeDto getById(Long operationTypeId) { Optional<OperationType> byId = operationTypeRepository.findById(operationTypeId); if (byId.isPresent()) { OperationType operationType = byId.get(); return Mapper.typeToDto(operationType); } logger.warn("No OperationStage with id={}", operationTypeId); return null; } public OperationTypeDto update(OperationTypeDto operationTypeDto) { try { OperationType operationType = Mapper.dtoToType(operationTypeDto); OperationType type = operationTypeRepository.save(operationType); return Mapper.typeToDto(type); } catch (Exception e) { logger.error("failed to update OperationType with id={} , operationTypeRepository={}", operationTypeDto.getOperationTypeId(), operationTypeRepository); return null; } } }
true
f5329aeeb972dc44ed374f5d42efcdeb5be07341
Java
pengshuai2010/practiceJava
/practiceJava/src/lintCode/Q140.java
UTF-8
1,510
3.640625
4
[]
no_license
package lintCode; public class Q140 { /* * Fast Power Show result * * 30:00 Start Calculate the an % b where a, b and n are all 32bit integers. * * Example For 231 % 3 = 2 * * For 1001000 % 1000 = 0 * * Challenge O(logn) */ /* * @param a, b, n: 32bit integers * * @return: An integer */ public int fastPower(int a, int b, int n) { // return (int) fPRecursion(a, b, n); return (int) fPIteration(a, b, n); } /* * a recusive solution */ public static long fPRecursion(int a, int b, int n) { if (n == 0) return 1 % b; if (n == 1) return a % b; if ((n & 1) == 1)// n is odd return (fPRecursion(a, b, n - 1) * fPRecursion(a, b, 1)) % b; else { long res = fPRecursion(a, b, n / 2); return (res * res) % b; } } /* * an iterative solution */ public static long fPIteration(int a, int b, int n) { int power = n; long value = a; long result = 1; while (power > 0) { if ((power & 1) == 1) { result *= value; result %= b; power--; } value *= value; value %= b; power >>= 1; } result %= b; return result; } public static void main(String[] args) { // int a = 2, b = 3, n = 31; // int a = 100, b = 1000, n = 1000; // pow(2,100)%1000000007 = 976371285 // int a = 2, b = 1000000007, n = 100; // 27123, 5201314, 78965412, expected out 842799 // int a = 27123, b = 5201314, n = 78965412; int a = 3, b = 1, n = 0; int res = new Q140().fastPower(a, b, n); System.out.println(res); } }
true
3e53c1b470c33df7717cb45bc8c6ed5d2be9f99b
Java
seokheecho/bigdata3
/bit-java01/src/main/java/step12/ex6/Truck.java
UTF-8
126
1.773438
2
[]
no_license
package step12.ex6; public class Truck extends Car { float ton; // 트럭의 적재량 boolean dump; // 덤프 여부 }
true
4f6b71ced6542fbb2558fa554c91ab93e573ddae
Java
MechaMonst3r/Data-Structures-Assignment-1
/Lab1/Lab1Exercise2/src/lab1exercise2/Rectangle2D.java
UTF-8
2,201
3.4375
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 lab1exercise2; /** * * @author work */ public class Rectangle2D { double xpos, ypos, width, height; public Rectangle2D() { xpos = 0.0; ypos = 0.0; width = 0.0; height = 0.0; } public Rectangle2D(double xpos, double ypos, double width, double height) { this.xpos = xpos; this.ypos = ypos; this.width = width; this.height = height; } public double getXpos() { return xpos; } public double getYpos() { return ypos; } public double getWidth() { return width; } public double getHeight() { return height; } public void setXpos(double xpos) { this.xpos = xpos; } public void setYpos(double ypos) { this.ypos = ypos; } public void setWidth(double width) { this.width = width; } public void setHeight(double height) { this.height = height; } public double getArea() { return width*height; } public double getPerimeter() { return 2*(width + height); } public boolean contains(double x, double y) { if(xpos <= x && x <= xpos + width && ypos <= y && y <= ypos + height) { return true; } return false; } public boolean contains(Rectangle2D r) { if(xpos <= r.getXpos() && r.getXpos() + r.getWidth() < (xpos + width) && ypos <= r.getYpos() && r.getYpos() + r.getHeight() < (ypos + height)) { return true; } return false; } public boolean overlaps(Rectangle2D r) { if(xpos < r.getXpos() + r.getWidth() && xpos + width > r.getXpos() && ypos < r.getYpos() + r.getHeight() && ypos + height > r.getYpos()) { return true; } return false; } }
true
400b56f4da7678b6a83666031611d8b4d7ec8c88
Java
kuldeep-singh-5894/KANG_E-Learning_System
/src/kang/com/Search_s.java
UTF-8
2,852
2.484375
2
[]
no_license
package kang.com; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/Search_s") public class Search_s extends HttpServlet { private static final long serialVersionUID = 1L; public Search_s() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<marquee> Welcome to our KANG E-learning System</marquee>"); out.println( "<body><h1 id='head'>Welcome to KANG E-learning System </br></br> <a href=professor.html> Go To Main Menu </a></h1>"); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"styles/view_s.css\">"); out.println("<form action=\"Search_s\" method=\"post\">"); out.println("<label style='font-size:25px; font-weight: 900;'> Search by Name :</label>"); out.println("<input style='padding: 5px;' type=\"text\" name=\"search\" value=\"\" id=\"search\" max=\"25\">"); out.println("<input type=\"submit\" value=\"Search\" style=\" padding: 5px; cursor: pointer;\">"); out.println("</form>"); out.println( "<a href=\"View_s\"><input type=\"text\" value=\"View All Student\" style=\" padding: 5px; cursor: pointer;\"></a>"); String search = request.getParameter("search"); String like = "%" + search + "%"; List<Student> list = KangDAO.getStudentsByName(like); out.print("<table>"); out.print( "<tr><th>Student ID</th><th>First Name</th><th>Last Name</th><th>Course</th><th>Gender</th><th>Date of Birth</th><th>Marital Status</th><th>Email</th><th>Phone_Number</th><th colspan=2>Edit/Delete</th></tr>"); for (Student s : list) { out.print("<tr><td>" + s.getUnm() + "</td><td>" + s.getFname() + "</td><td>" + s.getLname() + "</td><td>" + s.getCourse() + "</td><td>" + s.getGender() + "</td><td>" + s.getOdob() + "</td><td>" + s.getMs() + "</td><td>" + s.getEmail() + "</td><td>" + s.getPn() + "</td><td><a>Edit</a></td> <td><a href='Delete_s?id=" + s.getUnm() + "'>Delete</a></td></tr>"); } out.print("</table></body>"); out.print("<footer><a href='#top' class='sign_in' ><h2 id='btt'>Back to Top</h2></a>"); out.print("<h2>E-Learning System</h2><h2>Copyright&copy;by KANG Group #5 2020</h2></footer>"); out.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
true
19d9902c8cdec7f86b224937112226f03cad3b25
Java
qhq123/there-logic
/DbConnection.java
UTF-8
771
2.375
2
[]
no_license
package threelogic; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DbConnection { static Connection connection; DbConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); String url = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=GUPIAO;"; connection=DriverManager.getConnection(url,"sa","qhq15623282518"); /*Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); String url = "jdbc:sqlserver://rds.sqlserver.rds.aliyuncs.com:3433;DatabaseName=GUPIAO;"; connection=DriverManager.getConnection(url,"admin","qhq000402");*/ } }
true
0f57b9f8a31bd029b59005f51a2cea7a476ef25a
Java
argodev/BiLab
/BiLab/bilab_working/BiLab/src/uk/ac/sanger/artemis/editor/ExternalApplication.java
UTF-8
6,330
2.515625
3
[]
no_license
/* * * created: Wed Aug 3 2004 * * This file is part of Artemis * * Copyright(C) 2000 Genome Research Limited * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ package uk.ac.sanger.artemis.editor; import java.io.*; /** * * Used to run an external command and get the stdout * and stderr. * */ public class ExternalApplication { /** running process */ private Process p; /** standard out */ private StringBuffer stdout = new StringBuffer(); /** standard error */ private StringBuffer stderr = new StringBuffer(); /** running directory */ private File project; /** process status */ private String status; private StdoutHandler stdouth; private StderrHandler stderrh; /** * * @param cmd command to run * @param envp environment * @param project running directory * */ public ExternalApplication(String[] cmd, String[] envp, File project) { this.project = project; status = "0"; Runtime cmdRun = Runtime.getRuntime(); try { p = cmdRun.exec(cmd,envp,project); // 2 threads to read in stdout & stderr buffers // to prevent blocking stdouth = new StdoutHandler(this); stderrh = new StderrHandler(this); stdouth.start(); stderrh.start(); } catch(IOException ioe) { ioe.printStackTrace(); System.out.println("ExternalApplication Error executing: "+ cmd); status = "1"; } } /** * * Read in the process stderr. * */ private void readProcessStderr() { BufferedInputStream stderrStream = null; BufferedReader stderrRead = null; try { String line; stderrStream = new BufferedInputStream(p.getErrorStream()); stderrRead = new BufferedReader(new InputStreamReader(stderrStream)); char c[] = new char[100]; int nc = 0; while((nc = stderrRead.read(c,0,100)) != -1) stderr = stderr.append(new String(c,0,nc)); } catch (IOException io) { System.err.println("ExternalApplication: Error in "+ "collecting standard out"); } finally { try { if(stderrStream!=null) stderrStream.close(); } catch(IOException ioe) { System.err.println("ExternalApplication: Error closing stream"); } try { if(stderrRead!=null) stderrRead.close(); } catch(IOException ioe) { System.err.println("ExternalApplication: Error closing reader"); } } return; } /** * * Read in the process stdout. * */ private void readProcessStdout() { BufferedInputStream stdoutStream = null; BufferedReader stdoutRead = null; try { String line; stdoutStream = new BufferedInputStream(p.getInputStream()); stdoutRead = new BufferedReader(new InputStreamReader(stdoutStream)); char c[] = new char[100]; int nc = 0; String chunk; while((nc = stdoutRead.read(c,0,100)) != -1) { chunk = new String(c,0,nc); stdout = stdout.append(chunk); } } catch (IOException io) { System.err.println("ExternalApplication: Error in "+ "collecting standard out"); } finally { try { if(stdoutStream!=null) stdoutStream.close(); } catch(IOException ioe) { System.err.println("ExternalApplication: Error closing stream"); } try { if(stdoutRead!=null) stdoutRead.close(); } catch(IOException ioe) { System.err.println("ExternalApplication: Error closing reader"); } } return; } /** * * Get the stdout for the process. * @return standard out. * */ public String getProcessStdout() { try { // make sure we hang around for stdout while(stdouth.isAlive()) Thread.currentThread().sleep(10); } catch(InterruptedException ie) { ie.printStackTrace(); } return new String(stdout.toString().trim()); } /** * * Get the stderr for the process. * @return standard error. * */ public String getProcessStderr() { try { // make sure we hang around for stderr while(stderrh.isAlive()) Thread.currentThread().sleep(10); } catch(InterruptedException ie) { ie.printStackTrace(); } return new String(stderr.toString().trim()); } /** * * Wait for the process to end * */ public int waitFor() { try { return p.waitFor(); } catch(InterruptedException ie) { ie.printStackTrace(); } return -1; } /** * * @return process * */ public Process getProcess() { return p; } /** * * @return status * */ public String getStatus() { return status; } class StdoutHandler extends Thread { ExternalApplication rea; protected StdoutHandler(ExternalApplication rea) { this.rea = rea; } public void run() { rea.readProcessStdout(); } } class StderrHandler extends Thread { ExternalApplication rea; protected StderrHandler(ExternalApplication rea) { this.rea = rea; } public void run() { rea.readProcessStderr(); } } }
true
9179ebd5c91118e3a599beead3dcfc524698fd1e
Java
songtaehyeon1/Employment_Project
/itzProject/src/com/itzProject/home/myhome/CommandimgSave.java
UTF-8
1,593
2.171875
2
[]
no_license
package com.itzProject.home.myhome; import java.io.File; import java.io.IOException; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.itzProject.home.CommandService; import com.itzProject.home.DBConn; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.multipart.DefaultFileRenamePolicy; import com.sun.xml.internal.bind.v2.runtime.Location; public class CommandimgSave implements CommandService { public CommandimgSave() { // TODO Auto-generated constructor stub } @Override public String processStart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getServletContext().getRealPath("/myhome/resumePic"); int maxSize = 1024 * 1024 * 1024; DefaultFileRenamePolicy policy = new DefaultFileRenamePolicy(); MultipartRequest mr = new MultipartRequest(request, path, maxSize, "UTF-8", policy); File f = mr.getFile("file"); HttpSession ses = request.getSession(); String personno = (String)ses.getAttribute("personno"); String filename = f.getParent()+"/"+personno+".png"; File f2 = new File(filename); f.renameTo(f2); ResumeDAO dao = new ResumeDAO(); int result = dao.updatePic(Integer.parseInt(personno),personno+".png"); if(result <=0) { f.delete(); } request.setAttribute("filename", f2.getName()); request.setAttribute("result", result); return "/myhome/imgSaveOk.jsp"; } }
true
7a748acc7c3d4409439ce941ea29859081e5e597
Java
java-prolog-connectivity/jpc.examples
/src/main/java/org/jpc/examples/metro/model/hlapi/MetroHLApi.java
UTF-8
1,748
2.25
2
[]
no_license
package org.jpc.examples.metro.model.hlapi; import static java.util.Arrays.asList; import static org.jpc.engine.prolog.PrologEngines.getPrologEngine; import java.util.List; import org.jpc.Jpc; import org.jpc.JpcBuilder; import org.jpc.engine.logtalk.LogtalkObject; import org.jpc.engine.prolog.PrologEngine; import org.jpc.examples.metro.model.Line; import org.jpc.examples.metro.model.Metro; import org.jpc.examples.metro.model.hlapi.converters.LineConverter; import org.jpc.examples.metro.model.hlapi.converters.MetroConverter; import org.jpc.examples.metro.model.hlapi.converters.StationConverter; import org.jpc.query.Query; import org.jpc.term.Atom; import org.jpc.term.Compound; import org.jpc.term.Term; import org.jpc.term.Var; public class MetroHLApi implements Metro { public static final Jpc jpcContext = JpcBuilder.create() .register(new MetroConverter()) .register(new LineConverter()) .register(new StationConverter()).build(); private final PrologEngine prologEngine; public MetroHLApi() { prologEngine = getPrologEngine(getClass()); } @Override public String toString() {return "metro";} private LogtalkObject<Atom> asLogtalkObject() { return new LogtalkObject<>(this, prologEngine, jpcContext); } @Override public List<Line> lines() { String lineVarName = "Line"; Term message = new Compound(LineConverter.LINE_FUNCTOR_NAME, asList(new Var(lineVarName))); Query query = asLogtalkObject().perform(message); return query.<Line>selectObject().allSolutions(); } @Override public Line line(String name) { Term message = new Compound(LineConverter.LINE_FUNCTOR_NAME, asList(new Atom(name))); return asLogtalkObject().perform(message).<Line>selectObject().oneSolutionOrThrow(); } }
true
e3b95b7c135f2427bda59b0f87e3462ed9be0311
Java
liuyang0923/joycool
/WEB-INF/src/net/joycool/wap/bean/friend/FriendLevelBean.java
UTF-8
1,504
2.109375
2
[]
no_license
package net.joycool.wap.bean.friend; public class FriendLevelBean { int id; int fromId; int toId; int levelValue; String updateDatetime; String createDatetime; /** * @return Returns the createDatetime. */ public String getCreateDatetime() { return createDatetime; } /** * @param createDatetime The createDatetime to set. */ public void setCreateDatetime(String createDatetime) { this.createDatetime = createDatetime; } /** * @return Returns the fromId. */ public int getFromId() { return fromId; } /** * @param fromId The fromId to set. */ public void setFromId(int fromId) { this.fromId = fromId; } /** * @return Returns the id. */ public int getId() { return id; } /** * @param id The id to set. */ public void setId(int id) { this.id = id; } /** * @return Returns the levelValue. */ public int getLevelValue() { return levelValue; } /** * @param levelValue The levelValue to set. */ public void setLevelValue(int levelValue) { this.levelValue = levelValue; } /** * @return Returns the toId. */ public int getToId() { return toId; } /** * @param toId The toId to set. */ public void setToId(int toId) { this.toId = toId; } /** * @return Returns the updateDatetime. */ public String getUpdateDatetime() { return updateDatetime; } /** * @param updateDatetime The updateDatetime to set. */ public void setUpdateDatetime(String updateDatetime) { this.updateDatetime = updateDatetime; } }
true
f05b0c506e504cb775d978d6fa2e3a04ff8248e8
Java
Arathi/OpenGameDev
/src/org/beh/gamedev/Employee.java
UTF-8
3,552
2.578125
3
[]
no_license
package org.beh.gamedev; public class Employee { public static final int JOBTITLE_PROGRAMER = 0; public static final int JOBTITLE_WRITER = 1; public static final int JOBTITLE_DESIGNER = 2; public static final int JOBTITLE_SOUND_ENG = 3; public static final int JOBTITLE_DIRECT = 4; public static final int JOBTITLE_PRODUCE = 5; public static final int JOBTITLE_HARD_ENG = 6; public static final int JOBTITLE_HACK = 7; public static final int PROPERTY_PROGRAM = 0; public static final int PROPERTY_SCENARIO = 1; public static final int PROPERTY_GRAPHICS = 2; public static final int PROPERTY_SOUND = 3; int id; String name; String nickname; int job; //当前职称 int[] propertys; //4项基本属性 int[] skillLevels; //8种职业技能级别 int power; int powerMax; int salary; //薪水 int contract; //合约金 String desc; //招聘简介 int efficiency; //工作效率 int rank; //招聘分类 int talent; //天赋职业 Company company; //所属公司 @Deprecated public Employee(){ int[] skillLevels = {1, 0, 0, 0, 0, 0, 0, 0}; int[] propertys = {4, 3, 2, 1}; init(0, "Arathi", "A酱", JOBTITLE_PROGRAMER, propertys, skillLevels, 64); } public Employee(String csv){ String[] csvStr = Util.CsvSpliter(csv); int[] csvInt; int i; if (csvStr.length!=Constant.CSV_VALUE_AMOUNT){ id = -1; return; } csvInt = new int[Constant.CSV_VALUE_AMOUNT]; for (i=0; i<Constant.CSV_VALUE_AMOUNT; i++){ if (csvStr[i].startsWith("\"") && csvStr[i].endsWith("\"")){ csvInt[i] = 0; csvStr[i] = csvStr[i].substring(1, csvStr[i].length()-1); } else{ csvInt[i] = Integer.parseInt(csvStr[i]); } } propertys = new int[4]; skillLevels = new int[8]; //================ id = csvInt[0]; //TODO csvInt[1] 均为0 name = csvStr[2]; nickname = csvStr[3]; //TODO csvInt[4]; //TODO csvInt[5]; rank = csvInt[6]; salary = csvInt[7]; contract = csvInt[8]; efficiency = csvInt[9]; power = powerMax = csvInt[10]; for (i=0; i<4; i++){ propertys[i] = csvInt[11+i]; //11~14 } //TODO csvInt[15]; job = csvInt[16]; talent = csvInt[17]; for (i=0; i<8; i++){ skillLevels[i] = csvInt[18+i]; //18~25 } desc = csvStr[26]; } @Deprecated public void init(int id, String name, String nick, int job, int[] propertys, int[] skillLevels, int health){ this.name = name; this.nickname = nick; this.job = job; this.propertys = propertys; this.skillLevels = skillLevels; this.power = this.powerMax = health; } public void levelUp(){ if (company==null) return; if (skillLevels[job]>=Constant.SKILL_MAX_LEVEL) return; //TODO 扣除研究点数 //company.costTechPoint(); //TODO 增加属性点 //propertys[0]+=config.[][]; //TODO 增加薪水 //salary+=; //TODO 等级提升 skillLevels[job]++; } public void checkIn(Company company){ if (company==null) return; //TODO 扣除合约金 //company.costMoney(); this.company = company; } public void resign(){ //TODO company相关的清理 this.company = null; } @Override public String toString(){ String info="No." + id + " " + name + "("+nickname+")\n"; info += "体力:" + power + "/" + powerMax + "\n"; int i; info += "职称:" + job; info += "属性:"; for (i=0; i<4; i++){ if (i!=0) info += ","; info += propertys[i]; } info += "年薪:" + salary + "\n"; return info; } }
true
80b5e0b57e454597be73d19490c3d71584e0a50f
Java
s-nisha/CustomerMgmt
/src/main/java/com/task/customer/dao/ICustomerDAO.java
UTF-8
255
1.9375
2
[]
no_license
package com.task.customer.dao; import com.task.customer.entities.Customer; public interface ICustomerDAO { public Customer add(Customer customer); public Customer findByID(long customerID); public Customer update(Customer customer); }
true
d2cbf6a45fe0e763a94c100fcfccb69dc360ce8f
Java
pipipan/CycleFun
/app/src/main/java/jsp/activity/RoutesActivity.java
UTF-8
970
2.09375
2
[]
no_license
package jsp.activity; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.widget.ArrayAdapter; import android.widget.ListView; public class RoutesActivity extends Activity { public static String[] recommendationsArray = {"Santa Clara --> Mountain View", "Palo Alto --> Milpitals", "Cupertino --> San Jose", "San Jose --> San Francisco", "Fremont --> Redwood City"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.recommendation); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title); ArrayAdapter adaptor = new ArrayAdapter<String>(this, R.layout.profile_listview, recommendationsArray); ListView listView = (ListView) findViewById(R.id.recommendationsListView); listView.setAdapter(adaptor); } }
true
2fc09cb840b5a28dafaeb99cd088251800ace744
Java
deiz123/demo-store
/src/main/java/com/pnrpu/store/service/OrderItemService.java
UTF-8
192
1.679688
2
[]
no_license
package com.pnrpu.store.service; import com.pnrpu.store.persistence.entity.OrderItem; import java.util.List; public interface OrderItemService { void saveAll(List<OrderItem> orders); }
true
e244005f327f387c9d893b693b058adb0e970fdb
Java
vehpsr/VkMusicCrawler
/crawler-logic/src/main/java/com/gans/vk/logic/service/LogicService.java
UTF-8
1,018
1.914063
2
[]
no_license
package com.gans.vk.logic.service; import java.util.List; import java.util.Map.Entry; import com.gans.vk.data.AudioLibrary; import com.gans.vk.data.RecommendedArtistsData; import com.gans.vk.logic.processor.AudioProcessor; import com.google.common.collect.Multimap; public interface LogicService { AudioLibrary getWhiteList(); AudioLibrary getBlackList(); List<AudioProcessor> getProcessors(); List<String> getAllAudioFiles(); void save(List<String> statistics); AudioLibrary getLibrary(String file); List<Entry<String, Double>> getAggregatedMetricData(Multimap<String, Entry<AudioProcessor, Number>> metrics); List<RecommendedArtistsData> recommendedWhiteListArtists(List<Entry<String, Double>> aggregatedData); List<RecommendedArtistsData> recommendedBlackListArtists(List<Entry<String, Double>> aggregatedData); List<RecommendedArtistsData> recommendedBlackWithoutWhiteListArtists(List<Entry<String, Double>> aggregatedData); }
true
73c59b277c715e7d71b9c41279099831c8be8d82
Java
apache/geode
/geode-core/src/integrationTest/java/org/apache/geode/internal/process/PidFileIntegrationTest.java
UTF-8
6,121
2.234375
2
[ "BSD-3-Clause", "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-unknown" ]
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 org.apache.geode.internal.process; import static org.apache.geode.internal.process.ProcessUtils.identifyPid; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.File; import java.io.FileNotFoundException; import java.nio.charset.Charset; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.apache.geode.internal.process.lang.AvailablePid; /** * Functional integration tests for {@link PidFile}. * * @since GemFire 8.2 */ public class PidFileIntegrationTest { private File directory; private File pidFile; private String pidFileName; private int pid; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Before public void before() throws Exception { directory = temporaryFolder.getRoot(); pidFile = new File(directory, "pid.txt"); pidFileName = pidFile.getName(); pid = identifyPid(); } @Test public void readsIntFromFile() throws Exception { // arrange String value = "42"; FileUtils.writeStringToFile(pidFile, value, Charset.defaultCharset()); // act int readValue = new PidFile(pidFile).readPid(); // assert assertThat(readValue).isEqualTo(Integer.parseInt(value)); } @Test public void readingEmptyFileThrowsIllegalArgumentException() throws Exception { // arrange FileUtils.writeStringToFile(pidFile, "", Charset.defaultCharset()); // act/assert assertThatThrownBy(() -> new PidFile(pidFile).readPid()) .isInstanceOf(IllegalArgumentException.class); } @Test public void readingFileWithNonIntegerThrowsIllegalArgumentException() throws Exception { // arrange String value = "forty two"; FileUtils.writeStringToFile(pidFile, value, Charset.defaultCharset()); // act/assert assertThatThrownBy(() -> new PidFile(pidFile).readPid()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Invalid pid '" + value + "' found"); } @Test public void readingFileWithNegativeIntegerThrowsIllegalArgumentException() throws Exception { // arrange String value = "-42"; FileUtils.writeStringToFile(pidFile, value, Charset.defaultCharset()); // act/assert assertThatThrownBy(() -> new PidFile(pidFile).readPid()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Invalid pid '" + value + "' found"); } @Test public void readingNullFileThrowsNullPointerException() throws Exception { // arrange pidFile = null; // act/assert assertThatThrownBy(() -> new PidFile(pidFile).readPid()) .isInstanceOf(NullPointerException.class); } @Test public void findsCorrectFileByName() throws Exception { // arrange FileUtils.writeStringToFile(pidFile, String.valueOf(pid), Charset.defaultCharset()); int[] pids = new AvailablePid().findAvailablePids(4); for (int i = 1; i <= pids.length; i++) { FileUtils.writeStringToFile( new File(directory, "pid" + i + ".txt"), String.valueOf(pids[i - 1]), Charset.defaultCharset()); } assertThat(directory.listFiles()).hasSize(pids.length + 1); // act PidFile namedPidFile = new PidFile(directory, pidFile.getName()); // assert assertThat(namedPidFile.getFile()).hasContent(String.valueOf(pid)); assertThat(namedPidFile.readPid()).isEqualTo(pid); } @Test public void missingFileInEmptyDirectoryThrowsFileNotFoundException() throws Exception { // arrange assertThat(pidFile).doesNotExist(); // act/assert assertThatThrownBy(() -> new PidFile(directory, pidFileName).readPid()) .isInstanceOf(FileNotFoundException.class).hasMessage( "Unable to find PID file '" + pidFileName + "' in directory '" + directory + "'"); } @Test public void fileForDirectoryThrowsIllegalArgumentException() throws Exception { // arrange File directoryIsFile = temporaryFolder.newFile("my.file"); // act/assert assertThatThrownBy(() -> new PidFile(directoryIsFile, pidFileName).readPid()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Nonexistent directory '" + directoryIsFile + "' specified"); } @Test public void missingFileThrowsFileNotFoundException() throws Exception { // act/assert assertThatThrownBy(() -> new PidFile(pidFile).readPid()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Nonexistent file '" + pidFile + "' specified"); } @Test public void missingFileInFullDirectoryThrowsFileNotFoundException() throws Exception { // arrange int[] pids = new AvailablePid().findAvailablePids(4); for (int i = 1; i <= pids.length; i++) { FileUtils.writeStringToFile( new File(directory, "pid" + i + ".txt"), String.valueOf(pids[i - 1]), Charset.defaultCharset()); } assertThat(directory.listFiles()).hasSameSizeAs(pids); // act/assert assertThatThrownBy(() -> new PidFile(directory, pidFileName).readPid()) .isInstanceOf(FileNotFoundException.class).hasMessage( "Unable to find PID file '" + pidFileName + "' in directory '" + directory + "'"); } }
true
cdbed7b3337037fd0ab4334f946e07aa8a778198
Java
kylesyx/online-test-server
/src/main/java/com/ks_xlm/dao/UserDao.java
UTF-8
543
1.929688
2
[]
no_license
package com.ks_xlm.dao; import com.ks_xlm.entity.User; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; import java.util.List; /* 注册用户接口 */ @Repository //@Mapper public interface UserDao { //用户注册增加 void userAdd(User user); //用户信息修改 void userUpdate(User user); //用户列表查询 User userSelect(String username); //String userVerify(User user); }
true
dd26bec7723a6b735060d03c68ecec43394dd049
Java
386959653/backwordframework
/p2p-core/src/main/java/com/pds/p2p/core/fastjson/FastJsonUtils.java
UTF-8
281
1.820313
2
[]
no_license
package com.pds.p2p.core.fastjson; import com.alibaba.fastjson.JSON; public class FastJsonUtils { public static <T> T parse(String text, String handleUnknown, Class<T> cls) { return JSON.parseObject(text, cls, new HandleUnknownExtraProcessor(handleUnknown)); } }
true
37131b846f291387d95cbb8e50cc1836ea8340e5
Java
subramanyamg2198/selenium
/Selenium/src/Gmail.java
UTF-8
1,086
2.046875
2
[]
no_license
import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.*; public class Gmail { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", ".\\software\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get( "https://accounts.google.com/signin/v2/identifier?service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ss=1&scc=1&ltmpl=default&ltmplcache=2&emr=1&osid=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin"); // driver.findElement(By.id("identifierId")).sendKeys("Rocky"); // driver.findElement(By.id("identifierId")).click(); driver.findElement(By.id("identifierId")).sendKeys("Rocky", Keys.ENTER); driver.findElement(By.id("Email")).click(); Thread.sleep(2000); driver.findElement(By.name("password")).sendKeys("since 1998", Keys.ENTER); } }
true
3849b38b2b6a4c1cb1b92d63a9bd21ea248192a8
Java
djingwu/hybrid-development
/clbs/src/main/java/com/zw/platform/controller/core/CustomColumnController.java
UTF-8
5,666
2.0625
2
[ "MIT" ]
permissive
package com.zw.platform.controller.core; import com.alibaba.fastjson.JSON; import com.zw.adas.utils.controller.AdasControllerTemplate; import com.zw.platform.service.core.CustomColumnService; import com.zw.platform.util.GetIpAddr; import com.zw.platform.util.StrUtil; import com.zw.platform.util.common.AvoidRepeatSubmitToken; import com.zw.platform.util.common.JsonResultBean; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; 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.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map; /** * 定制列controller * @author zhouzongbo on 2019/3/11 14:36 */ @Controller @RequestMapping("/core/uum/custom/") public class CustomColumnController { private static final Logger logger = LogManager.getLogger(CustomColumnController.class); private static final String CUSTOM_COLUMN_SETTING_PAGE = "/core/uum/custom/setting"; private static final String CUSTOM_COLUMN_TRACKPLAY_SETTING_PAGE = "/core/uum/custom/trackPlaySetting"; private static final String CUSTOM_COLUMN_MULTI_WINDOW_SETTING_PAGE = "/core/uum/custom/multiWindowSetting"; private static final String ERROR_PAGE = "html/errors/error_exception"; @Value("${sys.error.msg}") private String sysErrorMsg; @Autowired private CustomColumnService customColumnService; /** * 获取自定列设置页面 * @param columnModule 功能点标识: 如实时监控: REALTIME_MONITORING * @return */ @AvoidRepeatSubmitToken(setToken = true) @RequestMapping(value = "/setting_{columnModule}", method = RequestMethod.GET) public ModelAndView getCustomColumnSettingPage(@PathVariable("columnModule") String columnModule) { try { ModelAndView modelAndView = new ModelAndView(getViewName(columnModule)); List<Map<String, Object>> resultList = customColumnService.findCustomColumnModule(columnModule); modelAndView.addObject("resultList", JSON.toJSONString(resultList)); return modelAndView; } catch (Exception e) { logger.error("获取自定列设置页面错误", e); return new ModelAndView(ERROR_PAGE); } } @RequestMapping(value = "/getSettingByColumnModule", method = RequestMethod.POST) @ResponseBody public JsonResultBean getSettingByColumnModule(String columnModule) { return AdasControllerTemplate .getResultBean(() -> customColumnService.findCustomColumnModule(columnModule), "获取自定列设置页面错误"); } private String getViewName(String columnModule) { String viewName = ""; switch (columnModule) { case "REALTIME_MONITORING": viewName = CUSTOM_COLUMN_SETTING_PAGE; break; case "TRACKPLAY": viewName = CUSTOM_COLUMN_TRACKPLAY_SETTING_PAGE; break; case "MULTI_WINDOW_REALTIME_MONITORING": viewName = CUSTOM_COLUMN_MULTI_WINDOW_SETTING_PAGE; break; default: break; } return viewName; } /** * 添加绑定关系 * @param request request * @param customColumnConfigJson customColumnConfigJson * @param title 用于打印日志 * @return JsonResultBean */ @RequestMapping(value = "/addCustomColumnConfig", method = RequestMethod.POST) @ResponseBody public JsonResultBean addCustomColumnConfig(HttpServletRequest request, String customColumnConfigJson, String title) { try { if (StrUtil.areNotBlank(customColumnConfigJson, title)) { String ipAddress = new GetIpAddr().getIpAddr(request); return customColumnService.addCustomColumnConfig(customColumnConfigJson, title, ipAddress); } else { return new JsonResultBean(JsonResultBean.FAULT, sysErrorMsg); } } catch (Exception e) { logger.error("添加用户自定义列绑定关系异常", e); return new JsonResultBean(JsonResultBean.FAULT, sysErrorMsg); } } /** * 查询自定义类数据 * @return */ @RequestMapping(value = "/findCustomColumnInfoByMark", method = RequestMethod.POST) @ResponseBody public JsonResultBean findCustomColumnInfoByMark(String marks) { try { if (StringUtils.isNotEmpty(marks)) { return customColumnService.findCustomColumnInfoByMark(marks); } return new JsonResultBean(JsonResultBean.FAULT); } catch (Exception e) { logger.error("查询用户自定义列失败"); return new JsonResultBean(JsonResultBean.FAULT); } } @RequestMapping(value = "/deleteUserMarkColumn", method = RequestMethod.POST) @ResponseBody public JsonResultBean deleteUserMarkColumn(String columnId, String mark) { return AdasControllerTemplate .getResultBean(() -> customColumnService.deleteUserMarkColumn(columnId, mark), "删除用户模块定制列异常"); } }
true
f3d02f1b11350eee9f5c8ddcfc851f8df5c9f690
Java
LeyiliKeang/MySniffer
/src/com/leyilikeang/common/example/CreateTcpPacketExample.java
UTF-8
1,202
2.453125
2
[]
no_license
package com.leyilikeang.common.example; import org.jnetpcap.packet.JMemoryPacket; import org.jnetpcap.packet.JPacket; import org.jnetpcap.protocol.JProtocol; import org.jnetpcap.protocol.lan.Ethernet; import org.jnetpcap.protocol.network.Ip4; import org.jnetpcap.protocol.tcpip.Tcp; /** * @author likang * @date 2018/9/8 14:18 * <p> * 示例:创建一个TCP数据包 */ public class CreateTcpPacketExample { public static void main(String[] args) { JPacket packet = new JMemoryPacket(JProtocol.ETHERNET_ID, " 001801bf 6adc0025 4bb7afec 08004500 " + " 0041a983 40004006 d69ac0a8 00342f8c " + " ca30c3ef 008f2e80 11f52ea8 4b578018 " + " ffffa6ea 00000101 080a152e ef03002a " + " 2c943538 322e3430 204e4f4f 500d0a"); Ip4 ip = packet.getHeader(new Ip4()); Tcp tcp = packet.getHeader(new Tcp()); tcp.destination(80); ip.checksum(ip.calculateChecksum()); tcp.checksum(tcp.calculateChecksum()); packet.scan(Ethernet.ID); System.out.println(packet.toString()); System.out.println(packet.toHexdump()); } }
true
9f618399014abe3f8da1ccbc1aef61f3c22e600c
Java
Agorapps/POSTJSON
/app/src/main/java/prueba/envioxml/alvaro/postjson/MainActivity.java
UTF-8
18,919
1.859375
2
[]
no_license
package prueba.envioxml.alvaro.postjson; import java.io.File; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.security.KeyStore; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.TimeZone; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.message.BasicNameValuePair; import android.widget.ProgressBar; import android.support.v7.app.ActionBarActivity; public class MainActivity extends ActionBarActivity implements OnClickListener { private EditText value, etid; private TextView etmd5, tv_files; private Button btn; private ProgressBar pb; private static final String LOGTAG = "LogsAndroid"; private ImageView img, img2; String strBase64; String strBase642; String strBase643; String strBase644, strBaseVideo, path; int num_img = 0, itemCount; String s, recibido,nameItem, address, youFilePathVideo, youFilePath, youFilePath2, youFilePath3, youFilePath4; String responseBody; //First We Declare Titles And Icons For Our Navigation Drawer List View //This Icons And Titles Are holded in an Array as you can see @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); value = (EditText) findViewById(R.id.editText1); etid = (EditText) findViewById(R.id.etid); etmd5 = (TextView) findViewById(R.id.etmd5); tv_files = (TextView) findViewById(R.id.tv_files); btn = (Button) findViewById(R.id.button1); pb = (ProgressBar) findViewById(R.id.progressBar1); pb.setVisibility(View.GONE); btn.setOnClickListener(this); img = (ImageView) findViewById(R.id.img); img2 = (ImageView) findViewById(R.id.img2); //get id WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo info = manager.getConnectionInfo(); address = info.getMacAddress(); Log.i(LOGTAG, "dispositivito2 " + address); } public void onClick (View v) { // TODO Auto-generated method stub if (value.getText().toString().length() < 1) { //out of range Toast.makeText(this, "Please enter something", Toast.LENGTH_LONG).show(); } else { pb.setVisibility(View.VISIBLE); new MyAsyncTask().execute(value.getText().toString()); } } private class MyAsyncTask extends AsyncTask<String, Integer, Double> { @Override protected Double doInBackground (String... params) { //String datos = value.getText().toString(); // Create a new HttpClient and Post Header HttpClient httpClient = getNewHttpClient(); HttpPost httppost = new HttpPost("https://3isgestion.com/caronte/admin/scripts/recibirinfracciontabletPruebas/4c74032c271a/12"); try { //base64 image //convertimos byteArray /*img.buildDrawingCache(); Bitmap image2 = img.getDrawingCache(); ByteArrayOutputStream stream2 = new ByteArrayOutputStream(); image2.compress(Bitmap.CompressFormat.PNG, 100, stream2); byte[] food2 = stream2.toByteArray(); String str = new String(food2, "UTF-8");*/ //pasamos byteArray to Base64 String youFilePath = Environment.getExternalStorageDirectory() + "/proyectoCaronte/foto1.png"; /* Bitmap selectedImage = BitmapFactory.decodeFile(youFilePath); ByteArrayOutputStream stream = new ByteArrayOutputStream(); selectedImage.compress(Bitmap.CompressFormat.JPEG, 85, stream); byte[] byteArray = stream.toByteArray(); strBase64 = Base64.encodeToString(byteArray, 0); Log.i(LOGTAG, "pasamos b64 img1");*/ youFilePath2 = Environment.getExternalStorageDirectory() + "/proyectoCaronte/foto2.png"; /*Bitmap selectedImage2 = BitmapFactory.decodeFile(youFilePath2); ByteArrayOutputStream strea = new ByteArrayOutputStream(); selectedImage2.compress(Bitmap.CompressFormat.JPEG, 85, strea); byte[] byteArray2 = strea.toByteArray(); strBase642 = Base64.encodeToString(byteArray2, 0); Log.i(LOGTAG, "pasamos b64 img2");*/ youFilePath3 = Environment.getExternalStorageDirectory() + "/proyectoCaronte/foto3.png"; /*Bitmap selectedImage3 = BitmapFactory.decodeFile(youFilePath3); ByteArrayOutputStream stream3 = new ByteArrayOutputStream(); selectedImage3.compress(Bitmap.CompressFormat.JPEG, 85, stream3); byte[] byteArray3 = stream3.toByteArray(); strBase643 = Base64.encodeToString(byteArray3, 0); Log.i(LOGTAG, "pasamos b64 img3"); */ youFilePath4 = Environment.getExternalStorageDirectory() + "/proyectoCaronte/foto4.png"; //get Image4 /*Bitmap selectedImage4 = BitmapFactory.decodeFile(youFilePath4); ByteArrayOutputStream stream4 = new ByteArrayOutputStream(); selectedImage4.compress(Bitmap.CompressFormat.JPEG, 80, stream4); byte[] byteArray4 = stream4.toByteArray(); strBase644 = Base64.encodeToString(byteArray4, 0); Log.i(LOGTAG, "pasamos b64 img4");*/ //get Video youFilePathVideo = Environment.getExternalStorageDirectory() + "/proyectoCaronte/video.mp4"; //File file = new File(youFilePathVideo); //byte[] fileData = new byte[(int) file.length()]; /*DataInputStream dis = new DataInputStream(new FileInputStream(file)); dis.readFully(fileData); dis.close();*/ //strBaseVideo=Base64.encodeToString(buffer, 0); /*File file = new File(youFilePathVideo); FileInputStream fis = new FileInputStream(file); //System.out.println(file.exists() + "!!"); //InputStream in = resource.openStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[1000000]; try { for (int readNum; (readNum = fis.read(buf)) != -1;) { bos.write(buf, 0, readNum); //no doubt here is 0 //Writes len bytes from the specified byte array starting at offset off to this byte array output stream. } } catch (IOException ex) { } byte[] bytes = bos.toByteArray();*/ //below is the different part /*File someFile = new File("video2_"+youFilePathVideo); FileOutputStream fos = new FileOutputStream(someFile); fos.write(bytes); fos.flush(); fos.close();*/ //strBaseVideo=Base64.encodeToString(bytes, 0); /*JSONObject imagenes = new JSONObject(); try { imagenes.put("img1.png", strBase64); imagenes.put("img2.png", strBase642); imagenes.put("img3.png", strBase643); imagenes.put("img4.png", strBase644); imagenes.put("video.mp4", strBaseVideo); Log.i(LOGTAG, "Guardamos Array imagenes y video"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } JSONArray jsonArray = new JSONArray(); jsonArray.put(imagenes);*/ /*JSONObject ImagenesObj = new JSONObject(); try { ImagenesObj.put("Imagenes", jsonArray); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ //String jsonStr = ImagenesObj.toString(); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+1:00")); Date currentLocalTime = cal.getTime(); DateFormat date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); date.setTimeZone(TimeZone.getTimeZone("GMT+1:00")); String localTime = date.format(currentLocalTime); Log.i(LOGTAG, "folio " + localTime); // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //nameValuePairs.add(new BasicNameValuePair("imagenes", imagenes.toString())); nameValuePairs.add(new BasicNameValuePair("hora_infra", "15/02/2015 13:06:23")); nameValuePairs.add(new BasicNameValuePair("tipo_infra", "2")); nameValuePairs.add(new BasicNameValuePair("dni_infra", "76038672T")); nameValuePairs.add(new BasicNameValuePair("nombre_infra", "Antonio")); nameValuePairs.add(new BasicNameValuePair("apellido_infra", "García Pérez")); nameValuePairs.add(new BasicNameValuePair("sexo", "M")); nameValuePairs.add(new BasicNameValuePair("fecha_nacimiento", "15/02/1992")); nameValuePairs.add(new BasicNameValuePair("nacionalidad", "Española")); nameValuePairs.add(new BasicNameValuePair("validez_dni", "27/02/2019")); nameValuePairs.add(new BasicNameValuePair("provincia_infra", "Cáceres")); nameValuePairs.add(new BasicNameValuePair("matricula", "1478BBF")); nameValuePairs.add(new BasicNameValuePair("tipo_vehiculo", "1")); nameValuePairs.add(new BasicNameValuePair("marca", "Toyota")); nameValuePairs.add(new BasicNameValuePair("color", "Rojo")); nameValuePairs.add(new BasicNameValuePair("modelo", "Avensis")); nameValuePairs.add(new BasicNameValuePair("observaciones", "El usuario se nego a pagar la multa.")); nameValuePairs.add(new BasicNameValuePair("fecha_envio", localTime)); //UrlEncodedFormEntity uefe=new UrlEncodedFormEntity(nameValuePairs); //httppost.setEntity(uefe); //arrayList con los ficheros MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); path = Environment.getExternalStorageDirectory().toString() + "/proyectoCaronte"; File f = new File(path); File file[] = f.listFiles(); ArrayList<File> files = new ArrayList<File>(); ArrayList<File> fileordenado = new ArrayList<File>(); for (int i=0; i<file.length; i++){ files.add(file[i]); } while(!files.isEmpty()) { File filemenor = files.get(0); for (File archivo : files) { if( archivo.getName().compareTo(filemenor.getName()) < 0) { filemenor = archivo; } } fileordenado.add(filemenor); files.remove(filemenor); Log.i(LOGTAG,"FileMenor" + filemenor); } Log.i(LOGTAG,"FileOrdenado" + fileordenado); for (int i = 0; i < file.length; i++) { String nameItem = fileordenado.get(i).getName(); switch (nameItem){ case "foto1.png": builder.addPart("imagenes[]", new FileBody(new File(youFilePath))); break; case "foto2.png": builder.addPart("imagenes[]", new FileBody(new File(youFilePath2))); break; case "foto3.png": builder.addPart("imagenes[]", new FileBody(new File(youFilePath3))); break; case "foto4.png": builder.addPart("imagenes[]", new FileBody(new File(youFilePath4))); break; case "video.mp4": builder.addPart("imagenes[]", new FileBody(new File(youFilePathVideo))); break; default: } } builder.addTextBody("response", "prueba"); HttpEntity entity = builder.build(); httppost.setEntity(entity); // Execute HTTP Post Request HttpResponse response = httpClient.execute(httppost); responseBody = EntityUtils.toString(response.getEntity()); try { JSONObject jresponse = new JSONObject(responseBody); recibido = jresponse.getString("1"); Log.i(LOGTAG, "folio " + recibido); /*public void onResponse(JSONArray response) { List<Contact> result = new ArrayList<Contact>(); for (int i = 0; i < response.length(); i++) { try { result.add(convertContact(response .getJSONObject(i))); } catch (JSONException e) { } }*/ } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.i(LOGTAG, "pruebita"); Log.i(LOGTAG, responseBody); } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { Log.i(LOGTAG, "boligrafo" + e.getMessage()); } return null; } protected void onPostExecute (Double result) { //arrayList con ficheros /*path = Environment.getExternalStorageDirectory().toString() + "/proyectoCaronte"; File fileArray = new File(path); ArrayList<File> files = new ArrayList<File>(Arrays.asList(fileArray.listFiles())); itemCount = files.size(); tv_files.setText("Valor: " + itemCount + "\n");*/ File f = new File(path); File file[] = f.listFiles(); for (int i = 0; i < file.length; i++) { nameItem = file[i].getName(); etmd5.setText(etmd5.getText() + file[i].getName() + "\n"); } etid.setText(responseBody); pb.setVisibility(View.GONE); Toast.makeText(getApplicationContext(), "Command sent", Toast.LENGTH_LONG).show(); //decode base64 string /*byte[] decodedString = Base64.decode(strBase64, Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); img2.setImageBitmap(decodedByte); //decode base64 string byte[] decodedString1 = Base64.decode(strBase642, Base64.DEFAULT); Bitmap decodedByte1 = BitmapFactory.decodeByteArray(decodedString1, 0, decodedString1.length); img.setImageBitmap(decodedByte1);*/ } protected void onProgressUpdate (Integer... progress) { pb.setProgress(progress[0]); } public HttpClient getNewHttpClient () { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } } } }
true
2bc1dda594283014fbfc4662a60971f398c5cd15
Java
zhongxingyu/Seer
/Diff-Raw-Data/16/16_c8bd9ec24e51c5975c3dffa3a607a27cd208292f/CompilerAstCompletionNodeFinder/16_c8bd9ec24e51c5975c3dffa3a607a27cd208292f_CompilerAstCompletionNodeFinder_s.java
UTF-8
38,527
1.523438
2
[]
no_license
/** * Copyright (c) 2010 Darmstadt University of Technology. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Marcel Bruch - initial API and implementation. */ package org.eclipse.recommenders.internal.rcp.codecompletion; import static org.eclipse.recommenders.commons.utils.Checks.ensureIsNotNull; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.eclipse.jdt.internal.codeassist.complete.CompletionOnFieldType; import org.eclipse.jdt.internal.codeassist.complete.CompletionOnLocalName; import org.eclipse.jdt.internal.codeassist.complete.CompletionOnMemberAccess; import org.eclipse.jdt.internal.codeassist.complete.CompletionOnMessageSend; import org.eclipse.jdt.internal.codeassist.complete.CompletionOnQualifiedNameReference; import org.eclipse.jdt.internal.codeassist.complete.CompletionOnSingleNameReference; import org.eclipse.jdt.internal.compiler.ASTVisitor; import org.eclipse.jdt.internal.compiler.ast.AND_AND_Expression; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.AllocationExpression; import org.eclipse.jdt.internal.compiler.ast.AnnotationMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.ArrayAllocationExpression; import org.eclipse.jdt.internal.compiler.ast.ArrayInitializer; import org.eclipse.jdt.internal.compiler.ast.ArrayQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ArrayReference; import org.eclipse.jdt.internal.compiler.ast.ArrayTypeReference; import org.eclipse.jdt.internal.compiler.ast.AssertStatement; import org.eclipse.jdt.internal.compiler.ast.Assignment; import org.eclipse.jdt.internal.compiler.ast.BinaryExpression; import org.eclipse.jdt.internal.compiler.ast.Block; import org.eclipse.jdt.internal.compiler.ast.BreakStatement; import org.eclipse.jdt.internal.compiler.ast.CaseStatement; import org.eclipse.jdt.internal.compiler.ast.CastExpression; import org.eclipse.jdt.internal.compiler.ast.CharLiteral; import org.eclipse.jdt.internal.compiler.ast.ClassLiteralAccess; import org.eclipse.jdt.internal.compiler.ast.Clinit; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.CompoundAssignment; import org.eclipse.jdt.internal.compiler.ast.ConditionalExpression; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.ContinueStatement; import org.eclipse.jdt.internal.compiler.ast.DoStatement; import org.eclipse.jdt.internal.compiler.ast.DoubleLiteral; import org.eclipse.jdt.internal.compiler.ast.EmptyStatement; import org.eclipse.jdt.internal.compiler.ast.EqualExpression; import org.eclipse.jdt.internal.compiler.ast.ExplicitConstructorCall; import org.eclipse.jdt.internal.compiler.ast.Expression; import org.eclipse.jdt.internal.compiler.ast.ExtendedStringLiteral; import org.eclipse.jdt.internal.compiler.ast.FalseLiteral; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldReference; import org.eclipse.jdt.internal.compiler.ast.FloatLiteral; import org.eclipse.jdt.internal.compiler.ast.ForStatement; import org.eclipse.jdt.internal.compiler.ast.ForeachStatement; import org.eclipse.jdt.internal.compiler.ast.IfStatement; import org.eclipse.jdt.internal.compiler.ast.ImportReference; import org.eclipse.jdt.internal.compiler.ast.Initializer; import org.eclipse.jdt.internal.compiler.ast.InstanceOfExpression; import org.eclipse.jdt.internal.compiler.ast.IntLiteral; import org.eclipse.jdt.internal.compiler.ast.Javadoc; import org.eclipse.jdt.internal.compiler.ast.JavadocAllocationExpression; import org.eclipse.jdt.internal.compiler.ast.JavadocArgumentExpression; import org.eclipse.jdt.internal.compiler.ast.JavadocArrayQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.JavadocArraySingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.JavadocFieldReference; import org.eclipse.jdt.internal.compiler.ast.JavadocImplicitTypeReference; import org.eclipse.jdt.internal.compiler.ast.JavadocMessageSend; import org.eclipse.jdt.internal.compiler.ast.JavadocQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.JavadocReturnStatement; import org.eclipse.jdt.internal.compiler.ast.JavadocSingleNameReference; import org.eclipse.jdt.internal.compiler.ast.JavadocSingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.LabeledStatement; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.LongLiteral; import org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation; import org.eclipse.jdt.internal.compiler.ast.MemberValuePair; import org.eclipse.jdt.internal.compiler.ast.MessageSend; import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.NormalAnnotation; import org.eclipse.jdt.internal.compiler.ast.NullLiteral; import org.eclipse.jdt.internal.compiler.ast.OR_OR_Expression; import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ParameterizedSingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.PostfixExpression; import org.eclipse.jdt.internal.compiler.ast.PrefixExpression; import org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression; import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedSuperReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedThisReference; import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference; import org.eclipse.jdt.internal.compiler.ast.ReturnStatement; import org.eclipse.jdt.internal.compiler.ast.SingleMemberAnnotation; import org.eclipse.jdt.internal.compiler.ast.SingleNameReference; import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.StringLiteral; import org.eclipse.jdt.internal.compiler.ast.StringLiteralConcatenation; import org.eclipse.jdt.internal.compiler.ast.SuperReference; import org.eclipse.jdt.internal.compiler.ast.SwitchStatement; import org.eclipse.jdt.internal.compiler.ast.SynchronizedStatement; import org.eclipse.jdt.internal.compiler.ast.ThisReference; import org.eclipse.jdt.internal.compiler.ast.ThrowStatement; import org.eclipse.jdt.internal.compiler.ast.TrueLiteral; import org.eclipse.jdt.internal.compiler.ast.TryStatement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.eclipse.jdt.internal.compiler.ast.UnaryExpression; import org.eclipse.jdt.internal.compiler.ast.WhileStatement; import org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.eclipse.jdt.internal.compiler.lookup.Binding; import org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.eclipse.jdt.internal.compiler.lookup.ClassScope; import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.eclipse.jdt.internal.compiler.lookup.MethodBinding; import org.eclipse.jdt.internal.compiler.lookup.MethodScope; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; import org.eclipse.jdt.internal.compiler.lookup.VariableBinding; import org.eclipse.recommenders.commons.utils.annotations.Clumsy; import com.google.common.collect.Sets; @Clumsy @SuppressWarnings("restriction") public class CompilerAstCompletionNodeFinder extends ASTVisitor { /** * The JDT completion node created by the completion completion parser. * * @see one of org.eclipse.jdt.internal.codeassist.complete * @see CompletionOnMessageSend * @see CompletionOnQualifiedNameReference * @see CompletionOnSingleNameReference */ public Statement completionNode; /** * One of {@link ReturnStatement}, {@link LocalDeclaration}, * {@link FieldDeclaration}, or <code>null</code> */ public Statement completionNodeParent; /** * The type of the receiver this completion event was triggered on, e.g, * Button b = ...; b.|&lt;ctrl-space&gt; would set {@link #receiverType} to * <code>Button</code>. */ public TypeBinding receiverType; /** * The name of the receiver - if it has one. When triggering code completion * on <code>b.|&lt;ctrl-space&gt;</code> then {@link #receiverName} is 'b'. * However, if code completion has been triggered on an implicit method * return value like {@code getB().|&lt;ctrl-space&gt;} then * {@link #receiverName} is null. * <p> * If code completion is triggered on a type like <code>PlatformUI</code> * this variable holds the name of the type. <b>NOTE:</b> in the case of * single names like <code>PlatformUI|&lt;^Space&gt </code> or * <code>varName|&lt;^Space&gt</code> the reveiver type is typically NOT * set! Be careful! */ public String receiverName; /** * If {@link #expectsReturnType} is true, this completion request requires * the completion to define a new local, i.e., in the case of method calls * to have a return value. */ public boolean expectsReturnType; /** * if {@link #expectsReturnType} is true, then this value <b>might</b> hold * a type binding of the expected return type. However, this might not be as * easy and work in all cases and thus may be <code>null</code> even if * {@link #expectsReturnType} is true; */ public TypeBinding expectedReturnType; /** * This field is set whenever a completion is triggered on a type name like * 'Button' etc. * <p> * Example: * * <pre> * void someMethod(){ * Button|&|&lt;ctrl-space&gt; * } * </pre> */ public TypeBinding requestedTypeCompletion; public boolean expectsStaticMember; /** * If the code completion event occurs as a method argument guessing * completion (i.e., b.method(|&lt;ctrl-space&gt;), then * {@link IntelligentCompletionContext#enclosingMethodCallSelector} contains * the (unresolved and potentially ambiguous) name of the method call * enclosing this completion event. * * <p> * Example: * * <pre> * methodCall(|&lt;ctrl-space&gt;) // gives "methodCall" * </pre> */ public String enclosingMethodCallSelector; /** * If the code completion event occurs as a method argument guessing as * indicated by {@link #enclosingMethodCallSelector} being not * <code>null</code>, this field holds the type binding that declares the * enclosing method. */ public TypeBinding declaringTypeOfEnclosingMethodCall; /** * If code completion was triggered on an implicit method return value, this * field stores the method binding that defined this implicit (and unnamed) * local variable. * <p> * Example; * * <pre> * getX().|&lt;ctrl-space&gt; // evaluates to a binding for method "getX" * </pre> */ public MethodBinding receiverDefinedByMethodReturn; public MethodScope scope; public final Set<FieldDeclaration> fieldDeclarations = Sets.newHashSet(); public final Set<LocalDeclaration> localDeclarations = Sets.newHashSet(); public void clearState() { receiverDefinedByMethodReturn = null; completionNode = null; declaringTypeOfEnclosingMethodCall = null; enclosingMethodCallSelector = null; expectedReturnType = null; expectsReturnType = false; expectsStaticMember = false; receiverName = null; receiverType = null; requestedTypeCompletion = null; } @Override public boolean visit(final SingleNameReference singleNameReference, final BlockScope scope) { if (singleNameReference instanceof CompletionOnSingleNameReference) { final CompletionOnSingleNameReference node = storeCompletionNode(singleNameReference); evaluateCompletionOnSingleNameReference(node); return false; } return true; } @SuppressWarnings("unchecked") private <T extends Statement> T storeCompletionNode(final Statement statement) { completionNode = statement; return (T) statement; } private void evaluateCompletionOnSingleNameReference(final CompletionOnSingleNameReference completion) { // XXX this is actually not resolving any binding: receiverType = completion.resolvedType; setReceiverName(completion.token); } private void setReceiverName(final char[] name) { String s = String.valueOf(name); setReceiverName(s); } private void setReceiverName(final String name) { receiverName = StringUtils.deleteWhitespace(name); } @Override public boolean visit(final QualifiedNameReference qualifiedNameReference, final BlockScope scope) { if (qualifiedNameReference instanceof CompletionOnQualifiedNameReference) { final CompletionOnQualifiedNameReference node = storeCompletionNode(qualifiedNameReference); evaluateCompletionOnQualifiedNameReference(node); return false; } return true; } private void evaluateCompletionOnQualifiedNameReference(final CompletionOnQualifiedNameReference c) { switch (c.binding.kind()) { case Binding.VARIABLE: case Binding.FIELD: case Binding.LOCAL: final VariableBinding varBinding = (VariableBinding) c.binding; evaluateVariableBindingAsReceiver(varBinding); return; case Binding.TYPE: // e.g. PlatformUI.|<ctrl-space> final TypeBinding typeBinding = (TypeBinding) c.binding; receiverType = typeBinding; expectsStaticMember = true; return; default: /** * triggering code completion on an err pos like: * * <pre> * b.|&lt;^Space&gt; * final Button b = new Button(parent, 0); * * </pre> * * TODO is this appropriate? Do we want to handle these events? or * just discard error situations? */ // if (c.binding instanceof ProblemBinding) { // final ProblemBinding problem = cast(c.binding); // receiverName = String.valueOf(problem.name); // receiverType = problem.searchType; // } clearState(); } } private void evaluateVariableBindingAsReceiver(final VariableBinding binding) { ensureIsNotNull(binding); setReceiverName(binding.name); receiverType = binding.type; } @Override public boolean visit(final MessageSend messageSend, final BlockScope scope) { if (messageSend instanceof CompletionOnMessageSend) { final CompletionOnMessageSend node = storeCompletionNode(messageSend); evaluateCompletionOnMessageSend(node); return false; } return true; } private void evaluateCompletionOnMessageSend(final CompletionOnMessageSend c) { declaringTypeOfEnclosingMethodCall = c.actualReceiverType; enclosingMethodCallSelector = new String(c.selector); expectsReturnType = true; } @Override public boolean visit(final FieldReference fieldReference, final BlockScope scope) { if (fieldReference instanceof CompletionOnMemberAccess) { final CompletionOnMemberAccess node = storeCompletionNode(fieldReference); evaluateCompletionOnMemberAccess(node); return false; } return true; } private void evaluateCompletionOnMemberAccess(final CompletionOnMemberAccess c) { // what is the actual receiver type we are asked to create a completion // for (i.e., the type returned by the members method return type? receiverType = c.actualReceiverType; // since we are navigating through the API call graph this receiver // either is 'this' or has // no name. if (c.receiver instanceof ThisReference) { // NOTE simply calling 'c.isThis()' doesn't work; evaluateThisReferenceAsReceiver((ThisReference) c.receiver); } else if (c.receiver instanceof MessageSend) { evaluteMessageSendAsDefForAnonymousReceiver((MessageSend) c.receiver); } else if (c.fieldBinding() != null) { // does this happen? When? evaluateVariableBindingAsReceiver(c.fieldBinding()); } else if (c.localVariableBinding() != null) { // does this happen? when? evaluateVariableBindingAsReceiver(c.localVariableBinding()); } } private void evaluateThisReferenceAsReceiver(final ThisReference ref) { setReceiverName("this"); receiverType = ref.resolvedType; } /** * <pre> * public Activator() { * b.getLocation().|&lt;ctrl-space&gt; * } * </pre> * * @param m */ private void evaluteMessageSendAsDefForAnonymousReceiver(final MessageSend m) { if (m.binding != null) { receiverDefinedByMethodReturn = m.binding; receiverType = m.binding.returnType; setReceiverName(""); } } @Override public boolean visit(final LocalDeclaration localDeclaration, final BlockScope scope) { if (localDeclaration instanceof CompletionOnLocalName) { final CompletionOnLocalName node = storeCompletionNode(localDeclaration); evaluateCompletionOnLocalName(node); } else if (isCompletionOnVariableInitialization(localDeclaration.initialization)) { setExpectedReturnType(localDeclaration.binding.type); completionNodeParent = localDeclaration; } else { // we only add this declaration if it's "complete". // Var c = c doesn't make sense, right? localDeclarations.add(localDeclaration); } return true; } private void evaluateCompletionOnLocalName(final CompletionOnLocalName c) { if (c.binding != null) { setExpectedReturnType(c.binding.type); // TODO this is actually not correct! Need to fix the pattern // template stuff which expects receiver type // being set! receiverType = expectedReturnType; } setReceiverName(c.name); expectsReturnType = true; } @Override public boolean visit(final FieldDeclaration fieldDeclaration, final MethodScope scope) { if (fieldDeclaration instanceof CompletionOnFieldType) { storeCompletionNode(fieldDeclaration); return false; } if (isCompletionOnVariableInitialization(fieldDeclaration.initialization)) { setExpectedReturnType(fieldDeclaration.binding.type); completionNodeParent = fieldDeclaration; } else { // we only add this declaration if it's "complete". // Var c = c doesn't make sense, right? fieldDeclarations.add(fieldDeclaration); } return true; } private boolean isCompletionOnVariableInitialization(final Expression initialization) { return initialization instanceof CompletionOnSingleNameReference || initialization instanceof CompletionOnQualifiedNameReference || initialization instanceof CompletionOnMemberAccess; } public boolean isCompletionNodeFound() { return completionNode != null; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean visit(final AllocationExpression allocationExpression, final BlockScope scope) { return true; } @Override public boolean visit(final AND_AND_Expression and_and_Expression, final BlockScope scope) { return true; } @Override public boolean visit(final AnnotationMethodDeclaration annotationTypeDeclaration, final ClassScope classScope) { return true; } @Override public boolean visit(final Argument argument, final BlockScope scope) { return true; } @Override public boolean visit(final Argument argument, final ClassScope scope) { return true; } @Override public boolean visit(final ArrayAllocationExpression arrayAllocationExpression, final BlockScope scope) { return true; } @Override public boolean visit(final ArrayInitializer arrayInitializer, final BlockScope scope) { return true; } @Override public boolean visit(final ArrayQualifiedTypeReference arrayQualifiedTypeReference, final BlockScope scope) { return true; } @Override public boolean visit(final ArrayQualifiedTypeReference arrayQualifiedTypeReference, final ClassScope scope) { return true; } @Override public boolean visit(final ArrayReference arrayReference, final BlockScope scope) { return true; } @Override public boolean visit(final ArrayTypeReference arrayTypeReference, final BlockScope scope) { return true; } @Override public boolean visit(final ArrayTypeReference arrayTypeReference, final ClassScope scope) { return true; } @Override public boolean visit(final AssertStatement assertStatement, final BlockScope scope) { return true; } @Override public boolean visit(final Assignment assignment, final BlockScope scope) { return true; } @Override public boolean visit(final BinaryExpression binaryExpression, final BlockScope scope) { return true; } @Override public boolean visit(final Block block, final BlockScope scope) { return true; } @Override public boolean visit(final BreakStatement breakStatement, final BlockScope scope) { return true; } @Override public boolean visit(final CaseStatement caseStatement, final BlockScope scope) { return true; } @Override public boolean visit(final CastExpression castExpression, final BlockScope scope) { return true; } @Override public boolean visit(final CharLiteral charLiteral, final BlockScope scope) { return true; } @Override public boolean visit(final ClassLiteralAccess classLiteral, final BlockScope scope) { return true; } @Override public boolean visit(final Clinit clinit, final ClassScope scope) { return true; } @Override public boolean visit(final CompilationUnitDeclaration compilationUnitDeclaration, final CompilationUnitScope scope) { return true; } @Override public boolean visit(final CompoundAssignment compoundAssignment, final BlockScope scope) { return true; } @Override public boolean visit(final ConditionalExpression conditionalExpression, final BlockScope scope) { return true; } @Override public boolean visit(final ConstructorDeclaration constructorDeclaration, final ClassScope scope) { return true; } @Override public boolean visit(final ContinueStatement continueStatement, final BlockScope scope) { return true; } @Override public boolean visit(final DoStatement doStatement, final BlockScope scope) { return true; } @Override public boolean visit(final DoubleLiteral doubleLiteral, final BlockScope scope) { return true; } @Override public boolean visit(final EmptyStatement emptyStatement, final BlockScope scope) { return true; } @Override public boolean visit(final EqualExpression equalExpression, final BlockScope scope) { return true; } @Override public boolean visit(final ExplicitConstructorCall explicitConstructor, final BlockScope scope) { return true; } @Override public boolean visit(final ExtendedStringLiteral extendedStringLiteral, final BlockScope scope) { return true; } @Override public boolean visit(final FalseLiteral falseLiteral, final BlockScope scope) { return true; } @Override public boolean visit(final FieldReference fieldReference, final ClassScope scope) { return true; } @Override public boolean visit(final FloatLiteral floatLiteral, final BlockScope scope) { return true; } @Override public boolean visit(final ForeachStatement forStatement, final BlockScope scope) { return true; } @Override public boolean visit(final ForStatement forStatement, final BlockScope scope) { return true; } @Override public boolean visit(final IfStatement ifStatement, final BlockScope scope) { return true; } @Override public boolean visit(final ImportReference importRef, final CompilationUnitScope scope) { return true; } @Override public boolean visit(final Initializer initializer, final MethodScope scope) { return true; } @Override public boolean visit(final InstanceOfExpression instanceOfExpression, final BlockScope scope) { return true; } @Override public boolean visit(final IntLiteral intLiteral, final BlockScope scope) { return true; } @Override public boolean visit(final Javadoc javadoc, final BlockScope scope) { return true; } @Override public boolean visit(final Javadoc javadoc, final ClassScope scope) { return true; } @Override public boolean visit(final JavadocAllocationExpression expression, final BlockScope scope) { return true; } @Override public boolean visit(final JavadocAllocationExpression expression, final ClassScope scope) { return true; } @Override public boolean visit(final JavadocArgumentExpression expression, final BlockScope scope) { return true; } @Override public boolean visit(final JavadocArgumentExpression expression, final ClassScope scope) { return true; } @Override public boolean visit(final JavadocArrayQualifiedTypeReference typeRef, final BlockScope scope) { return true; } @Override public boolean visit(final JavadocArrayQualifiedTypeReference typeRef, final ClassScope scope) { return true; } @Override public boolean visit(final JavadocArraySingleTypeReference typeRef, final BlockScope scope) { return true; } @Override public boolean visit(final JavadocArraySingleTypeReference typeRef, final ClassScope scope) { return true; } @Override public boolean visit(final JavadocFieldReference fieldRef, final BlockScope scope) { return true; } @Override public boolean visit(final JavadocFieldReference fieldRef, final ClassScope scope) { return true; } @Override public boolean visit(final JavadocImplicitTypeReference implicitTypeReference, final BlockScope scope) { return true; } @Override public boolean visit(final JavadocImplicitTypeReference implicitTypeReference, final ClassScope scope) { return true; } @Override public boolean visit(final JavadocMessageSend messageSend, final BlockScope scope) { return true; } @Override public boolean visit(final JavadocMessageSend messageSend, final ClassScope scope) { return true; } @Override public boolean visit(final JavadocQualifiedTypeReference typeRef, final BlockScope scope) { return true; } @Override public boolean visit(final JavadocQualifiedTypeReference typeRef, final ClassScope scope) { return true; } @Override public boolean visit(final JavadocReturnStatement statement, final BlockScope scope) { return true; } @Override public boolean visit(final JavadocReturnStatement statement, final ClassScope scope) { return true; } @Override public boolean visit(final JavadocSingleNameReference argument, final BlockScope scope) { return true; } @Override public boolean visit(final JavadocSingleNameReference argument, final ClassScope scope) { return true; } @Override public boolean visit(final JavadocSingleTypeReference typeRef, final BlockScope scope) { return true; } @Override public boolean visit(final JavadocSingleTypeReference typeRef, final ClassScope scope) { return true; } @Override public boolean visit(final LabeledStatement labeledStatement, final BlockScope scope) { return true; } @Override public boolean visit(final LongLiteral longLiteral, final BlockScope scope) { return true; } @Override public boolean visit(final MarkerAnnotation annotation, final BlockScope scope) { return true; } @Override public boolean visit(final MemberValuePair pair, final BlockScope scope) { return true; } @Override public boolean visit(final MethodDeclaration methodDeclaration, final ClassScope scope) { return true; } @Override public boolean visit(final StringLiteralConcatenation literal, final BlockScope scope) { return true; } @Override public boolean visit(final NormalAnnotation annotation, final BlockScope scope) { return true; } @Override public boolean visit(final NullLiteral nullLiteral, final BlockScope scope) { return true; } @Override public boolean visit(final OR_OR_Expression or_or_Expression, final BlockScope scope) { return true; } @Override public boolean visit(final ParameterizedQualifiedTypeReference parameterizedQualifiedTypeReference, final BlockScope scope) { return true; } @Override public boolean visit(final ParameterizedQualifiedTypeReference parameterizedQualifiedTypeReference, final ClassScope scope) { return true; } @Override public boolean visit(final ParameterizedSingleTypeReference parameterizedSingleTypeReference, final BlockScope scope) { return true; } @Override public boolean visit(final ParameterizedSingleTypeReference parameterizedSingleTypeReference, final ClassScope scope) { return true; } @Override public boolean visit(final PostfixExpression postfixExpression, final BlockScope scope) { return true; } @Override public boolean visit(final PrefixExpression prefixExpression, final BlockScope scope) { return true; } @Override public boolean visit(final QualifiedAllocationExpression qualifiedAllocationExpression, final BlockScope scope) { return true; } @Override public boolean visit(final QualifiedNameReference qualifiedNameReference, final ClassScope scope) { return true; } @Override public boolean visit(final QualifiedSuperReference qualifiedSuperReference, final BlockScope scope) { return true; } @Override public boolean visit(final QualifiedSuperReference qualifiedSuperReference, final ClassScope scope) { return true; } @Override public boolean visit(final QualifiedThisReference qualifiedThisReference, final BlockScope scope) { return true; } @Override public boolean visit(final QualifiedThisReference qualifiedThisReference, final ClassScope scope) { return true; } @Override public boolean visit(final QualifiedTypeReference qualifiedTypeReference, final BlockScope scope) { return true; } @Override public boolean visit(final QualifiedTypeReference qualifiedTypeReference, final ClassScope scope) { return true; } @Override public boolean visit(final ReturnStatement returnStatement, final BlockScope scope) { if (!isCompletionOnVariableInitialization(returnStatement.expression)) { return true; } if (!(scope.referenceContext() instanceof AbstractMethodDeclaration)) { return true; } final AbstractMethodDeclaration referenceContext = (AbstractMethodDeclaration) scope.referenceContext(); if (referenceContext.binding == null) { return true; } setExpectedReturnType(referenceContext.binding.returnType); completionNodeParent = returnStatement; return true; } private void setExpectedReturnType(final TypeBinding type) { expectedReturnType = type; expectsReturnType = true; } @Override public boolean visit(final SingleMemberAnnotation annotation, final BlockScope scope) { return true; } @Override public boolean visit(final SingleNameReference singleNameReference, final ClassScope scope) { return true; } @Override public boolean visit(final SingleTypeReference singleTypeReference, final BlockScope scope) { return true; } @Override public boolean visit(final SingleTypeReference singleTypeReference, final ClassScope scope) { return true; } @Override public boolean visit(final StringLiteral stringLiteral, final BlockScope scope) { return true; } @Override public boolean visit(final SuperReference superReference, final BlockScope scope) { return true; } @Override public boolean visit(final SwitchStatement switchStatement, final BlockScope scope) { return true; } @Override public boolean visit(final SynchronizedStatement synchronizedStatement, final BlockScope scope) { return true; } @Override public boolean visit(final ThisReference thisReference, final BlockScope scope) { return true; } @Override public boolean visit(final ThisReference thisReference, final ClassScope scope) { return true; } @Override public boolean visit(final ThrowStatement throwStatement, final BlockScope scope) { return true; } @Override public boolean visit(final TrueLiteral trueLiteral, final BlockScope scope) { return true; } @Override public boolean visit(final TryStatement tryStatement, final BlockScope scope) { return true; } @Override public boolean visit(final TypeDeclaration localTypeDeclaration, final BlockScope scope) { return true; } @Override public boolean visit(final TypeDeclaration memberTypeDeclaration, final ClassScope scope) { return true; } @Override public boolean visit(final TypeDeclaration typeDeclaration, final CompilationUnitScope scope) { return true; } @Override public boolean visit(final TypeParameter typeParameter, final BlockScope scope) { return true; } @Override public boolean visit(final TypeParameter typeParameter, final ClassScope scope) { return true; } @Override public boolean visit(final UnaryExpression unaryExpression, final BlockScope scope) { return true; } @Override public boolean visit(final WhileStatement whileStatement, final BlockScope scope) { return true; } @Override public boolean visit(final Wildcard wildcard, final BlockScope scope) { return true; } @Override public boolean visit(final Wildcard wildcard, final ClassScope scope) { return true; } }
true
2325f9fad6592549525bc5f1d1900ab388248501
Java
cuicuicui123/pdjfy
/app/src/main/java/com/goodo/app/email/presenter/SelectPersonPresenterImpl.java
UTF-8
7,412
2.09375
2
[]
no_license
package com.goodo.app.email.presenter; import com.goodo.app.base.BaseActivity; import com.goodo.app.email.model.UnitBean; import com.goodo.app.email.model.UnitUserBean; import com.goodo.app.email.view.SelectPersonView; import com.goodo.app.rxjava.HttpMethods; import com.goodo.app.rxjava.MySubscriber; import com.goodo.app.util.JudgeIsJsonArray; import com.goodo.app.util.MyConfig; import com.google.gson.Gson; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.ResponseBody; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Created by Cui on 2017/4/18. * * @Description */ public class SelectPersonPresenterImpl implements SelectPersonPresenter { private SelectPersonView mSelectPersonView; private BaseActivity mActivity; private HttpMethods mHttpMethods; private int mSize; private int mNum = 0; private List<UnitBean> mUnitBeanList; private List<UnitUserBean>[] mUserBeanLists; private String KEY_UNIT_INFO = "getUnitInfo"; public SelectPersonPresenterImpl(SelectPersonView selectPersonView, BaseActivity activity) { mSelectPersonView = selectPersonView; mActivity = activity; mHttpMethods = HttpMethods.getInstance(); mUnitBeanList = new ArrayList<>(); } @Override public void getUnitInfo() { // MySubscriber subscriber = new MySubscriber() { // @Override // protected void onResponse(String response) { // try { // JSONObject jsonObject = new JSONObject(response); // JSONObject Goodo = jsonObject.getJSONObject("Goodo"); // JSONObject Record = Goodo.getJSONObject("Record"); // final Gson gson = new Gson(); // JudgeIsJsonArray.judge(Record, "Record", new JudgeIsJsonArray.OnJudged() { // @Override // public void judged(JSONObject jsonObject) throws JSONException { // UnitBean bean = gson.fromJson(jsonObject.toString(), UnitBean.class); // mUnitBeanList.add(bean); // } // }); // mSize = mUnitBeanList.size(); // mUserBeanLists = new List[mSize]; // for (int i = 0;i < mSize;i ++) { // UnitBean bean = mUnitBeanList.get(i); // getUnitUser(bean.getID(), i); // } // } catch (JSONException e) { // e.printStackTrace(); // } // } // }; // mHttpMethods.getUnitInfo(subscriber); getUser(); } @Override public void getUnitUser(int id, final int position) { MySubscriber subscriber = new MySubscriber() { @Override protected void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); JSONObject Goodo = jsonObject.getJSONObject("Goodo"); final List<UnitUserBean> list = new ArrayList<>(); final Gson gson = new Gson(); JudgeIsJsonArray.judge(Goodo, "R", new JudgeIsJsonArray.OnJudged() { @Override public void judged(JSONObject jsonObject) throws JSONException { UnitUserBean bean = gson.fromJson(jsonObject.toString(), UnitUserBean.class); list.add(bean); } }); mUserBeanLists[position] = list; mNum ++; if (mNum == mSize) { mSelectPersonView.getUnitInfoList(mUnitBeanList, mUserBeanLists); } } catch (JSONException e) { e.printStackTrace(); } } }; mHttpMethods.getUnitGroupUser(id, subscriber); } public void getUser(){ Subscriber subscriber = new MySubscriber() { @Override protected void onResponse(String response) { handleUserResponse(response); } }; mHttpMethods.getHttpService().getUnitInfo(MyConfig.USER_ID, MyConfig.UNIT_ID, MyConfig.SESSION_ID) .flatMap(new Func1<ResponseBody, Observable<?>>() { @Override public Observable<?> call(ResponseBody responseBody) { handleUnitResponse(responseBody); return Observable.from(mUnitBeanList).flatMap(new Func1<UnitBean, Observable<?>>() { @Override public Observable<?> call(UnitBean unitBean) { return mHttpMethods.getHttpService().getUnitUser(MyConfig.USER_ID, MyConfig.UNIT_ID, MyConfig.SESSION_ID, unitBean.getID(), true); } }); } }) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(subscriber); } private void handleUserResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); JSONObject Goodo = jsonObject.getJSONObject("Goodo"); final List<UnitUserBean> list = new ArrayList<>(); final Gson gson = new Gson(); JudgeIsJsonArray.judge(Goodo, "R", new JudgeIsJsonArray.OnJudged() { @Override public void judged(JSONObject jsonObject) throws JSONException { UnitUserBean bean = gson.fromJson(jsonObject.toString(), UnitUserBean.class); list.add(bean); } }); mUserBeanLists[mNum] = list; mNum ++; if (mNum == mSize) { mSelectPersonView.getUnitInfoList(mUnitBeanList, mUserBeanLists); } } catch (JSONException e) { e.printStackTrace(); } } private void handleUnitResponse(ResponseBody responseBody) { try { String response = responseBody.string(); JSONObject jsonObject = new JSONObject(response); JSONObject Goodo = jsonObject.getJSONObject("Goodo"); JSONObject Record = Goodo.getJSONObject("Record"); final Gson gson = new Gson(); JudgeIsJsonArray.judge(Record, "Record", new JudgeIsJsonArray.OnJudged() { @Override public void judged(JSONObject jsonObject) throws JSONException { UnitBean bean = gson.fromJson(jsonObject.toString(), UnitBean.class); mUnitBeanList.add(bean); } }); mSize = mUnitBeanList.size(); mUserBeanLists = new List[mSize]; } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
true
fa4f6e0b82baa79f31b69f7cfd1580aa1cf2e9b9
Java
Bahar17/MyApi
/src/test/java/com/my/api/domain/AddressTest.java
UTF-8
1,297
2.515625
3
[]
no_license
package com.my.api.domain; import static org.junit.Assert.assertNotNull; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.my.api.service.ApplicationConstants; /** * * The Class AddressTest. * */ public class AddressTest { /** * Class under test. */ @SuppressWarnings("unused") private Address address1; /** * Class under test. */ private Address address2; /** * Method executed before each test method. */ @Before public void setUp () { address1 = new Address(); address2 = new Address (ApplicationConstants.ID1, ApplicationConstants.LONDON, ApplicationConstants.POST_CODE); address2.setId(ApplicationConstants.ID1); address2.setPostCode(ApplicationConstants.POST_CODE); address2.setCity(ApplicationConstants.LONDON); } /** * Test teardown method. */ @After public void teardown () { address1 = null; address2 = null; } /** * test get methods. */ @Test public void testGetMethods () { assertNotNull (address2.getId()); assertNotNull (address2.getPostCode()); assertNotNull (address2.getCity()); assertNotNull (address2.toString()); } }
true
c9953b1019918007212c081da1a167c7a1333103
Java
Harbormaster-AI/freeport-cloned
/src/main/java/com/freeport/dao/TournamentDAO.java
UTF-8
6,400
2.390625
2
[]
no_license
/******************************************************************************* Turnstone Biologics Confidential 2018 Turnstone Biologics All Rights Reserved. This file is subject to the terms and conditions defined in file 'license.txt', which is part of this source code package. Contributors : Turnstone Biologics - General Release ******************************************************************************/ package com.freeport.dao; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.mongodb.morphia.Datastore; import org.bson.Document; import com.mongodb.client.MongoCollection; import com.freeport.exception.*; import com.freeport.primarykey.*; import com.freeport.bo.*; /** * Implements the MongoDB NoSQL persistence processing for business entity Tournament * using the Morphia Java Datastore. * * @author Dev Team */ public class TournamentDAO extends BaseDAO { /** * default constructor */ public TournamentDAO() { } //***************************************************** // CRUD methods //***************************************************** /** * Retrieves a Tournament from the persistent store, using the provided primary key. * If no match is found, a null Tournament is returned. * <p> * @param pk * @return Tournament * @exception ProcessingException */ public Tournament findTournament( TournamentPrimaryKey pk ) throws ProcessingException { Tournament businessObject = null; if (pk == null) { throw new ProcessingException("TournamentDAO.findTournament cannot have a null primary key argument"); } Datastore dataStore = getDatastore(); try { businessObject = dataStore.createQuery( Tournament.class ) .field( "tournamentId" ) .equal( (Long)pk.getFirstKey() ) .get(); } catch( Throwable exc ) { exc.printStackTrace(); throw new ProcessingException( "TournamentDAO.findTournament failed for primary key " + pk + " - " + exc ); } finally { } return( businessObject ); } /** * Inserts a new Tournament into the persistent store. * @param businessObject * @return newly persisted Tournament * @exception ProcessingException */ public Tournament createTournament( Tournament businessObject ) throws ProcessingException { Datastore dataStore = getDatastore(); try { // let's assign out internal unique Id Long id = getNextSequence( "tournamentId" ) ; businessObject.setTournamentId( id ); dataStore.save( businessObject ); LOGGER.info( "---- TournamentDAO.createTournament created a bo is " + businessObject ); } catch( Throwable exc ) { exc.printStackTrace(); throw new ProcessingException( "TournamentDAO.createTournament - " + exc.getMessage() ); } finally { } // return the businessObject return( businessObject ); } /** * Stores the provided Tournament to the persistent store. * * @param businessObject * @return Tournament stored entity * @exception ProcessingException */ public Tournament saveTournament( Tournament businessObject ) throws ProcessingException { Datastore dataStore = getDatastore(); try { dataStore.save( businessObject ); } catch( Throwable exc ) { exc.printStackTrace(); throw new ProcessingException( "TournamentDAO:saveTournament - " + exc.getMessage() ); } finally { } return( businessObject ); } /** * Removes a Tournament from the persistent store. * * @param pk identity of object to remove * @exception ProcessingException */ public boolean deleteTournament( TournamentPrimaryKey pk ) throws ProcessingException { Datastore dataStore = getDatastore(); try { dataStore.delete( findTournament( pk ) ); } catch( Throwable exc ) { LOGGER.severe("TournamentDAO:delete() - failed " + exc.getMessage() ); exc.printStackTrace(); throw new ProcessingException( "TournamentDAO.deleteTournament failed - " + exc ); } finally { } return( true ); } /** * returns a Collection of all Tournaments * @return ArrayList<Tournament> * @exception ProcessingException */ public ArrayList<Tournament> findAllTournament() throws ProcessingException { final ArrayList<Tournament> list = new ArrayList<Tournament>(); Datastore dataStore = getDatastore(); try { list.addAll( dataStore.createQuery( Tournament.class ).asList() ); } catch( Throwable exc ) { exc.printStackTrace(); LOGGER.warning( "TournamentDAO.findAll() errors - " + exc.getMessage() ); throw new ProcessingException( "TournamentDAO.findAllTournament failed - " + exc ); } finally { } if ( list.size() <= 0 ) { LOGGER.info( "TournamentDAO:findAllTournaments() - List is empty."); } return( list ); } // abstracts and overloads from BaseDAO @Override protected String getCollectionName() { return( "com.freeport.Tournament" ); } @Override protected MongoCollection<Document> createCounterCollection( MongoCollection<Document> collection ) { if ( collection != null ) { Document document = new Document(); Long initialValue = new Long(0); document.append( MONGO_ID_FIELD_NAME, "tournamentId" ); document.append( MONGO_SEQ_FIELD_NAME, initialValue ); collection.insertOne(document); } return( collection ); } //***************************************************** // Attributes //***************************************************** private static final Logger LOGGER = Logger.getLogger(Tournament.class.getName()); }
true
1f1d4df5f7d678d291f27cd5551e2c4a08d799fd
Java
YoshThePinetree/FuzzyCMeans
/src/defo/main.java
UTF-8
167
1.789063
2
[]
no_license
package defo; public class main { public static void main (String arg[]) { System.out.println("Fuzzy C Means"); FCM fcm = new FCM(); fcm.FuzzyCMeans(); } }
true
a00e24e78b7d6cf1d8336c062797bfc771bd599a
Java
tuk2000/sundaygame
/core/src/com/sunday/engine/environment/window/WindowEnvironment.java
UTF-8
1,273
2.390625
2
[]
no_license
package com.sunday.engine.environment.window; import com.sunday.engine.common.Data; import com.sunday.engine.common.context.DataContext; import com.sunday.engine.contextbank.ContextBank; import com.sunday.engine.environment.EnvironmentDataContext; import com.sunday.engine.rule.Condition; import com.sunday.engine.rule.DataProvider; public class WindowEnvironment implements DataProvider<WindowCondition> { private Window window; private EnvironmentDataContext<Window> windowEnvironmentDataContext; public WindowEnvironment(ContextBank contextBank) { window = new Window(); windowEnvironmentDataContext = contextBank.getDataContext(window); } public void resize(int width, int height) { window.width = width; window.height = height; windowEnvironmentDataContext.setSignal(WindowSignal.Resized); windowEnvironmentDataContext.evaluate(); window.reset(); } @Override public boolean isSuitedFor(Condition condition) { return condition instanceof WindowCondition; } @Override public Window requestData(WindowCondition condition) { return window; } @Override public <D extends Data> void feedback(D data, DataContext<D> dataContext) { } }
true
aa209055c7d8851999c64a106712589a1f49b2f5
Java
zkt1061749991/revdol-cq
/src/main/java/com/example/demo/domin/Event.java
UTF-8
420
1.90625
2
[]
no_license
package com.example.demo.domin; import lombok.Data; import java.io.Serializable; import java.sql.Date; @Data public class Event implements Serializable{ private int id; private int state; private int type; private String event_title; private String event_alt; private String event_body; private String img; private String url; private Date begin_date; private Date end_date; }
true
dc8015b82f7f998aa16371f4ce748f20c2780696
Java
ankitsorathiya/Er-Algorithm-and-Dr-Data-Structure
/src/test/java/com/engineeralgorithmanddrdatastructure/combinactory/SumWithKDigitsTest.java
UTF-8
1,813
2.890625
3
[ "MIT" ]
permissive
package com.engineeralgorithmanddrdatastructure.combinactory; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class SumWithKDigitsTest { private int[] input; List<ArrayList<Integer>> expected; private int k; private int sum; public SumWithKDigitsTest(List<ArrayList<Integer>> expected, int[] input, int k, int sum) { this.expected = expected; this.input = input; this.k = k; this.sum = sum; } @Parameters public static Collection<Object[]> getData() { Collection<Object[]> input = new ArrayList<>(); List<ArrayList<Integer>> result = new ArrayList<>(); result.add(getList(new int[] { 1, 2, 7, 9 })); result.add(getList(new int[] { 1, 3, 6, 9 })); result.add(getList(new int[] { 1, 3, 7, 8 })); result.add(getList(new int[] { 1, 4, 5, 9 })); result.add(getList(new int[] { 1, 4, 6, 8 })); result.add(getList(new int[] { 1, 5, 6, 7 })); result.add(getList(new int[] { 2, 3, 5, 9 })); result.add(getList(new int[] { 2, 3, 6, 8 })); result.add(getList(new int[] { 2, 4, 5, 8 })); result.add(getList(new int[] { 2, 4, 6, 7 })); result.add(getList(new int[] { 3, 4, 5, 7 })); input.add(new Object[] { result, new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 4, 19 }); return input; } private static ArrayList<Integer> getList(int[] input) { ArrayList<Integer> list = new ArrayList<>(input.length); for (int number : input) { list.add(number); } return list; } @Test public void testMaximizedInvestmentFolio() { assertEquals(this.expected, SumWithKDigits.findKDigitsWhoSum(input, k, sum)); } }
true
e7624b301344ea256ddcd449fdbf385bb0102fc2
Java
thanass/ThanCal
/app/src/main/java/edu/thanassis/thancal/MainActivity.java
UTF-8
3,165
2.46875
2
[]
no_license
package edu.thanassis.thancal; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import edu.thanassis.thancal.R; public class MainActivity extends AppCompatActivity implements View.OnClickListener, ICalculatorResultHandler { private Button _btn1; private Button _btn2; private Button _btn3; private Button _btn4; private Button _btn5; private Button _btn6; private Button _btn7; private Button _btn8; private Button _btn9; private Button _btn0; private Button _btnClear; private Button _btnPlus; private Button _btnResult; private TextView _consoleView; private CalculatorController _controller; public MainActivity() { _controller = new CalculatorController(this); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); _btn0 = (Button) findViewById(R.id.button10); _btn1 = (Button) findViewById(R.id.button1); _btn2 = (Button) findViewById(R.id.button2); _btn3 = (Button) findViewById(R.id.button3); _btn4 = (Button) findViewById(R.id.button4); _btn5 = (Button) findViewById(R.id.button5); _btn6 = (Button) findViewById(R.id.button6); _btn7 = (Button) findViewById(R.id.button7); _btn8 = (Button) findViewById(R.id.button8); _btn9 = (Button) findViewById(R.id.button9); _btnClear = (Button) findViewById(R.id.buttonClear); _btnPlus = (Button) findViewById(R.id.buttonPlus); _btnResult = (Button) findViewById(R.id.buttonResult); _consoleView = (TextView) findViewById(R.id.consoleTxtView); _btn0.setOnClickListener(this); _btn1.setOnClickListener(this); _btn2.setOnClickListener(this); _btn3.setOnClickListener(this); _btn4.setOnClickListener(this); _btn5.setOnClickListener(this); _btn6.setOnClickListener(this); _btn7.setOnClickListener(this); _btn8.setOnClickListener(this); _btn9.setOnClickListener(this); _btnClear.setOnClickListener(this); _btnResult.setOnClickListener(this); _btnPlus.setOnClickListener(this); } @Override public void onClick(View v) { int curViewId = v.getId(); if (curViewId == _btnClear.getId()) { _controller.Clear(); } else if(curViewId == _btnPlus.getId()) { // Handler for plus button _controller.Add(); } else if (curViewId == _btnResult.getId()) { // Handler for result button _controller.Equals(); } else { // Handler for numbers buttons _controller.Number(Integer.parseInt(((Button) v).getText().toString())); } } @Override public void OnCalculatorResult(String result) { _consoleView.setText(result); } }
true
b275c34a56b8e4892f694dc4a40a97136682faa9
Java
hiepnhse61627/CapstoneProject
/04.Source/CapstoneMVC/src/main/java/com/capstone/controllers/StudentPassFailSubjectController.java
UTF-8
4,870
2.28125
2
[]
no_license
package com.capstone.controllers; import com.capstone.entities.MarksEntity; import com.capstone.entities.RealSemesterEntity; import com.capstone.models.Global; import com.capstone.models.Ultilities; import com.capstone.services.*; import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.*; import java.util.stream.Collectors; @Controller public class StudentPassFailSubjectController { @RequestMapping("/passfail") public ModelAndView Index(HttpServletRequest request) { if (!Ultilities.checkUserAuthorize(request)) { return Ultilities.returnDeniedPage(); } //logging user action Ultilities.logUserAction("go to " + request.getRequestURI()); ModelAndView view = new ModelAndView("StudentPassFailSubject"); view.addObject("title", "DSSV đậu rớt"); IRealSemesterService realSemesterService = new RealSemesterServiceImpl(); List<RealSemesterEntity> reals = Ultilities.SortSemesters(realSemesterService.getAllSemester()); view.addObject("semesters", Lists.reverse(reals)); ISubjectService subjectService = new SubjectServiceImpl(); view.addObject("subjects", subjectService.getAllSubjects()); return view; } @RequestMapping("/passfail/get") @ResponseBody public JsonObject GetData(@RequestParam Map<String, String> params) { // List<RealSemesterEntity> list = Global.getSortedList(); // List<RealSemesterEntity> processedSemesters = list.stream().filter(c -> list.indexOf(c) <= list.indexOf(list.stream().filter(a -> a.getId() == Integer.parseInt(semesterId)).findFirst().get())).collect(Collectors.toList()); // List<String> tmp = processedSemesters.stream().map(c -> c.getSemester()).collect(Collectors.toList()); JsonObject jsonObj = new JsonObject(); try { int semesterId = Integer.parseInt(params.get("semesterId")); String subjectId = params.get("subjectId"); int passfail = Integer.parseInt(params.get("passfail")); IMarksService service = new MarksServiceImpl(); List<MarksEntity> marks = service.findMarksByStudentIdAndSubjectCdAndSemesterId(0, subjectId, semesterId); marks = marks.stream().filter(c -> c.getIsActivated() && c.getEnabled() != null && c.getEnabled()).collect(Collectors.toList()); marks = Ultilities.SortSemestersByMarks(marks); Map<String, List<MarksEntity>> map = marks .stream() .collect(Collectors.groupingBy(c -> c.getStudentId().getRollNumber())); List<List<String>> data = new ArrayList<>(); map.entrySet().forEach(c -> { List<MarksEntity> stuMarks = c.getValue(); stuMarks.forEach(a -> { List<String> tmp = new ArrayList<>(); if (passfail == 1) { if (a.getStatus().toLowerCase().contains("pass") || a.getStatus().toLowerCase().contains("exempt")) { tmp.add(a.getStudentId().getRollNumber()); tmp.add(a.getStudentId().getFullName()); tmp.add(a.getSemesterId().getSemester()); tmp.add(String.valueOf(a.getAverageMark())); tmp.add(a.getStatus()); data.add(tmp); } } else { if (a.getStatus().toLowerCase().contains("fail")) { tmp.add(a.getStudentId().getRollNumber()); tmp.add(a.getStudentId().getFullName()); tmp.add(a.getSemesterId().getSemester()); tmp.add(String.valueOf(a.getAverageMark())); tmp.add(a.getStatus()); data.add(tmp); } } }); }); Gson gson = new Gson(); JsonArray array = (JsonArray) gson.toJsonTree(data); // jsonObj.addProperty("iTotalRecords", array.size()); // jsonObj.addProperty("iTotalDisplayRecords", array.size()); jsonObj.add("aaData", array); // jsonObj.addProperty("sEcho", params.get("sEcho")); } catch (Exception e) { e.printStackTrace(); } return jsonObj; } }
true
1c115fb41cfbcaa4397449640b259af978049c7b
Java
mairan/Local
/src/self/kiwi/dao/ItemDAO.java
UTF-8
420
2.046875
2
[]
no_license
package self.kiwi.dao; import java.net.UnknownHostException; import com.mongodb.DBCollection; import self.kiwi.model.GeneralItem; public class ItemDAO extends MongoWrapper { public ItemDAO() throws UnknownHostException { super(); // TODO Auto-generated constructor stub } public void insert(GeneralItem item){ DBCollection coll = db.getCollection("item_list"); coll.insert(item.getItemObj()); } }
true
82cd4a2cd85b1852adb58dfbcac5faba330593db
Java
racsor/prueba
/src/main/java/org/alterq/domain/UserAlterQ.java
UTF-8
2,912
1.929688
2
[]
no_license
package org.alterq.domain; import java.io.Serializable; import java.util.Date; import java.util.List; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document public class UserAlterQ implements Serializable { @Id private String id; private String nick; private String name; private String surnames; private int typeID; private String idCard; private String pwd; private String phoneNumber; private String birthday; private String city; private String balance; private String accept; private boolean active; private Date dateCreated; private Date dateUpdated; private List<RolCompany> rols; private List<Bet> specialBets; public List<Bet> getSpecialBets() { return specialBets; } public void setSpecialBets(List<Bet> specialBets) { this.specialBets = specialBets; } public List<RolCompany> getRols() { return rols; } public void setRols(List<RolCompany> rols) { this.rols = rols; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumer) { this.phoneNumber = phoneNumer; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getBalance() { return balance; } public void setBalance(String balance) { this.balance = balance; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public Date getDateUpdated() { return dateUpdated; } public void setDateUpdated(Date dateUpdated) { this.dateUpdated = dateUpdated; } /* * public boolean isAdmin() { return admin; } * * public void setAdmin(boolean admin) { this.admin = admin; } */ public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public String getAccept() { return accept; } public void setAccept(String accept) { this.accept = accept; } public String getNick() { return nick; } public void setNick(String nick) { this.nick = nick; } public String getSurnames() { return surnames; } public void setSurnames(String surnames) { this.surnames = surnames; } public int getTypeID() { return typeID; } public void setTypeID(int typeID) { this.typeID = typeID; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
true