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
da28726b468ace5c3145d02b050039c184edc90a
Java
heuristicus/nxt
/src/search/SearchNode.java
UTF-8
224
1.664063
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package search; /** * * @author Jeremiah Via */ public interface SearchNode { public boolean equals(GridPoint point); }
true
4ec8649792eb87b23191ecdd58b462cf8f3af715
Java
EngrRubel/iCare
/app/src/main/java/com/jkkniugmail/rubel/icare/db/DatabaseManager.java
UTF-8
551
2.265625
2
[]
no_license
package com.jkkniugmail.rubel.icare.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; /** * Created by islan on 2/19/2017. */ public class DatabaseManager { private DatabaseHelper helper; private SQLiteDatabase database; public DatabaseManager(Context context) { helper = new DatabaseHelper(context); } private void openDatabase() { database = helper.getWritableDatabase(); } private void closeDatabase() { database.close(); helper.close(); } }
true
58354462d5b41e07645140951f44b2f93e02c7ca
Java
patrickHub/Quick-Documents
/QuickDocumentsDam/src/main/java/ch/cloud/quickdocument/service/dam/model/Dtos/ImageDTO.java
UTF-8
589
1.953125
2
[]
no_license
package ch.cloud.quickdocument.service.dam.model.Dtos; /** * * @Author <a href="pDjomo@hamilton-medical.com">Patrick Djomo</a> * */ public class ImageDTO { private int id; private String uploadOn; private String imgPath; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUploadOn() { return uploadOn; } public void setUploadOn(String uploadOn) { this.uploadOn = uploadOn; } public String getImgPath() { return imgPath; } public void setImgPath(String imgPath) { this.imgPath = imgPath; } }
true
4a85b668568dfd026bd750c6b9d1b87100686866
Java
miaoihan/AwsomeJava
/collection/LinkListTest1.java
UTF-8
551
2.734375
3
[]
no_license
package collection; import pojo.Person; /** * time: 16-5-12. * author: han */ public class LinkListTest1 { public static void main(String[] args) { Person p1 = new Person("han",1); Person p2 = new Person("zh",2); Person p3 = new Person("阿龙",3); Person p4 = new Person("阿辉",4); p1.next = p2; p2.next = p4; p4.next = p3; // while (p1.hasNext()){ // System.out.println(p1.name); // p1 = p1.next; // } // Iterable iter = Person. } }
true
9b0395e388c09ab4aa180918fb0f6ad4c4538492
Java
maxymilianz/CS-at-University-of-Wroclaw
/Object-oriented software design/Solutions/3/2/src/com/company/OldReportPrinter.java
UTF-8
361
2.6875
3
[]
no_license
package com.company; public class OldReportPrinter { private String data; public OldReportPrinter(String data) { this.data = data; } public void formatDocument() { // some implementation } public void printReport() { System.out.println(data); } public String getData() { return data; } }
true
a7d71743bfabe68eb18e5c688b79d0f549bae718
Java
mohsenuss91/KGBANDROID
/src/com/appyet/manager/bv.java
UTF-8
1,215
1.554688
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.appyet.manager; import com.appyet.context.ApplicationContext; import com.appyet.d.d; import com.appyet.f.a; // Referenced classes of package com.appyet.manager: // bq, d final class bv extends a { final bq a; private Long b; private boolean c; private boolean d; private boolean f; public bv(bq bq1, Long long1, boolean flag) { a = bq1; super(); b = null; c = true; d = true; f = true; b = long1; f = flag; } private transient Void f() { try { if (d) { a.c(); } if (c) { bq.g(a).h.a(); } a.a(b, f); } catch (Exception exception) { com.appyet.d.d.a(exception); return null; } return null; } protected final volatile void a(Object obj) { } protected final Object b() { return f(); } }
true
7eb5da1c031bfaccb03c02bd34534b3b65bcdcbc
Java
YeChenyu/HelloWorld
/HelloActivity/src/com/felipecsl/asymmetricgridview/RowItem.java
GB18030
464
2.734375
3
[]
no_license
package com.felipecsl.asymmetricgridview; final class RowItem { //ʵΪAsymmetricItem private final AsymmetricItemDao item; // private final int index; /** * AsymmetricItemзװ * @param index * @param item ʵΪAsymmetricItem */ RowItem(int index, AsymmetricItemDao item) { this.item = item; this.index = index; } AsymmetricItemDao getItem() { return item; } int getIndex() { return index; } }
true
f114794d9a7853aa369b51f7e5be822de32a5476
Java
jwiszowata/code_reaper
/code/my-app/functions/3/isNewWorldLuxuryType_GoodsType.java
UTF-8
104
2.15625
2
[]
no_license
public boolean isNewWorldLuxuryType() { return madeFrom != null && madeFrom.isNewWorldGoodsType(); }
true
641a75ff4249350b8896ab6f4114ef738a011c47
Java
AsiaMielczarek/JUnitTest
/src/main/java/workshop/test/exercises/NotString.java
UTF-8
209
2.5
2
[]
no_license
package workshop.test.exercises; public class NotString { public String notString(String word){ if(word.contains("not")){ return word; } return "not " + word; } }
true
baab28ace6bafa051bdf169330bd0fac835328a4
Java
exxcellent/swt2-bsa-backend
/bogenliga/bogenliga-application/src/main/java/de/bogenliga/application/services/v1/wettkampf/mapper/WettkampfDTOMapper.java
UTF-8
3,682
2.3125
2
[ "MIT" ]
permissive
package de.bogenliga.application.services.v1.wettkampf.mapper; import java.sql.Date; import java.util.function.Function; import de.bogenliga.application.business.wettkampf.api.types.WettkampfDO; import de.bogenliga.application.common.service.mapping.DataTransferObjectMapper; import de.bogenliga.application.services.v1.wettkampf.model.WettkampfDTO; /** * I map the {@link WettkampfDO} and {@link WettkampfDTO} objects * * @author Marvin Holm, Daniel Schott * @see <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html"> * Oracle Function Package Overview</a> * @see <a href="https://www.baeldung.com/java-8-functional-interfaces">Functional Interfaces in Java 8</a> */ public class WettkampfDTOMapper implements DataTransferObjectMapper { /** * I map the {@link WettkampfDO} to the {@link WettkampfDTO} object */ public static final Function<WettkampfDO, WettkampfDTO> toDTO = wettkampfDO -> { final Long wettkampfId = wettkampfDO.getId(); final Long wettkampfVeranstaltungsId = wettkampfDO.getWettkampfVeranstaltungsId(); final Date wettkampfDatum = wettkampfDO.getWettkampfDatum(); final String wettkampfStrasse = wettkampfDO.getWettkampfStrasse(); final String wettkampfPlz = wettkampfDO.getWettkampfPlz(); final String wettkampfOrtsname = wettkampfDO.getWettkampfOrtsname(); final String wettkampfOrtsinfo = wettkampfDO.getWettkampfOrtsinfo(); final String wettkampfBeginn = wettkampfDO.getWettkampfBeginn(); final Long wettkampfTag = wettkampfDO.getWettkampfTag(); final Long wettkampfDisziplinId = wettkampfDO.getWettkampfDisziplinId(); final Long wettkampfTypId = wettkampfDO.getWettkampfTypId(); final Long version = wettkampfDO.getVersion(); final Long wettkampfAusrichter = wettkampfDO.getWettkampfAusrichter(); return new WettkampfDTO(wettkampfId, wettkampfVeranstaltungsId, wettkampfDatum, wettkampfStrasse, wettkampfPlz, wettkampfOrtsname, wettkampfOrtsinfo, wettkampfBeginn, wettkampfTag, wettkampfDisziplinId, wettkampfTypId, version, wettkampfAusrichter); }; /** * maps the {@link WettkampfDTO} to the {@link WettkampfDO} object */ public static final Function<WettkampfDTO, WettkampfDO> toDO = wettkampfDTO -> { final Long wettkampfId = wettkampfDTO.getId(); final Long wettkampfVeranstaltungsId = wettkampfDTO.getwettkampfVeranstaltungsId(); final Date wettkampfDatum = wettkampfDTO.getDatum(); final String wettkampfStrasse = wettkampfDTO.getWettkampfStrasse(); final String wettkampfPlz = wettkampfDTO.getWettkampfPlz(); final String wettkampfOrtsname = wettkampfDTO.getWettkampfOrtsname(); final String wettkampfOrtsinfo = wettkampfDTO.getWettkampfOrtsinfo(); final String wettkampfBeginn = wettkampfDTO.getWettkampfBeginn(); final Long wettkampfTag = wettkampfDTO.getWettkampfTag(); final Long wettkampfDisziplinId = wettkampfDTO.getWettkampfDisziplinId(); final Long wettkampfTypId = wettkampfDTO.getWettkampfTypId(); final Long version = wettkampfDTO.getVersion(); final Long wettkampfAusrichter = wettkampfDTO.getWettkampfAusrichter(); return new WettkampfDO(wettkampfId, wettkampfVeranstaltungsId, wettkampfDatum, wettkampfStrasse, wettkampfPlz, wettkampfOrtsname, wettkampfOrtsinfo, wettkampfBeginn, wettkampfTag, wettkampfDisziplinId, wettkampfTypId, version, wettkampfAusrichter); }; /** * Constructor */ private WettkampfDTOMapper(){ //empty } }
true
0c05d752d647f3aea5d5d469bb5d2f224de5e2d4
Java
neumotngayem/AilatrieuphuNew
/app/src/main/java/com/example/administrator/trieuphu/ScoreActivity.java
UTF-8
1,243
2.328125
2
[]
no_license
package com.example.administrator.trieuphu; import android.app.Activity; import android.graphics.Typeface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; public class ScoreActivity extends Activity { TextView textView; ArrayList<ArrayList<String>> listHighScore; ListView listScore; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_score); textView = (TextView)findViewById(R.id.tvHigh) ; Typeface face = Typeface.createFromAsset(getAssets(),"font/dorid.ttf"); textView.setTypeface(face); listHighScore = new ArrayList<>(); for(int i = 0; i< 15;i++){ ArrayList<String> temp = new ArrayList<>(); temp.add(i+1+""); temp.add("Bac "+i); listHighScore.add(temp); } ListScoreAdapter adapter = new ListScoreAdapter(this,listHighScore); listScore = (ListView) findViewById(R.id.listScore); listScore.setAdapter(adapter); } }
true
c7815d9758037f16b224a452c8e4fd7b012178f5
Java
joshuadavis/yajul
/yajul-micro/src/main/java/org/yajul/micro/ModuleList.java
UTF-8
2,681
2.953125
3
[]
no_license
package org.yajul.micro; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.AbstractModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; /** * Helps make a list of modules to bootstrap Guice with. * <br> * User: josh * Date: Jan 28, 2009 * Time: 10:01:07 AM */ public class ModuleList { private final static Logger log = LoggerFactory.getLogger(ModuleList.class); private List<Module> modules = new ArrayList<Module>(); /** * Adds a module to the list. * @param module the module */ public void add(Module module) { modules.add(module); } /** * Adds a module using reflection. * @param moduleClassName the class name of the module. */ public void addClassName(String moduleClassName) { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class<?> clazz = loader.loadClass(moduleClassName); Module module = (Module) clazz.newInstance(); modules.add(module); } catch (RuntimeException e) { log.error("Unable to add " + moduleClassName + " due to :" + e, e); throw e; } catch (Exception e) { log.error("Unable to add " + moduleClassName + " due to :" + e, e); throw new RuntimeException(e); } } /** * Adds a module that will register a specific instance. * @param key the component key * @param instance the component instance * @param <T> the key type */ public <T> void addInstance(final Class<T> key, final T instance) { modules.add(new AbstractModule() { protected void configure() { log.info("Binding " + key + " to " + instance + " ..."); bind(key).toInstance(instance); } }); } /** * @return the number of modules in the list */ public int size() { return modules.size(); } /** * Creates a Guice injector with all of the modules. * @return the new Guice injector. */ public Injector createInjector() { log.info("Creating injector with " + size() + " modules..."); Injector injector = Guice.createInjector(getModules()); log.info("Injector created."); return injector; } /** * Returns the modules in a way that can be used with Guice.createInjector() * @return an iterable list of modules */ public Iterable<Module> getModules() { return modules; } }
true
2dc73e0a48c8744f9edb1ebd36ed051f0f065770
Java
emcaste93/Tripscape
/app/src/main/java/com/example/tripscape/data/TripescapeFirestore.java
UTF-8
2,845
2.546875
3
[]
no_license
package com.example.tripscape.data; import android.util.Log; import com.example.tripscape.model.Attraction; import com.example.tripscape.model.Trip; import com.example.tripscape.model.TripUser; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.FirebaseFirestore; public class TripescapeFirestore { private CollectionReference attractions; // private CollectionReference trips; private static final String TAG = "Tripescape"; public TripescapeFirestore() { FirebaseFirestore db = FirebaseFirestore.getInstance(); attractions = db.collection("attractionsGermany"); // trips = db.collection("tripsGermany"); } public void addAttracionToCollection(Attraction attraction) { attractions.document().set(attraction); } /* public void addTripToCollection(Trip trip) { trips.document().set(trip); }*/ public String addEmptyAttrationToCollection() { return attractions.document().getId(); } /* public String addEmptyTripToCollection() { return trips.document().getId(); }*/ public void updateAttraction(String id, Attraction attraction) { attractions.document(id).set(attraction); } public void updateTrip(String id, Trip trip) { attractions.document(id).set(trip); } public void saveTripData(Trip trip) { /* if(trip.getUserId() == "") { trip.setUserId(TripUser.getInstance().getUid()); } trips.add(trip);*/ trip.setUserId(TripUser.getInstance().getUid()); FirebaseFirestore db = FirebaseFirestore.getInstance(); try { db.collection("tripsGermany").document(trip.getId()).set(trip); } catch (Exception e) { Log.d(TAG, "Error when storing the trip into FirebaseFirestore: " +e.getMessage()); } } public void generateFirestoreData(AttractionList attractionList) { for(int id = 0; id < attractionList.getSize(); id++) { attractions.add(attractionList.getElementAt(id)); } } public void saveUser(final TripUser user) { FirebaseFirestore db = FirebaseFirestore.getInstance(); try { db.collection("users").document(user.getUid()).set(user); } catch (Exception e) { Log.d(TAG, "Error when storing the user into FirebaseFirestore: " +e.getMessage()); } } public void removeTrip(String tripId) { FirebaseFirestore db = FirebaseFirestore.getInstance(); try { //Get Document id from tripId db.collection("tripsGermany").document(tripId).delete(); } catch (Exception e) { Log.d(TAG, "Error when storing the user into FirebaseFirestore: " +e.getMessage()); } } }
true
84dc566451ff55a67a078b71cdd7ea421e3e9d7d
Java
AlexHajek93/Workspace
/ERS_Web/src/com/revature/servlet/ServletHelper.java
UTF-8
5,198
2.234375
2
[]
no_license
package com.revature.servlet; import java.io.IOException; import java.sql.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import ers.beans.ErsReimbursement; import ers.beans.ErsRole; import ers.beans.ErsStatus; import ers.beans.ErsType; import ers.beans.ErsUser; import ers.dao.ErsDAO; public class ServletHelper extends HttpServlet{ private ErsDAO dao; private ErsUser info; @Override public void init() throws ServletException { // TODO Auto-generated method stub super.init(); dao = new ErsDAO(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException{ if((info = dao.retrieveUser(req.getParameter("user")))!=null){ if(info.getPassword().equals(req.getParameter("pass"))) System.out.println(info.getRole().getRole()); if(info.getRole().getRole()!=2){ System.out.println("password match"); req.getSession().setAttribute("userid", info.getId()); req.getSession().setAttribute("username", info.getFname()); req.getSession().setAttribute("userRole", info.getRole().getRole()); resp.sendRedirect("page.jsp"); } else if(info.getRole().getRole()==2){ System.out.println("password match"); req.getSession().setAttribute("userid", info.getId()); req.getSession().setAttribute("username", info.getFname()); req.getSession().setAttribute("userRole", info.getRole().getRole()); resp.sendRedirect("page.jsp"); } else{ System.out.println("password failed"); req.getSession().setAttribute("loginFail", "Login failed, I guess you don't know who you are..."); resp.sendRedirect("login.jsp"); } }else{ System.out.println("password failed"); req.setAttribute("loginFail", "Login failed, I guess you don't know who you are..."); resp.sendRedirect("login.jsp"); } } public void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException{ req.getSession().setAttribute("userRole", 0); req.getSession().invalidate(); resp.sendRedirect("reimburse.jsp"); } public void ureg(HttpServletRequest req, HttpServletResponse resp) throws IOException{ //Needs work info = new ErsUser(); info.setId(1); info.setUsername(req.getParameter("user")); info.setPassword(req.getParameter("pass")); info.setFname(req.getParameter("fname")); info.setLname(req.getParameter("lname")); info.setEmail(req.getParameter("email")); info.setRole(new ErsRole(1,"")); System.out.println("creating user..."); System.out.println(info); if(dao.createUser(info)){ req.getSession().setAttribute("userid", info.getId()); req.getSession().setAttribute("username", info.getFname()); req.getSession().setAttribute("userRole", info.getRole().getRole()); resp.sendRedirect("page.jsp"); }else{ System.out.println("registration failed"); req.setAttribute("regFail", "Registration failed, Try again or don't..."); resp.sendRedirect("ureg.jsp"); } } public void stateChange(HttpServletRequest req, HttpServletResponse resp,int role,int state) throws IOException{ switch(role){ case 1: req.getSession().setAttribute("ustate", state); break; case 2: req.getSession().setAttribute("mstate", state); break; } resp.sendRedirect("state.jsp"); } public void nstat(HttpServletRequest req, HttpServletResponse resp) throws IOException{ if(dao.createStat(new ErsStatus(1,req.getParameter("newstat")))) resp.sendRedirect("page.jsp"); else resp.sendRedirect("state.jsp"); } public void ntype(HttpServletRequest req, HttpServletResponse resp) throws IOException{ if(dao.createType(new ErsType(1,req.getParameter("newtype")))) resp.sendRedirect("page.jsp"); else resp.sendRedirect("state.jsp"); } public void nrole(HttpServletRequest req, HttpServletResponse resp) throws IOException{ if(dao.createRole(new ErsRole(1,req.getParameter("newrole")))) resp.sendRedirect("page.jsp"); else resp.sendRedirect("state.jsp"); } public void nreim(HttpServletRequest req, HttpServletResponse resp) throws IOException{ System.out.println("Entered"); System.out.println(Integer.parseInt(req.getParameter("amount"))); System.out.println(new Date(1)); System.out.println(new ErsUser((int)req.getSession().getAttribute("userid"), " ", " ", " ", " ", " ", new ErsRole(1, " "))); System.out.println(new ErsStatus(1, "Pending") +" "+ new ErsType()); if(dao.createReim(new ErsReimbursement(1, 20, new Date(1), new ErsUser((int)req.getSession().getAttribute("userid"), " ", " ", " ", " ", " ", new ErsRole(1, " ")), new ErsStatus(1, "Pending"), new ErsType()))) resp.sendRedirect("page.jsp"); else resp.sendRedirect("page.jsp"); } public void creim(HttpServletRequest req, HttpServletResponse resp) throws IOException{ //Needs work resp.sendRedirect("page.jsp"); } public void process(HttpServletRequest req, HttpServletResponse resp) throws IOException{ resp.sendRedirect("page.jsp"); } }
true
533801c8b7a0956b018fa9b2e5ec08bb08facd1e
Java
codimiracle/huidu-backend
/src/main/java/com/codimiracle/application/platform/huidu/web/api/expose/ApiCategoryController.java
UTF-8
4,103
2.15625
2
[]
no_license
package com.codimiracle.application.platform.huidu.web.api.expose; import com.codimiracle.application.platform.huidu.contract.*; import com.codimiracle.application.platform.huidu.entity.vo.BookVO; import com.codimiracle.application.platform.huidu.entity.vo.CategoryVO; import com.codimiracle.application.platform.huidu.enumeration.BookStatus; import com.codimiracle.application.platform.huidu.enumeration.BookType; import com.codimiracle.application.platform.huidu.enumeration.CategoryType; import com.codimiracle.application.platform.huidu.service.BookService; import com.codimiracle.application.platform.huidu.service.CategoryService; import com.codimiracle.application.platform.huidu.util.RestfulUtil; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.Objects; /** * @author Codimiracle */ @CrossOrigin @RestController @RequestMapping("/api/categories") public class ApiCategoryController { @Resource private CategoryService categoryService; @Resource private BookService bookService; @GetMapping("/{id}") public ApiResponse entity(@PathVariable String id) { CategoryVO categoryVO = categoryService.findByIdIntegrally(id); return RestfulUtil.entity(categoryVO); } @GetMapping("/{id}/items") public ApiResponse items(@PathVariable("id") String categoryId, @RequestParam("filter") Filter filter, @RequestParam("sorter") Sorter sorter, @ModelAttribute Page page) { filter = Objects.isNull(filter) ? new Filter() : filter; filter.put("status", new String[]{BookStatus.Serializing.toString(), BookStatus.Ended.toString(), BookStatus.Paused.toString()}); PageSlice<BookVO> slice = bookService.findByCategoryIdIntegrally(categoryId, filter, sorter, page); return RestfulUtil.list(slice); } @GetMapping("/{id}/album") public ApiResponse album(@PathVariable("id") String categoryId, @RequestParam("filter") Filter filter, @RequestParam("sorter") Sorter sorter, @ModelAttribute Page page) { filter = Objects.isNull(filter) ? new Filter() : filter; filter.put("status", new String[]{BookStatus.Serializing.toString(), BookStatus.Ended.toString(), BookStatus.Paused.toString()}); PageSlice<BookVO> slice = bookService.findByCollectionIdIntegrally(categoryId, filter, sorter, page); return RestfulUtil.list(slice); } @GetMapping("/{id}/album/most-read") public ApiResponse albumMostRead(@PathVariable("id") String categoryId) { Page page = new Page(); page.setLimit(10); page.setPage(1); Sorter sorter = new Sorter(); sorter.setField("hotDegree"); sorter.setOrder("descend"); return album(categoryId, null, sorter, page); } @GetMapping("/{id}/items/most-read") public ApiResponse mostRead(@PathVariable("id") String categoryId) { Page page = new Page(); page.setLimit(10); page.setPage(1); return items(categoryId, null, null, page); } @GetMapping("/{id}/items/recommends") public ApiResponse recommends(@PathVariable("id") String categoryId) { return mostRead(categoryId); } @GetMapping("/related-by-book-type") public ApiResponse relativeCategories(String type) { return RestfulUtil.success(categoryService.findRelativeCategoriesByBookType(BookType.valueOfCode(type))); } @GetMapping("/suggestion") public ApiResponse suggestion(@RequestParam("keyword") String keyword) { Filter filter = new Filter(); filter.put("name", new String[]{keyword}); Sorter sorter = null; Page page = new Page(); page.setLimit(10); page.setPage(1); return collection(filter, sorter, page); } @GetMapping public ApiResponse collection(@RequestParam("filter") Filter filter, @RequestParam("sorter") Sorter sorter, @ModelAttribute Page page) { PageSlice<CategoryVO> slice = categoryService.findAllIntegrally(CategoryType.Category, filter, sorter, page); return RestfulUtil.list(slice); } }
true
b5ddceb36eba65b055626b32dd938479db51c862
Java
AbrorHoshimov/SpringModul2les1task1
/src/main/java/com/example/lesson1task1/payload/WorkerDto.java
UTF-8
270
1.664063
2
[]
no_license
package com.example.lesson1task1.payload; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @AllArgsConstructor @NoArgsConstructor @Data public class WorkerDto { private String name,street,home; private int departmentId; }
true
1f72a99254b4e6143b010e9be592784217d571b7
Java
itcloudy/micro
/micro-common/src/main/java/com/hechihan/micro/common/util/jwt/JwtHelper.java
UTF-8
2,158
2.53125
3
[]
no_license
/** * @author: cloudy Date: 2018/1/30 Time: 16:24 * @email: 272685110@qq.com * @description: * @project: micro */ package com.hechihan.micro.common.util.jwt; import com.hechihan.micro.common.constants.CommonConstants; import com.hechihan.micro.common.util.KeyHelper; import com.hechihan.micro.common.util.StringHelper; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import lombok.extern.slf4j.Slf4j; import org.joda.time.DateTime; @Slf4j public class JwtHelper { /** * 加密token * @param jwtInfo * @param expireTime * @return * @throws Exception */ public static String generateToken(JwtInfo jwtInfo, String priKeyPath, int expireTime) throws Exception{ String compactJws = Jwts.builder() .setSubject(jwtInfo.getUsername()) .claim(CommonConstants.JWT_KEY_USER_ID,jwtInfo.getUserId()) .claim(CommonConstants.JWT_KEY_NAME,jwtInfo.getName()) .setExpiration(DateTime.now().plusSeconds(expireTime).toDate()) .signWith(SignatureAlgorithm.RS256, KeyHelper.getPrivateKey(priKeyPath)) .compact(); return compactJws; } /** * 公钥解析token * @param token * @param pubKeyPath * @return * @throws Exception */ public static Jws<Claims> parserToken(String token,String pubKeyPath) throws Exception{ Jws<Claims> claimsJwts = Jwts.parser().setSigningKey(KeyHelper.getPublicKey(pubKeyPath)).parseClaimsJws(token); return claimsJwts; } /** * 获取用户信息 * @param token * @param pubKeyPath * @return */ public static JwtInfo getInfoFromToken(String token, String pubKeyPath) throws Exception { Jws<Claims> claimsJws = parserToken(token,pubKeyPath); Claims body = claimsJws.getBody(); return new JwtInfo(body.getSubject(), StringHelper.getObjectValue(body.get(CommonConstants.JWT_KEY_USER_ID)), StringHelper.getObjectValue(body.get(CommonConstants.JWT_KEY_NAME))); } }
true
b12b3b14acbd07e0b15a4ca79d357fd06d0e6301
Java
thbdy/SG
/app/src/main/java/com/zhangf/unnamed/App.java
UTF-8
3,528
2.375
2
[]
no_license
package com.zhangf.unnamed; import android.app.Application; import android.content.Context; import android.support.annotation.NonNull; import com.google.gson.Gson; import com.scwang.smartrefresh.layout.SmartRefreshLayout; import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator; import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator; import com.scwang.smartrefresh.layout.api.RefreshFooter; import com.scwang.smartrefresh.layout.api.RefreshHeader; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.footer.ClassicsFooter; import com.scwang.smartrefresh.layout.header.ClassicsHeader; import com.zhangf.unnamed.utils.SaveCookiesUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; import okhttp3.Cookie; public class App extends Application { private static final String TAG = "App"; private static App app; @Override public void onCreate() { super.onCreate(); app = this; initSmartRefreshLayout(); } /** * 存储cookie * * @param cookies */ public void saveCookie(List<Cookie> cookies) { synchronized (cookieList) { for (int i = 0; i < cookies.size(); i++) { for (int k = 0; k < cookieList.size(); k++) { if (cookieList.get(k).name().equals(cookies.get(i).name())) { cookieList.remove(k); } } } // for(Cookie cookie:cookies){ // Log.e(TAG, "saveCookie: "+cookie.toString()); // } cookieList.addAll(cookies); for (Cookie cookie : cookieList) { SaveCookiesUtils.put(this, cookie.name(), new Gson().toJson(cookie)); } } } /** * 获取cookie * * @return */ public List<Cookie> getCookie() { synchronized (cookieList){ if ( cookieList.size() <= 0) { Map<String, ?> cookies = SaveCookiesUtils.getAll(this); for (Object o : cookies.entrySet()) { Map.Entry entry = (Map.Entry) o; String val = (String) entry.getValue(); cookieList.add(new Gson().fromJson(val, Cookie.class)); } } // for(Cookie cookie: cookieList){ // Log.e(TAG, "getCookie: "+cookie.toString()); // } return cookieList; } } private void initSmartRefreshLayout() { SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() { @Override public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) { ClassicsHeader header = new ClassicsHeader(context); return header;//指定为经典Header,默认是 贝塞尔雷达Header } }); SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() { @NonNull @Override public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) { ClassicsFooter footer = new ClassicsFooter(context); return footer; } }); } public void clearCookies() { cookieList.clear(); } private static final List<Cookie> cookieList = new ArrayList<>(); public static App getApp() { return app; } }
true
715d006ad52d63008ff8366ef6d9a13c6ee9f2c5
Java
meysamaghighi/Kattis
/Catalan/j.java
UTF-8
607
3.015625
3
[]
no_license
import java.math.BigInteger; import java.util.Scanner; public class j { public static BigInteger[] cat; public static void main(String[] args) { Scanner in = new Scanner(System.in); int q,n; q = in.nextInt(); cat = new BigInteger[5010]; cat[0] = BigInteger.ONE; cat[1] = BigInteger.ONE; while (q > 0){ q--; n = in.nextInt(); System.out.println(catalan(n)); } } private static BigInteger catalan(int n){ if (cat[n] != null) return cat[n]; BigInteger c = BigInteger.valueOf(4*n-2).multiply(catalan(n-1)).divide(BigInteger.valueOf(n+1)); return cat[n] = c; } }
true
f710aebddb400a744278b9176303348760794551
Java
oranshiner/oran1
/app/src/main/java/com/example/oran/MapProject/activities/SecondActivity.java
UTF-8
926
2.046875
2
[]
no_license
package com.example.oran.MapProject.activities; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import com.example.oran.MapProject.R; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; public class SecondActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); double latitude = getIntent().getDoubleExtra("latitude", 0); double longitude = getIntent().getDoubleExtra("longitude", 0); // SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment2); // The fragment will read the new arguments and will initialize itself based on them // savedInstanceState.put.setArguments(bundleArguments); } }
true
a6702af84c7ceb4aef64d1ccbb41e6f6bc88bc47
Java
vasudhareddy/ebi
/src/main/java/com/embl/assignment/controllers/DateController.java
UTF-8
726
2.40625
2
[]
no_license
package com.embl.assignment.controllers; import com.embl.assignment.model.*; import org.springframework.beans.factory.annotation.*; import org.springframework.http.*; import org.springframework.web.bind.annotation.*; import java.time.*; import java.time.format.*; @RestController public class DateController { @Value("${datepattern}") String datePattern; @GetMapping(value = "/date", produces = MediaType.APPLICATION_JSON_VALUE) public DateResponse fetchDate() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(datePattern); String format = formatter.format(ZonedDateTime.now()); DateResponse dateResponse = new DateResponse(format); return dateResponse; } }
true
6e7091b8a31da398d5cec054a28fe072845e01c8
Java
dinhphuong99/BtClassromModule4
/bank_manager/src/main/java/group/service/deposit/DepositServiceImpl.java
UTF-8
915
2.21875
2
[]
no_license
package group.service.deposit; import group.model.Customer; import group.model.Deposit; import group.repository.ICustomerRepository; import group.repository.IDepositRepository; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import java.util.Optional; public class DepositServiceImpl implements IDepositService { @Autowired IDepositRepository depositRepository; @Override public List<Deposit> findAll() { return (List<Deposit>) depositRepository.findAll(); } @Override public void save(Deposit deposit) { depositRepository.save(deposit); } @Override public Optional<Deposit> findById(long id) { return depositRepository.findById(id); } @Override public void update(long id, Deposit deposit) { } @Override public void remove(long id) { depositRepository.deleteById(id); } }
true
a66b2acf796745faa01c1ec0498c8f175265b52a
Java
cristoprogramador/PRO
/pro.07Arrays/src/_03Ejercicios/_09TocayosConArrayLis.java
UTF-8
740
3.734375
4
[]
no_license
package _03Ejercicios; import java.util.Arrays; import java.util.List; public class _09TocayosConArrayLis { public static void main(String[] args) { String[] grupo1 = {"Bartolo", "David", "Esteban", "German", "Javi"}; String[] grupo2 = {"Ana", "Bartolo", "Carlos", "David", "Esteban", "Fernando"}; List<String> g1 = Arrays.asList(grupo1); List<String> g2 = Arrays.asList(grupo2); // Recorremos los nombres del g1 for (String nombre : g1) { if (g2.indexOf(nombre) != -1) System.out.println(nombre + " tiene tocayo en el gurpo 2"); } // Recorremos los nombres del g1 for (String nombre : g1) { if (g2.contains(nombre)) System.out.println(nombre + " tiene tocayo en el gurpo 2"); } } }
true
ef0e5127370e94605b7dea5194676dd6ab29868f
Java
CamelBell007/interactiveAd
/suspendinter/src/main/java/com/interactive/suspend/ad/html/load/AdListLoadTask.java
UTF-8
8,581
1.859375
2
[]
no_license
package com.interactive.suspend.ad.html.load; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.text.TextUtils; import android.util.Log; import com.interactive.suspend.ad.constant.Constants; import com.interactive.suspend.ad.db.AdInfo; import com.interactive.suspend.ad.db.AvDatabaseUtils; import com.interactive.suspend.ad.html.FetchAdResult; import com.interactive.suspend.ad.http.NetworkUtils; import com.interactive.suspend.ad.util.LogUtil; import com.interactive.suspend.ad.util.PreferenceUtils; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** * Created by csc on 15/5/20. */ public class AdListLoadTask extends AsyncTask<Void, Void, FetchAdResult> { private static final String TAG = AdListLoadTask.class.getSimpleName(); private Context mContext; private String sourceId; private String excludePackages; private int limitNumber; private int pageNumber; private int creatives; private String market; private String adpkg; private long adpkgSize; private AdListLoadTaskListener mListener; // clean cache when refresh, keep cache when loading more private boolean cacheClean = true; private String adType; private int subType; private int requestType; private boolean videoAllow; public AdListLoadTask(Context mContext, String sourceId, String excludePackages, int limitNumber, int pageNumber, int creatives, String market, String adpkg, long adpkgSize, AdListLoadTaskListener mListener, boolean cacheClean, String adType, int subType, boolean videoAllow, int requestType) { this.mContext = mContext.getApplicationContext(); this.sourceId = sourceId; this.excludePackages = excludePackages; this.limitNumber = limitNumber; this.pageNumber = pageNumber; this.creatives = creatives; this.mListener = mListener; this.market = market; this.cacheClean = cacheClean; this.adpkg = adpkg; this.adpkgSize = adpkgSize; this.adType = adType; this.subType = subType; this.requestType = requestType; this.videoAllow = videoAllow; } protected void onPreExecute() { Log.d(LogUtil.TAG,"onPreExecute"); if (mListener != null) { mListener.onLoadAdListStart(); } } @Override protected FetchAdResult doInBackground(Void... params) { if (TextUtils.isEmpty(sourceId)) { return null; } FetchAdResult ads = NetworkUtils.fetchAd(mContext, sourceId, excludePackages, limitNumber, pageNumber, creatives, market, adType, subType, videoAllow, adpkg, adpkgSize, requestType); if (!FetchAdResult.isFailed(ads)) { List<AdInfo> adInfoList = new ArrayList<AdInfo>(); for (FetchAdResult.Ad data : ads.ads.ad) { if (!checkAdInfoError(data)) { AdInfo info = new AdInfo(data, adType); adInfoList.add(info); // L.e("VC-->DB-->updateAdToDatabase", "AdListLoadTask"); AvDatabaseUtils.updateAdToDatabase(mContext, info); } } if (adpkgSize > 0) { //下载中的app大小 savePkgsForSize(adpkgSize, adInfoList); } //是否删除数据 if (cacheClean) { removeDeprecatedAds(mContext, adInfoList); } return ads; } return null; } @Override protected void onPostExecute(final FetchAdResult result) { SharedPreferences sp = mContext.getSharedPreferences(Constants.Preference.PREF_NAME, Context.MODE_PRIVATE); if (FetchAdResult.isFailed(result) && mListener != null) { Log.d(TAG, "load ad failed"); Error mError = new Error("fetch raw data error"); mListener.onLoadAdListFail(mError); mListener = null; return; } if (adType.equals(Constants.ApxAdType.APPWALL)) { try { sp.edit().putLong(Constants.Preference.LAST_GET_APPWALL_TASK_SUCCESS_TIME, System.currentTimeMillis()).apply(); } catch (Throwable e) { e.printStackTrace(); } } else if (adType.equals(Constants.ApxAdType.NATIVE)) { try { sp.edit().putLong(Constants.Preference.LAST_GET_NATIVE_TASK_SUCCESS_TIME, System.currentTimeMillis()).apply(); } catch (Throwable e) { e.printStackTrace(); } } else if (adType.equals(Constants.ApxAdType.REWARD)) { try { sp.edit().putLong(Constants.Preference.LAST_GET_REWARD_TASK_SUCCESS_TIME, System.currentTimeMillis()).apply(); } catch (Throwable e) { e.printStackTrace(); } } else if (adType.equals(Constants.ApxAdType.PLAYABLE)) { try { sp.edit().putLong(Constants.Preference.LAST_GET_PLAYABLE_TASK_SUCCESS_TIME, System.currentTimeMillis()).apply(); } catch (Throwable e) { e.printStackTrace(); } } else if (adType.equals(Constants.ApxAdType.SMART)) { try { sp.edit().putLong(Constants.Preference.LAST_GET_SMART_TASK_SUCCESS_TIME, System.currentTimeMillis()).apply(); } catch (Throwable e) { e.printStackTrace(); } } if (mListener != null) { mListener.onLoadAdListSuccess(result.ads.ad); } mListener = null; } private boolean checkAdInfoError(FetchAdResult.Ad ad) { boolean isError = false; if (TextUtils.isEmpty(ad.campaignID) || TextUtils.isEmpty(ad.packageName) || TextUtils.isEmpty(ad.clickURL) || TextUtils.isEmpty(ad.icon)) { isError = true; } return isError; } private void removeDeprecatedAds(Context context, List<AdInfo> newDatas) { if (newDatas == null || newDatas.size() == 0) { return; } List<AdInfo> cached = null; if (newDatas.get(0).type.equals(Constants.ApxAdType.APPWALL)) { cached = AvDatabaseUtils.getCacheAppWallData(context, -1, Constants.ActivityAd.SORT_ALL); } else if (newDatas.get(0).type.equals(Constants.ApxAdType.NATIVE)) { cached = AvDatabaseUtils.getCacheNativeAdData(context, -1, Constants.NativeAdStyle.SMALL); } else if (newDatas.get(0).type.equals(Constants.ApxAdType.REWARD)) { cached = AvDatabaseUtils.getCacheRewardAdData(context, -1); } else if (newDatas.get(0).type.equals(Constants.ApxAdType.PLAYABLE)) { cached = AvDatabaseUtils.getCachePlayableAdData(context, -1); } else if (newDatas.get(0).type.equals(Constants.ApxAdType.SMART)) { cached = AvDatabaseUtils.getCacheSmartAdData(context, -1); } if (cached == null || cached.size() == 0) { return; } HashSet<String> newIds = new HashSet<>(); for (int i = 0; i < newDatas.size(); i++) { newIds.add(newDatas.get(i).campaignid); } for (int i = 0; i < cached.size(); i++) { AdInfo info = cached.get(i); if (!newIds.contains(info.campaignid)) { // L.d("VC--DB-->AdListLoadTask", AdColumns.CAMPAIGN_ID + ": " + info.campaignid); AvDatabaseUtils.removeData(context, info); } } } private void savePkgsForSize(long pkgSize, List<AdInfo> data) { if (pkgSize > 0 && data != null && data.size() > 0) { HashSet<String> matchPkgs = new HashSet<>(); for (AdInfo info : data) { if (!matchPkgs.contains(info.pkgname)) { matchPkgs.add(info.pkgname); } } StringBuilder sb = new StringBuilder(); for (String str : matchPkgs) { sb.append(str).append(";"); } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); Log.e(TAG, "pkgs: " + sb.toString() + ", size: " + pkgSize); if (!TextUtils.isEmpty(sb.toString())) { PreferenceUtils.setPkgsWithSameSize(mContext, sb.toString()); } } } } }
true
89f613506b83f3c44c225729b7290375964d3d2f
Java
msgpo/mantissa
/src/test/java/org/spaceroots/mantissa/utilities/MappableScalarTest.java
UTF-8
1,695
2.640625
3
[]
no_license
package org.spaceroots.mantissa.utilities; import junit.framework.*; public class MappableScalarTest extends TestCase { public MappableScalarTest(String name) { super(name); mapper = null; scalar1 = null; scalar2 = null; scalar3 = null; } public void testDimensionCheck() { assertTrue(mapper.getDataArray().length == 3); } public void testUpdateObjects() { double[] data = new double [mapper.getDataArray().length]; for (int i = 0; i < data.length; ++i) { data [i] = i * 0.1; } mapper.updateObjects(data); assertTrue(Math.abs(scalar1.getValue() - 0.0) < 1.0e-10); assertTrue(Math.abs(scalar2.getValue() - 0.1) < 1.0e-10); assertTrue(Math.abs(scalar3.getValue() - 0.2) < 1.0e-10); } public void testUpdateArray() { scalar1.setValue(00.0); scalar2.setValue(10.0); scalar3.setValue(20.0); mapper.updateArray(); double[] data = mapper.getDataArray(); for (int i = 0; i < data.length; ++i) { assertTrue(Math.abs(data [i] - i * 10.0) < 1.0e-10); } } public static Test suite() { return new TestSuite(MappableScalarTest.class); } public void setUp() { scalar1 = new MappableScalar(); scalar2 = new MappableScalar(2); scalar3 = new MappableScalar(-3); mapper = new ArrayMapper(); mapper.manageMappable(scalar1); mapper.manageMappable(scalar2); mapper.manageMappable(scalar3); } public void tearDown() { scalar1 = null; scalar2 = null; scalar3 = null; mapper = null; } private MappableScalar scalar1; private MappableScalar scalar2; private MappableScalar scalar3; private ArrayMapper mapper; }
true
4dd25e43e08d0764738f6037aa06d79f91673a8e
Java
tasleemarshu/Arshiya_Tasleem_845007
/src/test/java/com/Pages/Loginpage.java
UTF-8
1,927
2.609375
3
[]
no_license
package com.Pages; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import ExcelUtility.ExcelPage; public class Loginpage { // inspecting the elements in the application WebDriver driver; ExcelPage e = new ExcelPage(); public Loginpage(WebDriver driver) { this.driver=driver; } public void url(String browser) // launching the application using multiple browsers { if (browser.equalsIgnoreCase("chrome")) { System.setProperty("webdriver.chrome.driver", "Drivers\\chromedriver.exe"); driver = new ChromeDriver(); // to launch the application in chrome browser } else if (browser.equalsIgnoreCase("firefox")) { System.setProperty("webdriver.gecko.driver", "Drivers\\geckodriver.exe"); driver = new FirefoxDriver(); // to launch the application in firefox browser } driver.manage().window().maximize(); // maximizes the browser driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS); // providing waiting time } public void Launch_URL() // using webdriver get visting the testing website { driver.get("http://automationpractice.com/index.php"); // takes us to homepage of the application System.out.println(driver.getTitle()); // displays title of the page } public void Signin() { driver.findElement(By.xpath("//*[@id=\"header\"]/div[2]/div/div/nav/div[1]/a")).click(); } public void usernameandpassword() throws IOException,IncompatibleClassChangeError { driver.findElement(By.xpath("//*[@id=\"email\"]")).sendKeys(e.excel_username(1)); driver.findElement(By.xpath("//*[@id=\"passwd\"]")).sendKeys(e.excel_password(1)); } public void Click() { driver.findElement(By.xpath("//*[@id=\"SubmitLogin\"]/span")).click(); } }
true
4c6fd0c473b452981ad4385a7ff7402286dec1dc
Java
singledemon/cloud
/platform-common/platform-common-core/src/main/java/com/alin/common/core/subjectobserver/SubjectObserverStartHandler.java
UTF-8
2,198
2.453125
2
[]
no_license
package com.alin.common.core.subjectobserver; import com.alin.common.core.subjectobserver.annotation.SubjectObserver; import com.alin.common.core.subjectobserver.service.IObserver; import com.alin.common.core.subjectobserver.service.ISubject; import com.alin.common.core.util.SpringContextHolder; import lombok.extern.java.Log; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import java.util.Collection; import java.util.Map; /** * 观察者注册服务 自启动类 * * @Author maql * @create 2019/6/18 11:49 */ @Component @Log public class SubjectObserverStartHandler implements CommandLineRunner { /*@Value("${switch.on}") private Boolean switchOn;*/ @Autowired private ApplicationContext applicationContext; @Override public void run(String... args) throws Exception { ApplicationContext context = SpringContextHolder.getApplicationContext(); log.info("Initing SubjectObserver on starting ! [SubjectObserver]"); this.registSubjectObserverHandler(context); } /** * 注册数据处理事件 * * @param context */ private void registSubjectObserverHandler(ApplicationContext context) { //获取所有观察者列表bean Map<String, Object> observerMaps = context.getBeansWithAnnotation(SubjectObserver.class); if (observerMaps == null || observerMaps.size() < 1) { return; } Collection<Object> observers = observerMaps.values(); for (Object obj : observers) { if (obj instanceof IObserver) { IObserver hd = (IObserver) obj; SubjectObserver subjectObserver = hd.getClass().getAnnotation(SubjectObserver.class); log.info("Regist Subject to Observer ---" + subjectObserver.subject()); ISubject tmpSubject = (ISubject) SpringContextHolder.getBean(subjectObserver.subject());// context.getBean(subjectObserver.subject());// tmpSubject.register(hd); } } } }
true
aee94e90b271a66a13bb58f06eb92c23128aa7de
Java
junit/GenesisServer
/Code_Java/test/src/com/genesis/test/dataserver/sqlupdate/UpdateSqlTest.java
UTF-8
3,817
2.671875
3
[]
no_license
package com.genesis.test.dataserver.sqlupdate; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.genesis.core.orm.hibernate.HibernateDBService; import com.genesis.core.reflect.PrivateUtil; import com.genesis.dataserver.sqlupdate.SqlUpdate; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.TreeMap; import java.util.TreeSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /** * 数据库版本更新测试 * @author Joey * */ public class UpdateSqlTest { HibernateDBService dbService; @Test public void update_map_should_be_right() throws IOException { //1.1正常更新——增量 TreeSet<Integer> treeSet = Sets.newTreeSet(Lists.newArrayList(1, 2, 3)); TreeMap<Integer, Node> treeMap = new TreeMap<>(); treeMap.put(1, new Node(1, null)); treeMap.put(2, new Node(2, null)); treeMap.put(3, new Node(3, null)); treeMap.put(4, new Node(4, null)); treeMap.put(5, new Node(5, null)); { Object temp = PrivateUtil.invoke(new SqlUpdate(), "getUpdateMap", new Class[]{treeSet.getClass(), treeMap.getClass()}, new Object[]{treeSet, treeMap}); @SuppressWarnings("unchecked") TreeMap<Integer, Node> updateMap = (TreeMap<Integer, Node>) temp; assertThat(updateMap.size(), is(2)); assertThat(updateMap.firstKey(), is(4)); assertThat(updateMap.lastKey(), is(5)); } //1.2正常更新——从无到有 { treeSet.clear(); Object temp = PrivateUtil.invoke(new SqlUpdate(), "getUpdateMap", new Class[]{treeSet.getClass(), treeMap.getClass()}, new Object[]{treeSet, treeMap}); @SuppressWarnings("unchecked") TreeMap<Integer, Node> updateMap = (TreeMap<Integer, Node>) temp; assertThat(updateMap.size(), is(5)); assertThat(updateMap.firstKey(), is(1)); assertThat(updateMap.lastKey(), is(5)); } //2.1非正常更新——已更过的版本有缺失 { treeSet.add(1); treeSet.add(3); try { Object temp = PrivateUtil.invoke(new SqlUpdate(), "getUpdateMap", new Class[]{treeSet.getClass(), treeMap.getClass()}, new Object[]{treeSet, treeMap}); @SuppressWarnings("unchecked") TreeMap<Integer, Node> updateMap = (TreeMap<Integer, Node>) temp; assertThat(1, is(2)); } catch (Exception e) { //出异常就正确了 } } //2.2非正常更新——已更过的版本不存在 { treeSet.clear(); treeSet.add(0); treeSet.add(1); treeSet.add(3); try { Object temp = PrivateUtil.invoke(new SqlUpdate(), "getUpdateMap", new Class[]{treeSet.getClass(), treeMap.getClass()}, new Object[]{treeSet, treeMap}); @SuppressWarnings("unchecked") TreeMap<Integer, Node> updateMap = (TreeMap<Integer, Node>) temp; assertThat(1, is(2)); } catch (Exception e) { //出异常就正确了 } } } class Node { int version; File file; public Node(int version, File file) { this.version = version; this.file = file; } } }
true
37153c407124aa94bd67ef223f88889059ad7f4d
Java
MEJIOMAH17/rocketbank-api
/reverse/Rocketbank_All_3.12.4_source_from_JADX/sources/ru/rocketbank/r2d2/shop/cart/ShopCartActivity.java
UTF-8
9,325
1.773438
2
[]
no_license
package ru.rocketbank.r2d2.shop.cart; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import java.util.HashMap; import kotlin.jvm.internal.Intrinsics; import ru.rocketbank.core.manager.PresenterManager; import ru.rocketbank.core.model.UserModel; import ru.rocketbank.core.model.shop.Cart; import ru.rocketbank.core.model.shop.CartItem; import ru.rocketbank.core.model.shop.ShopItem; import ru.rocketbank.core.widgets.RocketButton; import ru.rocketbank.r2d2.C0859R; import ru.rocketbank.r2d2.PresenterSecuredActivity; import ru.rocketbank.r2d2.databinding.ActivityShopCartBinding; import ru.rocketbank.r2d2.fragments.rocketrouble.RocketRubleInfoActivity; import ru.rocketbank.r2d2.shop.cart.ShopCartContract.Presenter.DefaultImpls; import ru.rocketbank.r2d2.shop.cart.ShopCartContract.View; import ru.rocketbank.r2d2.shop.details.ShopDetailsActivity; import ru.rocketbank.r2d2.shop.feed.ShopFragmentData; import ru.rocketbank.r2d2.shop.order.ShopOrderActivity; /* compiled from: ShopCartActivity.kt */ public final class ShopCartActivity extends PresenterSecuredActivity<ShopCartPresenter> implements View { public static final Companion Companion = new Companion(); private static final int REQUEST_CODE = 0; private HashMap _$_findViewCache; private final ShopCartViewModel data = new ShopCartViewModel(); public ShopCartAdapter shopCartAdapter; /* compiled from: ShopCartActivity.kt */ public static final class Companion { private Companion() { } public final int getREQUEST_CODE() { return ShopCartActivity.REQUEST_CODE; } public final void startActivity(Context context) { Intrinsics.checkParameterIsNotNull(context, "context"); context.startActivity(new Intent(context, ShopCartActivity.class)); } } public final void _$_clearFindViewByIdCache() { if (this._$_findViewCache != null) { this._$_findViewCache.clear(); } } public final android.view.View _$_findCachedViewById(int i) { if (this._$_findViewCache == null) { this._$_findViewCache = new HashMap(); } android.view.View view = (android.view.View) this._$_findViewCache.get(Integer.valueOf(i)); if (view != null) { return view; } view = findViewById(i); this._$_findViewCache.put(Integer.valueOf(i), view); return view; } public final ShopCartViewModel getData() { return this.data; } public final ShopCartAdapter getShopCartAdapter() { ShopCartAdapter shopCartAdapter = this.shopCartAdapter; if (shopCartAdapter == null) { Intrinsics.throwUninitializedPropertyAccessException("shopCartAdapter"); } return shopCartAdapter; } public final void setShopCartAdapter(ShopCartAdapter shopCartAdapter) { Intrinsics.checkParameterIsNotNull(shopCartAdapter, "<set-?>"); this.shopCartAdapter = shopCartAdapter; } public final ShopCartPresenter createPresenter() { PresenterManager presenterManager = PresenterManager.INSTANCE; return (ShopCartPresenter) PresenterManager.getOrCreatePresenter("df346d56-a4d2-48c4-8da8-9f5411566c8f", ShopCartPresenter.class); } protected final void onCreate(Bundle bundle) { super.onCreate(bundle); bundle = DataBindingUtil.setContentView(this, C0859R.layout.activity_shop_cart); Intrinsics.checkExpressionValueIsNotNull(bundle, "DataBindingUtil.setConte…ayout.activity_shop_cart)"); ActivityShopCartBinding activityShopCartBinding = (ActivityShopCartBinding) bundle; setSupportActionBar((Toolbar) _$_findCachedViewById(C0859R.id.toolbar)); ActionBar supportActionBar = getSupportActionBar(); if (supportActionBar != null) { supportActionBar.setDisplayHomeAsUpEnabled(true); } setTitle(C0859R.string.cart_activity_title); activityShopCartBinding.setData(this.data); ((ShopCartPresenter) getPresenter()).setView(this); this.shopCartAdapter = new ShopCartAdapter(new ShopCartActivity$onCreate$1(this), new ShopCartActivity$onCreate$2(this), new ShopCartActivity$onCreate$3(this)); RecyclerView recyclerView = (RecyclerView) _$_findCachedViewById(C0859R.id.recyclerView); Intrinsics.checkExpressionValueIsNotNull(recyclerView, "recyclerView"); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView = (RecyclerView) _$_findCachedViewById(C0859R.id.recyclerView); Intrinsics.checkExpressionValueIsNotNull(recyclerView, "recyclerView"); ShopCartAdapter shopCartAdapter = this.shopCartAdapter; if (shopCartAdapter == null) { Intrinsics.throwUninitializedPropertyAccessException("shopCartAdapter"); } recyclerView.setAdapter(shopCartAdapter); ((RocketButton) _$_findCachedViewById(C0859R.id.checkoutButton)).setOnClickListener(new ShopCartActivity$onCreate$4(this)); } protected final void onStart() { super.onStart(); DefaultImpls.load$default((ShopCartPresenter) getPresenter(), false, 1, null); } public final void onUserModel(UserModel userModel) { super.onUserModel(userModel); DefaultImpls.load$default((ShopCartPresenter) getPresenter(), false, 1, null); } public final void onItemDeleted(CartItem cartItem) { Intrinsics.checkParameterIsNotNull(cartItem, "cartItem"); ShopCartAdapter shopCartAdapter = this.shopCartAdapter; if (shopCartAdapter == null) { Intrinsics.throwUninitializedPropertyAccessException("shopCartAdapter"); } shopCartAdapter.delete(cartItem); } public final void showCheckoutActivity(Cart cart) { Intrinsics.checkParameterIsNotNull(cart, "cart"); startActivityForResult(ShopOrderActivity.Companion.createIntent(this, cart), REQUEST_CODE); } protected final void onActivityResult(int i, int i2, Intent intent) { super.onActivityResult(i, i2, intent); if (i == REQUEST_CODE && i2 == -1) { setResult(-1); finish(); } } public final void onLoadingInProgress() { ShopFragmentData.set$default(this.data, true, false, false, false, 14, null); } public final void onCartLoaded(Cart cart, double d) { Intrinsics.checkParameterIsNotNull(cart, "cart"); ShopFragmentData.set$default(this.data, false, false, false, true, 7, null); ShopCartAdapter shopCartAdapter = this.shopCartAdapter; if (shopCartAdapter == null) { Intrinsics.throwUninitializedPropertyAccessException("shopCartAdapter"); } shopCartAdapter.setData(cart.getItems(), cart.getAmount(), d); } public final void onItemsLoadingError() { ShopFragmentData.set$default(this.data, false, true, false, false, 13, null); } public final void onItemsEmpty() { ShopFragmentData.set$default(this.data, false, false, true, false, 11, null); } public final void showItemInfo(ShopItem shopItem) { Intrinsics.checkParameterIsNotNull(shopItem, "shopItem"); ShopDetailsActivity.Companion.startActivity(this, shopItem); } public final void updateAmount(double d) { ShopCartAdapter shopCartAdapter = this.shopCartAdapter; if (shopCartAdapter == null) { Intrinsics.throwUninitializedPropertyAccessException("shopCartAdapter"); } shopCartAdapter.getAmount().set(d); } public final void updateDeficit(double d) { ShopCartAdapter shopCartAdapter = this.shopCartAdapter; if (shopCartAdapter == null) { Intrinsics.throwUninitializedPropertyAccessException("shopCartAdapter"); } shopCartAdapter.setDeficit(d); } public final void hideDeficit() { ShopCartAdapter shopCartAdapter = this.shopCartAdapter; if (shopCartAdapter == null) { Intrinsics.throwUninitializedPropertyAccessException("shopCartAdapter"); } shopCartAdapter.setDeficit(0.0d); } public final void enableCheckoutButton(boolean z) { this.data.getEnableCheckoutButton().set(z); } public final void showRocketrublesInfo() { ShopCartAdapter shopCartAdapter = this.shopCartAdapter; if (shopCartAdapter == null) { Intrinsics.throwUninitializedPropertyAccessException("shopCartAdapter"); } android.view.View infoButton = shopCartAdapter.getInfoButton(); int[] iArr = new int[]{0, 0}; if (infoButton != null) { infoButton.getLocationOnScreen(iArr); } int i = 0; int width = iArr[0] + ((infoButton != null ? infoButton.getWidth() : 0) / 2); int i2 = iArr[1]; if (infoButton != null) { i = infoButton.getWidth(); } RocketRubleInfoActivity.Companion.startActivity(this, true, width, i2 + (i / 2)); } }
true
4865a4fc73c07897e204908dab0b5668ac858c3a
Java
darshankumar/Modern-Java-Example
/JavaEight_Example/src/com/learn/javaeight/stream/BoxingUnboxingStreamExample.java
UTF-8
997
3.90625
4
[]
no_license
package com.learn.javaeight.stream; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; public class BoxingUnboxingStreamExample { public static void main(String[] args) { System.out.println("###################################### Start " +BoxingUnboxingStreamExample.class.getSimpleName()); IntStream intStream = IntStream.rangeClosed(0, 5000); // Stream of primitive List<Integer> numList = intStream.boxed().collect(Collectors.toList()); // making Integer List numList.forEach(System.out::println); Optional<Integer> sum = numList.stream().reduce((a,b)->a+b); sum.ifPresent(System.out::println); int sum1 = numList.stream().mapToInt(Integer::intValue).sum(); // unboxing System.out.println("Sum :: " + sum1); System.out.println("###################################### Ends " +BoxingUnboxingStreamExample.class.getSimpleName()); } }
true
ba379b38d34e267ec596b4c1aeb5900b19ed85ab
Java
waleedsalah088/Udacity-Google-India-Challenge-Scholarship-Projects-Phase-2
/AapnuAmdavad/app/src/main/java/com/wordpress/piedcipher/aapnuamdavad/activities/RestaurantActivity.java
UTF-8
3,497
2.375
2
[]
no_license
package com.wordpress.piedcipher.aapnuamdavad.activities; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.wordpress.piedcipher.aapnuamdavad.R; import com.wordpress.piedcipher.aapnuamdavad.models.Restaurant; public class RestaurantActivity extends AppCompatActivity { private String mRestaurantName; private String mRestaurantURL; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_restaurant); initializer(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_events_restaurants_hotels, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.open_in_google_maps: Intent openInGoogleMaps = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("geo:0,0?q=" + mRestaurantName + ", Ahmedabad")); if (openInGoogleMaps.resolveActivity(getPackageManager()) != null) { startActivity(openInGoogleMaps); } break; case R.id.view_more_details: startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(mRestaurantURL))); break; } return true; } /** * This method initializes all the Views, Widgets, Variables and Listeners. */ private void initializer() { ImageView restaurantsRestaurantPhotoImageView = findViewById(R.id.restaurants_restaurant_photo_image_view); TextView restaurantsRestaurantDescriptionTextView = findViewById(R.id.restaurants_restaurant_description_text_view); TextView restaurantsRestaurantContactNumberTextView = findViewById(R.id.restaurants_restaurant_contact_number_text_view); TextView restaurantsRestaurantTimingsTextView = findViewById(R.id.restaurants_restaurant_timings_text_view); RatingBar restaurantsRestaurantReviewRatingBar = findViewById(R.id.restaurants_restaurant_review_rating_bar); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitleTextColor(Color.WHITE); Bundle bundle = getIntent().getExtras(); Restaurant restaurant = null; if (bundle != null) { restaurant = bundle.getParcelable("Restaurant"); } if (restaurant != null) { mRestaurantName = restaurant.getRestaurantName(); setTitle(mRestaurantName); mRestaurantURL = restaurant.getRestaurantURL(); restaurantsRestaurantPhotoImageView.setImageResource(restaurant.getRestaurantPhoto()); restaurantsRestaurantReviewRatingBar.setRating(Float.parseFloat(restaurant.getRestaurantReview())); restaurantsRestaurantDescriptionTextView.setText(restaurant.getRestaurantDescription()); restaurantsRestaurantContactNumberTextView.setText(restaurant.getRestaurantContactNumber()); restaurantsRestaurantTimingsTextView.setText(restaurant.getRestaurantTimings()); } } }
true
673942adef92f7d2b2b90892990acaaad6d3ef54
Java
Amigo-sa/HandsFree
/App/src/main/java/by/citech/handsfree/network/control/IConnCtrl.java
UTF-8
245
1.742188
2
[]
no_license
package by.citech.handsfree.network.control; import by.citech.handsfree.exchange.IExchangeCtrl; public interface IConnCtrl extends IExchangeCtrl { void closeConnection(); void closeConnectionForce(); boolean isAliveConnection(); }
true
aea0375bf0fd78e38558f5075628ea355a96fe07
Java
namget/namgetfingerprint
/app/src/main/java/com/tistory/namget/fingerprint/Util.java
UTF-8
859
2.28125
2
[]
no_license
package com.tistory.namget.fingerprint; import android.content.Context; import android.support.v4.hardware.fingerprint.FingerprintManagerCompat; /** * Created by JaeWooLee on 2017-11-10. */ public class Util { public static boolean isFingerprintAuthAvailable(Context context) { FingerprintManagerCompat mFingerprintManager; mFingerprintManager = FingerprintManagerCompat.from(context); if (mFingerprintManager.isHardwareDetected() && mFingerprintManager.hasEnrolledFingerprints()) { return true; } else { return false; } } public static FingerprintManagerCompat getFingerprintManagerCompat(Context context){ FingerprintManagerCompat mFingerprintManager; mFingerprintManager = FingerprintManagerCompat.from(context); return mFingerprintManager; } }
true
5ad853f157b411b56d59d5e25dd2f9dc2ef2f55e
Java
P79N6A/icse_20_user_study
/methods/Method_23404.java
UTF-8
167
2.8125
3
[]
no_license
/** * Set the high bits of all pixels to opaque. */ protected void opaque(){ for (int i=0; i < pixels.length; i++) { pixels[i]=0xFF000000 | pixels[i]; } }
true
30641f261c20df02bf8558e7b9b4c4de5d970d12
Java
alguojian/HttpUtils
/commonsdk/src/main/java/com/shuwtech/commonsdk/http/adapter/BaseResponseObservable.java
UTF-8
3,704
2.0625
2
[]
no_license
/* * Copyright (C) 2016 Jake Wharton * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.shuwtech.commonsdk.http.adapter; import com.shuwtech.commonsdk.http.response.BaseResponse; import com.shuwtech.commonsdk.mediator.router.RouterUtils; import com.shuwtech.commonsdk.utils.AccountUtils; import com.shuwtech.commonsdk.utils.Toaster; import java.io.IOException; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.CompositeException; import io.reactivex.exceptions.Exceptions; import io.reactivex.plugins.RxJavaPlugins; import retrofit2.HttpException; import retrofit2.Response; /** * 用于BaseResponse的Observable */ final class BaseResponseObservable<T> extends Observable<BaseResponse<T>> { private final Observable<Response<BaseResponse<T>>> upstream; BaseResponseObservable(Observable<Response<BaseResponse<T>>> upstream) { this.upstream = upstream; } @Override protected void subscribeActual(Observer<? super BaseResponse<T>> observer) { upstream.safeSubscribe(new BaseResponseObserver<>(observer)); } private static class BaseResponseObserver<R> implements Observer<Response<BaseResponse<R>>> { private final Observer<? super BaseResponse<R>> observer; BaseResponseObserver(Observer<? super BaseResponse<R>> observer) { this.observer = observer; } @Override public void onSubscribe(Disposable disposable) { observer.onSubscribe(disposable); } @Override public void onNext(Response<BaseResponse<R>> response) { if (response.code() == 401) { //401返回授权失败 observer.onNext(BaseResponse.authFail()); } else if (response.code() == 403) {//token过期,要重新登录 observer.onNext(BaseResponse.authFail()); Toaster.toast("授权信息已过期,请重新登录!"); AccountUtils.logout(); RouterUtils.route2Login(); } else if (response.code() >= 200 && response.code() < 300) { //2xx 返回服务端内容 observer.onNext(response.body()); } else { observer.onNext(BaseResponse.netError()); // 返回网络错误 } } @Override public void onError(Throwable throwable) { try { if (throwable instanceof IOException || throwable instanceof HttpException) { observer.onNext(BaseResponse.netError()); } else { observer.onError(throwable); } } catch (Throwable t) { try { observer.onError(t); } catch (Throwable inner) { Exceptions.throwIfFatal(inner); RxJavaPlugins.onError(new CompositeException(t, inner)); } return; } observer.onComplete(); } @Override public void onComplete() { observer.onComplete(); } } }
true
f83a7ddb99134abbbc69bff55986e503ba3a8b27
Java
RogerVFbr/microservices-poc-atividades
/src/main/java/com/soundlab/atividades/external/AbstractExternalSnsService.java
UTF-8
2,291
2.5
2
[]
no_license
package com.soundlab.atividades.external; import com.amazonaws.services.sns.AmazonSNS; import com.amazonaws.services.sns.model.MessageAttributeValue; import com.amazonaws.services.sns.model.PublishRequest; import com.amazonaws.services.sns.model.PublishResult; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.soundlab.atividades.exceptions.ExternalServiceException; import org.jboss.logging.Logger; import java.util.HashMap; import java.util.Map; public class AbstractExternalSnsService<T> { private static final Logger LOG = Logger.getLogger(AbstractExternalSnsService.class); private final AmazonSNS client; private final String topicArn; private final ObjectMapper mapper = new ObjectMapper(); public AbstractExternalSnsService(AmazonSNS client, String topicArn) { this.client = client; this.topicArn = topicArn; } public void publish(T data) { try { PublishRequest request = new PublishRequest() .withMessage(serializeObject(data)) .withTopicArn(topicArn) .withMessageAttributes(getMessageAttributeMap()); PublishResult result = client.publish(request); LOG.info(String.format("Successfully placed message on SNS. (MessageId: %s | StatusCode: %s)", result.getMessageId(), result.getSdkHttpMetadata().getHttpStatusCode())); } catch (Exception e) { throw new ExternalServiceException("ExternalSnsService", e.getMessage()); } } private String serializeObject(T data) { try { return mapper.writeValueAsString(data); } catch (JsonProcessingException e) { e.printStackTrace(); } return "Serialization error"; } private static Map<String, MessageAttributeValue> getMessageAttributeMap() { Map<String, MessageAttributeValue> messageAttributeMap = new HashMap<>(); MessageAttributeValue messageAttributeValue = new MessageAttributeValue() .withStringValue("application/json") .withDataType("String"); messageAttributeMap.put("contentType", messageAttributeValue); return messageAttributeMap; } }
true
4a6117f2a00d72d586412d2207e3a5ad4661bcda
Java
Drageaux/ProjectOrwell
/app/service/GithubServicePlugin.java
UTF-8
5,006
2.25
2
[ "Apache-2.0" ]
permissive
package service; import com.fasterxml.jackson.databind.JsonNode; import com.feth.play.module.pa.providers.oauth2.OAuth2AuthInfo; import com.feth.play.module.pa.providers.oauth2.OAuth2AuthProvider; import com.google.inject.Inject; import play.Application; import play.Configuration; import play.Plugin; import play.libs.Json; import play.libs.ws.WS; import play.libs.ws.WSRequest; import play.libs.ws.WSResponse; /** * Created by Austin on 11/12/2015. */ public class GithubServicePlugin extends Plugin { public static final String PROVIDER_KEY = "github"; public static final String CLIENT_ID_KEY = "clientId"; public static final String CLIENT_SECRET_KEY = "clientSecret" ; private Application app; private Configuration config = null; private final long timeout = 10000L; private final String CLIENT_ID_PARAM = "client_id" ; private final String CLIENT_SECRET_PARAM = "client_secret" ; @Inject public GithubServicePlugin(final Application app) { this.app = app; config = app.configuration().getConfig("apis").getConfig(PROVIDER_KEY); } public void onStart() { } public void onStop() { } public boolean enabled() { return true; } private WSRequest genRequest(String url, OAuth2AuthInfo authInfo) { return WS .url(url) .setQueryParameter(CLIENT_ID_PARAM, app.configuration().getString(CLIENT_ID_KEY)) .setQueryParameter(CLIENT_SECRET_PARAM, app.configuration().getString(CLIENT_SECRET_KEY)) .setQueryParameter(OAuth2AuthProvider.Constants.ACCESS_TOKEN, authInfo.getAccessToken()); } //Method is currently not used. public JsonNode getUserInfo(OAuth2AuthInfo authInfo) { final WSResponse r = genRequest(config.getString("userInfo"), authInfo).get() .get(timeout); return r.asJson().get(0); } //Get all repositories belonging to current user public JsonNode getRepos(OAuth2AuthInfo authInfo) { //Build url String url = config.getString("userInfo") + "/repos" ; final WSResponse r = genRequest(url, authInfo).get().get(timeout); //System.out.println(r.getBody()); return r.asJson(); } //Get a single repository with the specified id public JsonNode getRepo(OAuth2AuthInfo authInfo, String ownerName, String repoName) { String url = config.getString("repositories") + "/"+ ownerName + "/" + repoName ; final WSResponse r = genRequest(url, authInfo).get().get(timeout); return r.asJson(); } public void createWebhook(OAuth2AuthInfo authInfo, String hooks_url) { boolean hasWebhook = false ; // Check if there's already a webhook that is connected to our website for(JsonNode hook : getWebhooks(authInfo, hooks_url)) { // Check if the current webhook is connected to our website if(hook.get("config") != null && hook.get("config").get("url").asText().startsWith(app.configuration().getString("root"))){ hasWebhook = true ; } } //If a webhook already exists with the current root url as a callback, don't bother making another. if(hasWebhook){ return ; } //Build the config param for webhook post payload JsonNode webhookConfig = Json.newObject() .put("url", app.configuration().getString("root") + "/webhook/github") // Our url for webhooks to hit .put("content_type", "json") // Define the data type received by webhook (json/form) .put("secret", "super_secret") // Optional string, probably should save this to verify incoming data from github .put("insecure_ssl", "1") ; // Will github verify our url when sending webhook data? (0=verified, 1=not verified) // Set the payload being posted to create the webhook. JsonNode webhookPost = Json.newObject() .put("name", "web") .set("config", webhookConfig) ; // Make the post request. final WSResponse r = genRequest(hooks_url, authInfo) .post(webhookPost) .get(timeout); } public void deleteWebhook(OAuth2AuthInfo authInfo, String hooks_url, long hookId) { // Build url in the form "https://api.github.com/repos/:ownerName/:repoName/hooks/:hookId" String url = hooks_url + "/" + hookId ; //No response is returned, but selected webhook is successfully deleted. final WSResponse r = genRequest(url, authInfo) .delete() .get(timeout); } // Get the webhooks for a single specified repository public JsonNode getWebhooks(OAuth2AuthInfo authInfo, String hooks_url) { final WSResponse r = genRequest(hooks_url , authInfo) .get() .get(timeout); return r.asJson(); } }
true
5bb36a6d44c1ebf96f1e4035c87f651539213fd0
Java
saliormoon/arangodb-java-driver
/src/test/java/com/arangodb/example/graph/UpdateAndReplaceVertexExample.java
UTF-8
4,105
2.75
3
[ "Apache-2.0" ]
permissive
package com.arangodb.example.graph; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.arangodb.ArangoException; import com.arangodb.entity.marker.VertexEntity; /** * Update and replace example * * @author a-brandt * */ public class UpdateAndReplaceVertexExample extends BaseExample { private static final String DATABASE_NAME = "UpdateAndReplaceVertexExample"; private static final String GRAPH_NAME = "example_graph1"; private static final String EDGE_COLLECTION_NAME = "edgeColl1"; private static final String VERTEXT_COLLECTION_NAME = "vertexColl1"; @Before public void _before() throws ArangoException { removeTestDatabase(DATABASE_NAME); createDatabase(driver, DATABASE_NAME); createGraph(driver, GRAPH_NAME, EDGE_COLLECTION_NAME, VERTEXT_COLLECTION_NAME); } @After public void _after() { removeTestDatabase(DATABASE_NAME); } @Test public void replaceVertex() throws ArangoException { // printHeadline("replace vertex"); // final Person personA = new Person("A", Person.MALE); final VertexEntity<Person> v1 = createVertex(personA); final Person personB = new Person("B", Person.FEMALE); final VertexEntity<Person> replaceVertex = driver.graphReplaceVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, v1.getDocumentKey(), personB); // document handle is unchanged Assert.assertNotNull(replaceVertex); Assert.assertEquals(v1.getDocumentHandle(), replaceVertex.getDocumentHandle()); // document revision has changed Assert.assertNotEquals(v1.getDocumentRevision(), replaceVertex.getDocumentRevision()); // name changed to "B" Assert.assertNotNull(replaceVertex.getEntity()); Assert.assertEquals(personB.getName(), replaceVertex.getEntity().getName()); } @Test public void updateVertex() throws ArangoException { // printHeadline("update vertex"); // final Person personA = new Person("A", Person.MALE); final VertexEntity<Person> v1 = createVertex(personA); // update one attribute (gender) personA.setGender(Person.FEMALE); final VertexEntity<Person> updateVertex = driver.graphUpdateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, v1.getDocumentKey(), personA, true); // document handle is unchanged Assert.assertNotNull(updateVertex); Assert.assertEquals(v1.getDocumentHandle(), updateVertex.getDocumentHandle()); // document revision has changed Assert.assertNotEquals(v1.getDocumentRevision(), updateVertex.getDocumentRevision()); // gender changed to Person.FEMALE Assert.assertNotNull(updateVertex.getEntity()); Assert.assertEquals(Person.FEMALE, updateVertex.getEntity().getGender()); Assert.assertEquals(personA.getName(), updateVertex.getEntity().getName()); } @Test public void updateOneAttribute() throws ArangoException { // printHeadline("update one vertex attribute"); // final Person personA = new Person("A", Person.MALE); final VertexEntity<Person> v1 = createVertex(personA); // update one attribute (gender) final Person update = new Person(null, Person.FEMALE); driver.graphUpdateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, v1.getDocumentKey(), update, true); // reload vertex final VertexEntity<Person> updateVertex = driver.graphGetVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, v1.getDocumentKey(), Person.class); // document handle is unchanged Assert.assertNotNull(updateVertex); Assert.assertEquals(v1.getDocumentHandle(), updateVertex.getDocumentHandle()); // document revision has changed Assert.assertNotEquals(v1.getDocumentRevision(), updateVertex.getDocumentRevision()); // gender changed to Person.FEMALE Assert.assertNotNull(updateVertex.getEntity()); Assert.assertEquals(update.getGender(), updateVertex.getEntity().getGender()); Assert.assertEquals(personA.getName(), updateVertex.getEntity().getName()); } private VertexEntity<Person> createVertex(final Person person) throws ArangoException { final VertexEntity<Person> v = driver.graphCreateVertex(GRAPH_NAME, VERTEXT_COLLECTION_NAME, person, true); Assert.assertNotNull(v); return v; } }
true
905f22c4117f54e9f30fed764a88663d493cfcc4
Java
EgardoPort/TiendaOnline
/src/java/Controller/LoginFilter.java
UTF-8
2,165
2.703125
3
[]
no_license
/*package Controller; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebFilter("/*") public class LoginFilter implements Filter { @Override public void init(FilterConfig filterConfig) { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpSession session = request.getSession(false); String Uri = request.getContextPath() + "/Login.jsp"; //String tipo = session.getAttribute("tipo_user").toString(); boolean loggeadIn = session != null && session.getAttribute("tipo_user") != null; boolean loginRequest = request.getRequestURI().equals(Uri); if(loggeadIn || loginRequest){ chain.doFilter(req, res); return; }else{ response.sendRedirect(request.getContextPath() + "/Login.jsp"); return; } String requestPath = request.getRequestURI(); //String tipo = session.getAttribute("tipo_user").toString(); if (needsAuthentication(requestPath) == true) { response.sendRedirect(request.getContextPath() + "/Login.jsp"); return; } else if(session.getAttribute("tipo_user") != null){ response.sendRedirect(request.getContextPath() + "/Login.jsp"); return; }else{ chain.doFilter(req, res); return; } } public void destroy() { } private boolean needsAuthentication(String url) { if (url.endsWith("Login.jsp")) { return false; } return true; } }*/
true
d6a42b8f0760a59e3b53ef2d804fed29a3892a9f
Java
Oleg-Stepanenko-owo/GANET_SERVICE
/app/src/main/java/com/ganet/catfish/GANET/Data/FolderData.java
UTF-8
1,566
2.1875
2
[]
no_license
package com.ganet.catfish.GANET.Data; import java.util.Vector; /** * Created by oleg on 28.07.2016. */ /* 1C 684B3102 0376 0F 01 0102 03 00 440065007000650063006800650020 59 PACK | ID | |Folder| | pack/ALL | | FOLDER NAME |number| <GA:183131684B31020376 0F02 02 02 01 0046006F006C00640065007200310031 49> <GA:183131684B31020376 0F02 02 02 11 FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF 8B> <GA:183131684B31020376 0F01 01 12 00 0046006F006C0064006500720031FFFF 23> <GA:183131684B31020376 0F01 01 12 10 FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF 98> */ public class FolderData { private GeNetPkgText folderName; private int folderID; public int parentID; public int folderLevel; public boolean isSelect; public int trackCount; public int trackCalcFrom; public Vector<Integer> subFoldersId; public FolderData( int folderID ) { folderName = new GeNetPkgText(); this.folderID = folderID; subFoldersId = new Vector<Integer>(); } /** * * @param allPk */ public void setFolderAllPkg(int allPk) { folderName.setAllPack( allPk ); } public void updateData(int currPk, String folderName ) { this.folderName.updateInfo( folderName, currPk ); } public boolean isComplete() { return folderName.isReady(); } public String getName() { return folderName.getText(); } public int getFolderID() { return folderID; } }
true
7105099a02abcf86430be36d79e16595b086cc44
Java
igordeuzami/ArqSoft
/pipoca/src/br/usjt/arqsw18/pipoca/model/service/FilmeService.java
UTF-8
2,315
2.25
2
[]
no_license
package br.usjt.arqsw18.pipoca.model.service; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import br.usjt.arqsw18.pipoca.model.dao.FilmeDAO; import br.usjt.arqsw18.pipoca.model.entity.Filme; import br.usjt.arqsw18.pipoca.model.entity.Genero; @Service public class FilmeService { private FilmeDAO dao; private GeneroService gs; public static final String API_KEY = "b6b4c4e94d7e361a14398567b0e5b533"; public static final String URL = "https://api.themoviedb.org/3/movie/popular?api_key="+ API_KEY +"&language=en-US"; public static final String IMG = "https://image.tmdb.org/t/p/w500/"; @Autowired public FilmeService(FilmeDAO fdao) { dao = fdao; this.gs = gs; } public Filme buscarFilme(int id) throws IOException{ return dao.buscarFilme(id); } @Transactional public Filme inserirFilme(Filme filme) throws IOException { int id = dao.inserirFilme(filme); filme.setId(id); return filme; } @Transactional public void excluirFilme(Filme filme) throws IOException { dao.removerFilme(filme); } @Transactional public void atualizarFilme(Filme filme) throws IOException { dao.atualizarFilme(filme); } public List<Filme> listarFilmes(String chave) throws IOException{ return dao.listarFilmes(chave); } public List<Filme> listarFilmes() throws IOException{ return dao.listarFilmes(); } public List<FilmeTMDb> carregarFilmes() { RestTemplate rt = new RestTemplate(); ResultadoTMDb resultado = rt.getForObject(URL, ResultadoTMDb.class); //System.out.println(resultado); List<FilmeTMDb> lista = resultado.getResults(); for(FilmeTMDb filmeTMDb:lista) { Filme filme = new Filme(); filme.setTitulo(filmeTMDb.getTitle()); filme.setDescricao(filmeTMDb.getOverview()); filme.setPopularidade(filmeTMDb.getPopularity()); filme.setPosterPath(IMG + filmeTMDb.getPoster_path()); System.out.println(lista); /* try { Genero genero = gs.buscarGenero(filmeTMDb.getGenre_ids()[0]); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } return lista; } }
true
0ffea7f3917a09ec68d1513fd0f36b1c195aaf8c
Java
yongqiang001/gmallparent
/service/service-cart/src/main/java/com/atguigu/gmall/cart/service/impl/CartServiceImpl.java
UTF-8
15,451
2.390625
2
[]
no_license
package com.atguigu.gmall.cart.service.impl; import com.atguigu.gmall.cart.mapper.CartInfoMapper; import com.atguigu.gmall.cart.service.CartAsyncService; import com.atguigu.gmall.cart.service.CartService; import com.atguigu.gmall.common.constant.RedisConst; import com.atguigu.gmall.model.cart.CartInfo; import com.atguigu.gmall.model.product.SkuInfo; import com.atguigu.gmall.product.client.ProductFeignClient; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.BoundHashOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors; /** * @author mqx * @date 2020-8-7 15:51:41 */ @Service public class CartServiceImpl implements CartService { // 引入mapper @Autowired private CartInfoMapper cartInfoMapper; // 引入异步操作数据库的接口 @Autowired private CartAsyncService cartAsyncService; @Autowired private ProductFeignClient productFeignClient; // 引入缓存 @Autowired private RedisTemplate redisTemplate; @Override public void addToCart(Long skuId, String userId, Integer skuNum) { /* 1. 如果购物车中没有当前要添加的商品,则数据直接插入! 2. 如果购物车中有当前要添加的商品,则数量直接相加 3. 做一步:mysql 与 redis 做同步! 弊端: mysql 与 redis 相当于同步操作的! */ // 获取购物车的key String cartKey = getCartKey(userId); // 缓存根本没有数据 if (!redisTemplate.hasKey(cartKey)){ loadCartCache(userId); } // 查询购物车中是否有该商品! 查询数据库 // 在购物车表中,一个用户,购买同一件商品,那么在数据库表中只有唯一的一条记录! QueryWrapper<CartInfo> cartInfoQueryWrapper = new QueryWrapper<>(); cartInfoQueryWrapper.eq("sku_id",skuId); cartInfoQueryWrapper.eq("user_id",userId); CartInfo cartInfoExist = cartInfoMapper.selectOne(cartInfoQueryWrapper); // 说明购物车中有添加的商品 if (cartInfoExist!=null){ // 有的话,商品的数量相加 cartInfoExist.setSkuNum(cartInfoExist.getSkuNum()+skuNum); // 初始化一个实时价格 cartInfoExist.setSkuPrice(productFeignClient.getSkuPrice(skuId)); // 更新数据库,缓存。暂时,先这样写,后面会有优化! // cartInfoMapper.updateById(cartInfoExist); cartAsyncService.updateCartInfo(cartInfoExist); // 更新缓存 // redisTemplate.boundHashOps(cartKey).put(skuId.toString(),cartInfoExist); }else { // 说明购物车中没有添加的商品 CartInfo cartInfo = new CartInfo(); // 给cartInfo 赋值数据 购物车---商品详情---商品后台{service-product} SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId); // 实时价格 =相当于skuInfo.price(); 第一次添加购物车的时候,这个价格就是实时价格。 cartInfo.setSkuPrice(skuInfo.getPrice()); cartInfo.setSkuNum(skuNum); // 默认值1 表示被选中 // cartInfo.setIsChecked(); cartInfo.setUserId(userId); cartInfo.setImgUrl(skuInfo.getSkuDefaultImg()); cartInfo.setSkuName(skuInfo.getSkuName()); cartInfo.setSkuId(skuId); // 添加购物车时的价格,默认是最新的价格 cartInfo.setCartPrice(skuInfo.getPrice()); // 插入到数据库 // cartInfoMapper.insert(cartInfo); cartAsyncService.saveCartInfo(cartInfo); cartInfoExist = cartInfo; // 更新缓存 // redisTemplate.boundHashOps(cartKey).put(skuId.toString(),cartInfo); } // 要设置缓存同步 // 使用hash 数据类型存储。 /* hset(key,field,value); key=user:userId:cart field=skuId value=cartInfo.toString(); */ // redisTemplate.opsForHash().put(); // 废物利用! redisTemplate.boundHashOps(cartKey).put(skuId.toString(),cartInfoExist); // 设置购物车过期时间 setCartKeyExpire(cartKey); } @Override public List<CartInfo> getCartList(String userId, String userTempId) { // 声明一个集合对象List<CartInfo> List<CartInfo> cartInfoList = new ArrayList<>(); // 判断用户是否登录 if (StringUtils.isEmpty(userId)){ // 登录的userId 为空,那么应该获取临时userTempId的购物车 cartInfoList = getCartList(userTempId); } // 登录 if (!StringUtils.isEmpty(userId)){ // 只有在用户登录的情况下 才能合并购物车! List<CartInfo> cartInfoNoLoginList = getCartList(userTempId); if (!CollectionUtils.isEmpty(cartInfoNoLoginList)){ // 未登录购物车中有数据,则合并。 cartInfoList = mergeToCartList(cartInfoNoLoginList,userId); // 合并完成之后,删除未登录购物车 deleteCartList(userTempId); } // 细节问题:如果未登录数据是空 或者 userTempId 是空,都回直接查询数据库 if (CollectionUtils.isEmpty(cartInfoNoLoginList) || StringUtils.isEmpty(userTempId)){ // 登录的userId 不为空, 查询userId 购物车 cartInfoList = getCartList(userId); } } return cartInfoList; } @Override public void checkCart(String userId, Integer isChecked, Long skuId) { // 这个位置,你要操作mysql,redis // 异步操作数据库: cartAsyncService.checkCart(userId, isChecked, skuId); // 更新redis // 获取到key String cartKey = getCartKey(userId); /* hset(key,field,value); 获取可以所有的数据 BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(cartKey); 通过key ,field 获取value hget(key,field); CartInfo cartInfoUpd = (CartInfo) boundHashOperations.get(skuId.toString()); 放入数据 field,value boundHashOperations.put(skuId.toString(),cartInfoUpd); */ BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(cartKey); // 判断这个hash 中是否有对应的key if (boundHashOperations.hasKey(skuId.toString())){ // 准备更新数据 CartInfo cartInfoUpd = (CartInfo) boundHashOperations.get(skuId.toString()); cartInfoUpd.setIsChecked(isChecked); // 将更新对象写入缓存 boundHashOperations.put(skuId.toString(),cartInfoUpd); // 设置一下获取时间 setCartKeyExpire(cartKey); } } @Override public void deleteCartInfo(String userId, Long skuId) { // 操作mysql,redis cartAsyncService.deleteCartInfo(userId, skuId); // 先获取购物车key String cartKey = getCartKey(userId); BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(cartKey); if (boundHashOperations.hasKey(skuId.toString())){ // 删除数据 boundHashOperations.delete(skuId.toString()); } } @Override public List<CartInfo> getCartCheckedList(String userId) { // 声明一个集合来存储被选中的商品 List<CartInfo> cartInfosList = new ArrayList<>(); // 从购物车列表页面点击去结算,这个时候,缓存一定会有数据! // 所以直接获取缓存数据即可! // 获取购物车key String cartKey = getCartKey(userId); // 获取购物车数据集合 List<CartInfo> cartInfoList = redisTemplate.opsForHash().values(cartKey); if (!CollectionUtils.isEmpty(cartInfoList)){ // 循环遍历 获取被选中的数据 for (CartInfo cartInfo : cartInfoList) { if (cartInfo.getIsChecked().intValue()==1){ cartInfosList.add(cartInfo); } } } // 返回集合 return cartInfosList; } // 删除未登录购物车数据 private void deleteCartList(String userTempId) { // 删除数据库,还需要删除缓存 // 将其改成异步 // cartInfoMapper.delete(new QueryWrapper<CartInfo>().eq("user_id",userTempId)); // 调用异步方法 cartAsyncService.deleteCartInfo(userTempId); // 获取缓存的key String cartKey = getCartKey(userTempId); // 判断缓存有这个keyme Boolean flag = redisTemplate.hasKey(cartKey); if (flag){ redisTemplate.delete(cartKey); } } // 合并购物车数据 private List<CartInfo> mergeToCartList(List<CartInfo> cartInfoNoLoginList, String userId) { /* 实现思路: demo1: 登录: 37 1 38 1 未登录: 37 1 38 1 39 1 合并之后的数据 37 2 38 2 39 1 demo2: 未登录: 37 1 38 1 39 1 40 1 合并之后的数据 37 1 38 1 39 1 40 1 */ // 合并必须有两个集合: 登录购物车集合,未登录购物车集合 List<CartInfo> cartInfoLoginList = getCartList(userId); // cartInfoNoLoginList 未登录购物车 // 将登录购物车变为map结构 key=skuId value=CartInfo // Collectors.toMap(CartInfo::getSkuId, cartInfo -> cartInfo) // map.put(key,value); // map.put(cartinfo.getskuId,cartinfo) // Function 当参数只有一个参数的时候,() {} 都可以省略。 Map<Long, CartInfo> cartInfoLoginMap = cartInfoLoginList.stream().collect(Collectors.toMap(CartInfo::getSkuId, cartInfo -> cartInfo)); // 处理map // 循环遍历未登录购物车集合数据 for (CartInfo cartInfoNoLogin : cartInfoNoLoginList) { // 获取未登录购物车数据对象中的skuId. Long skuId = cartInfoNoLogin.getSkuId(); // 判断 登录和未登录有相同商品 if(cartInfoLoginMap.containsKey(skuId)){ // 商品的数量进行相加操作 37,38 CartInfo cartInfoLogin = cartInfoLoginMap.get(skuId); cartInfoLogin.setSkuNum(cartInfoLogin.getSkuNum()+cartInfoNoLogin.getSkuNum()); // 细节: 合并选中细节 // 未登录购物车选中状态,那么则数据库为选中状态 if (cartInfoNoLogin.getIsChecked().intValue()==1){ cartInfoLogin.setIsChecked(1); } // 更新数据库操作 cartAsyncService.updateCartInfo(cartInfoLogin); }else { // 没有包含的说明没有对应的商品,cartInfoNoLogin 放入数据 39 // 将未登录用户Id 设置成已登录的用户Id cartInfoNoLogin.setUserId(userId); cartAsyncService.saveCartInfo(cartInfoNoLogin); } } // 获取合并之后的所有数据 37,38,39 统一做个汇总,去查询一下最新购物车数据。 List<CartInfo> cartInfoList = loadCartCache(userId); // 返回数据 return cartInfoList; } // 根据userId 获取购物车列表数据 private List<CartInfo> getCartList(String userId) { // 声明一个集合 List<CartInfo> cartInfoList = new ArrayList<>(); // 判断用户Id是否为空 if (StringUtils.isEmpty(userId)){ return cartInfoList; } // 先从缓存中获取 // 获取购物车key String cartKey = getCartKey(userId); // 获取购物车中所有数据? 获取hash中所有的value 数据 cartInfoList = redisTemplate.opsForHash().values(cartKey); // 判断 if(!CollectionUtils.isEmpty(cartInfoList)){ // 循环遍历获取里面的数据,原因?查询购物车列表时,应该有排序功能! 按照商品的更新时间进行排序 // 由于我们这个table 没有更新时间字段 | 在此按照id 进行排序。 cartInfoList.sort(new Comparator<CartInfo>() { @Override public int compare(CartInfo o1, CartInfo o2) { return o1.getId().compareTo(o2.getId()); } }); // 返回排序好的集合数据 return cartInfoList; }else { // 如果缓存数据为空,那么应该如何处理? 获取数据库中的数据,并添加到缓存 cartInfoList = loadCartCache(userId); return cartInfoList; } } // 根据userId 查询数据库,并将结果放入缓存! public List<CartInfo> loadCartCache(String userId) { // 从数据库中获取数据 // select * from cart_info where user_id=userId List<CartInfo> cartInfoList = cartInfoMapper.selectList(new QueryWrapper<CartInfo>().eq("user_id", userId)); // 判断这个集合 if(CollectionUtils.isEmpty(cartInfoList)){ return cartInfoList; } // 将数据放入缓存! String cartKey = getCartKey(userId); // hset(key,field,value) hmset(key,map) HashMap<String, CartInfo> hashMap = new HashMap<>(); for (CartInfo cartInfo : cartInfoList) { // redisTemplate.opsForHash().put(cartKey,cartInfo.getSkuId().toString(),cartInfo); // 细节问题: 数据库表cart_info 中没有skuPrice这个字段,那么我们为了将这个字段写入缓存时,不能为空 // 同时,需要将最新的商品价格赋值给skuPrice. cartInfo.setSkuPrice(productFeignClient.getSkuPrice(cartInfo.getSkuId())); hashMap.put(cartInfo.getSkuId().toString(),cartInfo); } redisTemplate.opsForHash().putAll(cartKey,hashMap); // 设置过期时间 setCartKeyExpire(cartKey); return cartInfoList; } // 设置购物车的过期时间 private void setCartKeyExpire(String cartKey) { redisTemplate.expire(cartKey, RedisConst.USER_CART_EXPIRE, TimeUnit.SECONDS); } // 获取购物车的缓存key private String getCartKey(String userId){ // key = user:userId:cart 谁的购物车 return RedisConst.USER_KEY_PREFIX+userId+RedisConst.USER_CART_KEY_SUFFIX; } }
true
56cbd9316d927728c31ea769aab9968ef57db6dc
Java
yangzpag/CodeReader
/cocoon/src/scratchpad/src/org/apache/cocoon/acting/ModularDatabaseSelectAction.java
UTF-8
9,666
1.9375
2
[]
no_license
/***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * ------------------------------------------------------------------------- * * This software is published under the terms of the Apache Software License * * version 1.1, a copy of which has been included with this distribution in * * the LICENSE file. * *****************************************************************************/ package org.apache.cocoon.acting; import java.util.Map; import java.sql.Connection; import java.sql.Clob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Struct; import java.sql.Types; import java.io.InputStream; import java.io.BufferedInputStream; import org.apache.cocoon.util.HashMap; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.cocoon.environment.Request; /** * Selects a record from a database. The action can select one or more * tables, and can select from more than one row of a table at a * time. The form descriptor semantics for this are still in a bit of * a state of flux. * * @author <a href="mailto:haul@apache.org">Christian Haul</a> * @version CVS $Revision: 1.1 $ $Date: 2002/01/03 12:31:35 $ */ public class ModularDatabaseSelectAction extends ModularDatabaseAction { /** * determine which mode to use as default mode * here: SELECT * highly specific to operation INSERT / UPDATE / DELETE / SELECT */ protected String selectMode ( boolean isAutoIncrement, HashMap modes ) { return (String) modes.get( MODE_OTHERS ); } /** * determine whether autoincrement columns should be honoured by * this operation. This is usually snsible only for INSERTs. */ protected boolean honourAutoIncrement() { return false; } /** * Get the String representation of the PreparedStatement. This is * mapped to the Configuration object itself, so if it doesn't exist, * it will be created. * * @param table the table's configuration object * @return the insert query as a string */ protected CacheHelper getQuery( Configuration table, HashMap modeTypes, HashMap defaultModeNames ) throws ConfigurationException, ComponentException { LookUpKey lookUpKey = new LookUpKey( table, modeTypes ); CacheHelper queryData = null; synchronized( this.cachedQueryData ) { queryData = (CacheHelper) this.cachedQueryData.get( lookUpKey ); if (queryData == null) { Configuration[] keys = table.getChild("keys").getChildren("key"); Configuration[] values = table.getChild("values").getChildren("value"); queryData = new CacheHelper( keys.length, keys.length ); fillModes( keys, true, defaultModeNames, modeTypes, queryData ); fillModes( values, false, defaultModeNames, modeTypes, queryData ); StringBuffer queryBuffer = new StringBuffer("SELECT "); queryBuffer.append(table.getAttribute("name")).append(" WHERE "); for (int i = 0; i < queryData.columns.length; i++) { if ( !queryData.columns[i].isKey ) { if ( i > 0 ) { queryBuffer.append(", "); } queryBuffer .append( queryData.columns[i].columnConf.getAttribute( "name" ) ); } } queryBuffer.append(" FROM ").append(table.getAttribute("name")).append(" WHERE "); for (int i = 0; i < queryData.columns.length; i++) { if ( queryData.columns[i].isKey ) { if ( i > 0 ) { queryBuffer.append(" AND "); } queryBuffer .append( queryData.columns[i].columnConf.getAttribute( "name" ) ) .append( "= ?"); } } queryData.queryString = queryBuffer.toString(); this.cachedQueryData.put( lookUpKey, queryData ); } } return queryData; } /** * Fetch all values for all key columns that are needed to do the * database operation. */ protected Object[][] getColumnValues( Configuration tableConf, CacheHelper queryData, Request request ) throws ConfigurationException, ComponentException { Object[][] columnValues = new Object[ queryData.columns.length ][]; for ( int i = 0; i < queryData.columns.length; i++ ){ if ( queryData.columns[i].isKey ) { columnValues[i] = this.getColumnValue( tableConf, queryData.columns[i], request ); } else { // columnValues[i] = new Object[1]; // this should not be needed } } return columnValues; } /** * set all necessary ?s and execute the query */ protected void processRow ( Request request, Connection conn, PreparedStatement statement, Configuration table, CacheHelper queryData, Object[][] columnValues, int rowIndex, Map results ) throws SQLException, ConfigurationException, Exception { int currentIndex = 1; // ordering is different for SELECT just needs keys for (int i = 0; i < queryData.columns.length; i++) { Column col = queryData.columns[i]; if ( col.isKey ) { this.setColumn( statement, currentIndex, request, col.columnConf, getOutputName( table, col.columnConf, rowIndex ), columnValues[ i ][ ( col.isSet ? rowIndex : 0 ) ], rowIndex); currentIndex++; } } statement.execute(); // retrieve values ResultSet resultset = statement.getResultSet(); rowIndex = -1; while ( resultset.next() ){ if ( ! ( rowIndex == -1 && resultset.isLast() ) ) { rowIndex++; } for (int i = 0; i < queryData.columns.length; i++) { if ( !queryData.columns[i].isKey ) { Object value = this.getColumn( resultset, queryData.columns[i].columnConf ); String param = getOutputName( table, queryData.columns[i].columnConf, rowIndex ); this.setRequestAttribute( request, param, value ); } } } } /** * Get the Statement column so that the results are mapped correctly. * (this has been copied from AbstractDatabaseAction and modified slightly) */ protected Object getColumn(ResultSet set, Configuration column ) throws Exception { Integer type = (Integer) AbstractDatabaseAction.typeConstants.get(column.getAttribute("type")); String dbcol = column.getAttribute("name"); Object value = null; switch (type.intValue()) { case Types.CLOB: Clob dbClob = set.getClob(dbcol); int length = (int) dbClob.length(); InputStream asciiStream = new BufferedInputStream(dbClob.getAsciiStream()); byte[] buffer = new byte[length]; asciiStream.read(buffer); String str = new String(buffer); asciiStream.close(); value = str; break; case Types.BIGINT: value = set.getBigDecimal(dbcol); break; case Types.TINYINT: value = new Byte(set.getByte(dbcol)); break; case Types.VARCHAR: value = set.getString(dbcol); break; case Types.DATE: value = set.getDate(dbcol); break; case Types.DOUBLE: value = new Double(set.getDouble(dbcol)); break; case Types.FLOAT: value = new Float(set.getFloat(dbcol)); break; case Types.INTEGER: value = new Integer(set.getInt(dbcol)); break; case Types.NUMERIC: value = new Long(set.getLong(dbcol)); break; case Types.SMALLINT: value = new Short(set.getShort(dbcol)); break; case Types.TIME: value = set.getTime(dbcol); break; case Types.TIMESTAMP: value = set.getTimestamp(dbcol); break; case Types.ARRAY: value = set.getArray(dbcol); // new Integer(set.getInt(dbcol)); break; case Types.BIT: value = new Integer(set.getInt(dbcol)); break; case Types.CHAR: value = new Integer(set.getInt(dbcol)); break; case Types.STRUCT: value = (Struct) set.getObject(dbcol); break; case Types.OTHER: value = set.getObject(dbcol); break; default: // The blob types have to be requested separately, via a Reader. value = ""; break; } return value; } }
true
66076ebc5bb011bdd3b26ee1d541b180049e1e21
Java
keithwars/FactoryPattern1
/src/edu/ap/factorypattern1/CarFactory.java
UTF-8
275
2.5625
3
[]
no_license
package edu.ap.factorypattern1; import edu.ap.factorypattern1.Engine.GAS; public abstract class CarFactory { public Engine makeEngine() { return new Engine(1600, 6, GAS.DIESEL); } public abstract Body createBody(); public abstract Interior createInterior(); }
true
0a72f2bd0770c8920f8711d6668034cb6e6fd619
Java
mcanthony/voc
/python/common/org/python/exceptions/MemoryError.java
UTF-8
215
2.03125
2
[ "BSD-3-Clause" ]
permissive
package org.python.exceptions; public class MemoryError extends org.python.exceptions.Exception { public MemoryError() { super(); } public MemoryError(String msg) { super(msg); } }
true
15c6cb393878fcb5f4a9cfcbab71d0f9c212f67c
Java
pvdung/microservlet
/microservlet/src/test/java/AllTests.java
UTF-8
1,079
1.585938
2
[]
no_license
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import com.sokolov.microservlet.MicroServletTest; import com.sokolov.microservlet.RequestFormImplTest; import com.sokolov.microservlet.RequestFormUtilTest; /** * Main test class AllTests. * @author Helio Frota * */ @RunWith(value = Suite.class) @SuiteClasses(value = { RequestFormUtilTest.class, RequestFormImplTest.class, MicroServletTest.class }) public class AllTests { }
true
9f279162a3e06eb0ca56b0c6e243491a3f0c8ae2
Java
freakcsh/HttpManage
/app/src/main/java/com/freak/httpmanage/util/picture/PictureSelectorUtil.java
UTF-8
52,730
1.867188
2
[]
no_license
package com.freak.httpmanage.util.picture; import android.app.Activity; import android.content.Context; import android.content.pm.ActivityInfo; import android.graphics.Color; import androidx.core.content.ContextCompat; import com.freak.httpmanage.R; import com.luck.picture.lib.PictureSelector; import com.luck.picture.lib.config.PictureConfig; import com.luck.picture.lib.config.PictureMimeType; import com.luck.picture.lib.entity.LocalMedia; import com.luck.picture.lib.listener.OnResultCallbackListener; import com.luck.picture.lib.style.PictureCropParameterStyle; import com.luck.picture.lib.style.PictureParameterStyle; import com.luck.picture.lib.style.PictureWindowAnimationStyle; import java.util.List; /** * Created by Freak on 2020/2/6. */ public class PictureSelectorUtil { private PictureParameterStyle mPictureParameterStyle; private PictureCropParameterStyle mCropParameterStyle; private PictureWindowAnimationStyle mWindowAnimationStyle; private static PictureSelectorUtil pictureSelectorUtil; public static PictureSelectorUtil getInstance() { if (pictureSelectorUtil == null) { synchronized (PictureSelectorUtil.class) { if (pictureSelectorUtil == null) { pictureSelectorUtil = new PictureSelectorUtil(); } } } return pictureSelectorUtil; } public void create(Activity activity, OnResultCallbackListener listener, List<LocalMedia> selectList) { PictureSelector.create(activity) .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio() // .theme(R.style.picture_default_style)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如:R.style.picture.white.style .setPictureStyle(mPictureParameterStyle)// 动态自定义相册主题 注意:此方法最好不要与.theme();同时存在, 二选一 .setPictureCropStyle(mCropParameterStyle)// 动态自定义裁剪主题 .setPictureWindowAnimationStyle(mWindowAnimationStyle)// 自定义相册启动退出动画 .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎,必传项 参考Demo MainActivity中代码 .isWithVideoImage(true)// 图片和视频是否可以同选,只在ofAll模式下有效 .isUseCustomCamera(false)// 是否使用自定义相机,5.0以下请不要使用,可能会出现兼容性问题 .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)// 设置相册Activity方向,不设置默认使用系统 .isOriginalImageControl(false)// 是否显示原图控制按钮,如果用户勾选了 压缩、裁剪功能将会失效 .isWeChatStyle(true)// 是否开启微信图片选择风格,此开关开启了才可使用微信主题!!! .isAndroidQTransform(false)// 是否需要处理Android Q 拷贝至应用沙盒的操作,只针对compress(false); && .enableCrop(true)//有效 // .bindCustomPlayVideoCallback(callback)// 自定义播放回调控制,用户可以使用自己的视频播放界面 .isMultipleSkipCrop(false)// 多图裁剪时是否支持跳过,默认支持 .isMultipleRecyclerAnimation(false)// 多图裁剪底部列表显示动画效果 // .setLanguage(language)// 设置语言,默认中文 .maxSelectNum(3)// 最大图片选择数量 int .minSelectNum(1)// 最小选择数量 int // .minVideoSelectNum(1)// 视频最小选择数量,如果没有单独设置的需求则可以不设置,同用minSelectNum字段 // .maxVideoSelectNum(1) // 视频最大选择数量,如果没有单独设置的需求则可以不设置,同用maxSelectNum字段 .imageSpanCount(3)// 每行显示个数 int .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回 .isNotPreviewDownload(true)// 预览图片长按是否可以下载 .queryMaxFileSize(10)// 只查多少M以内的图片、视频、音频 单位M // .querySpecifiedFormatSuffix(PictureMimeType.ofPNG())// 查询指定后缀格式资源 .cameraFileName(System.currentTimeMillis() + "camera.png") // 重命名拍照文件名、注意这个只在使用相机时可以使用 .renameCompressFile(System.currentTimeMillis() + "compress.png")// 重命名压缩文件名、 注意这个不要重复,只适用于单张图压缩使用 .renameCropFileName(System.currentTimeMillis() + "crop.png")// 重命名裁剪文件名、 注意这个不要重复,只适用于单张图裁剪使用 .isSingleDirectReturn(false)// 单选模式下是否直接返回,PictureConfig.SINGLE模式下有效 // .setTitleBarBackgroundColor()//相册标题栏背景色 // .isChangeStatusBarFontColor()// 是否关闭白色状态栏字体颜色 // .setStatusBarColorPrimaryDark()// 状态栏背景色 // .setUpArrowDrawable()// 设置标题栏右侧箭头图标 // .setDownArrowDrawable()// 设置标题栏右侧箭头图标 // .isOpenStyleCheckNumMode()// 是否开启数字选择模式 类似QQ相册 .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE .previewImage(true)// 是否可预览图片 true or false .previewVideo(true)// 是否可预览视频 true or false .enablePreviewAudio(true) // 是否可播放音频 true or false .isCamera(true)// 是否显示拍照按钮 true or false .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg .isZoomAnim(true)// 图片列表点击 缩放效果 默认true .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效 .enableCrop(true)// 是否裁剪 true or false // .setCircleDimmedColor()// 设置圆形裁剪背景色值 // .setCircleDimmedBorderColor()// 设置圆形裁剪边框色值 .setCircleStrokeWidth(3)// 设置圆形裁剪边框粗细 .compress(true)// 是否压缩 true or false // .glideOverride()// int glide 加载宽高,越小图片列表越流畅,但会影响列表图片浏览的清晰度 // .withAspectRatio()// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义 .hideBottomControls(false)// 是否显示uCrop工具栏,默认不显示 true or false .isGif(true)// 是否显示gif图片 true or false // .compressSavePath(getPath())//压缩图片保存地址 .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false .circleDimmedLayer(false)// 是否圆形裁剪 true or false .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false true or false .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false true or false .openClickSound(false)// 是否开启点击声音 true or false .selectionMedia(selectList)// 是否传入已选图片 List<LocalMedia> list .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false .cutOutQuality(80)// 裁剪输出质量 默认100 .minimumCompressSize(100)// 小于100kb的图片不压缩 .synOrAsy(true)//同步true或异步false 压缩 默认同步 // .cropImageWideHigh()// 裁剪宽高比,设置如果大于图片本身宽高则无效 .rotateEnabled(true) // 裁剪是否可旋转图片 true or false .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false // .videoQuality(1)// 视频录制质量 0 or 1 int // .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int // .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int // .recordVideoSecond(60)//视频秒数录制 默认60s int .isDragFrame(true)// 是否可拖动裁剪框(固定) // .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code .forResult(listener);//Callback回调方式 } public void create2(Activity activity, OnResultCallbackListener listener, List<LocalMedia> selectList) { PictureSelector.create(activity) .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio() // .theme(R.style.picture_default_style)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如:R.style.picture.white.style .setPictureStyle(mPictureParameterStyle)// 动态自定义相册主题 注意:此方法最好不要与.theme();同时存在, 二选一 .setPictureCropStyle(mCropParameterStyle)// 动态自定义裁剪主题 .setPictureWindowAnimationStyle(mWindowAnimationStyle)// 自定义相册启动退出动画 .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎,必传项 参考Demo MainActivity中代码 .isWithVideoImage(true)// 图片和视频是否可以同选,只在ofAll模式下有效 .isUseCustomCamera(false)// 是否使用自定义相机,5.0以下请不要使用,可能会出现兼容性问题 .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)// 设置相册Activity方向,不设置默认使用系统 .isOriginalImageControl(false)// 是否显示原图控制按钮,如果用户勾选了 压缩、裁剪功能将会失效 .isWeChatStyle(true)// 是否开启微信图片选择风格,此开关开启了才可使用微信主题!!! .isAndroidQTransform(false)// 是否需要处理Android Q 拷贝至应用沙盒的操作,只针对compress(false); && .enableCrop(true)//有效 // .bindCustomPlayVideoCallback(callback)// 自定义播放回调控制,用户可以使用自己的视频播放界面 .isMultipleSkipCrop(false)// 多图裁剪时是否支持跳过,默认支持 .isMultipleRecyclerAnimation(false)// 多图裁剪底部列表显示动画效果 // .setLanguage(language)// 设置语言,默认中文 .maxSelectNum(3)// 最大图片选择数量 int .minSelectNum(1)// 最小选择数量 int // .minVideoSelectNum(1)// 视频最小选择数量,如果没有单独设置的需求则可以不设置,同用minSelectNum字段 // .maxVideoSelectNum(1) // 视频最大选择数量,如果没有单独设置的需求则可以不设置,同用maxSelectNum字段 .imageSpanCount(3)// 每行显示个数 int .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回 .isNotPreviewDownload(true)// 预览图片长按是否可以下载 .queryMaxFileSize(10)// 只查多少M以内的图片、视频、音频 单位M // .querySpecifiedFormatSuffix(PictureMimeType.ofPNG())// 查询指定后缀格式资源 .cameraFileName(System.currentTimeMillis() + "camera.png") // 重命名拍照文件名、注意这个只在使用相机时可以使用 .renameCompressFile(System.currentTimeMillis() + "compress.png")// 重命名压缩文件名、 注意这个不要重复,只适用于单张图压缩使用 .renameCropFileName(System.currentTimeMillis() + "crop.png")// 重命名裁剪文件名、 注意这个不要重复,只适用于单张图裁剪使用 .isSingleDirectReturn(false)// 单选模式下是否直接返回,PictureConfig.SINGLE模式下有效 // .setTitleBarBackgroundColor()//相册标题栏背景色 // .isChangeStatusBarFontColor()// 是否关闭白色状态栏字体颜色 // .setStatusBarColorPrimaryDark()// 状态栏背景色 // .setUpArrowDrawable()// 设置标题栏右侧箭头图标 // .setDownArrowDrawable()// 设置标题栏右侧箭头图标 // .isOpenStyleCheckNumMode()// 是否开启数字选择模式 类似QQ相册 .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE .previewImage(true)// 是否可预览图片 true or false .previewVideo(true)// 是否可预览视频 true or false .enablePreviewAudio(true) // 是否可播放音频 true or false .isCamera(true)// 是否显示拍照按钮 true or false .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg .isZoomAnim(true)// 图片列表点击 缩放效果 默认true .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效 .enableCrop(true)// 是否裁剪 true or false // .setCircleDimmedColor()// 设置圆形裁剪背景色值 // .setCircleDimmedBorderColor()// 设置圆形裁剪边框色值 .setCircleStrokeWidth(3)// 设置圆形裁剪边框粗细 .compress(true)// 是否压缩 true or false // .glideOverride()// int glide 加载宽高,越小图片列表越流畅,但会影响列表图片浏览的清晰度 .withAspectRatio(1,1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义 .hideBottomControls(false)// 是否显示uCrop工具栏,默认不显示 true or false .isGif(true)// 是否显示gif图片 true or false // .compressSavePath(getPath())//压缩图片保存地址 .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false .circleDimmedLayer(false)// 是否圆形裁剪 true or false .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false true or false .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false true or false .openClickSound(false)// 是否开启点击声音 true or false .selectionMedia(selectList)// 是否传入已选图片 List<LocalMedia> list .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false .cutOutQuality(80)// 裁剪输出质量 默认100 .minimumCompressSize(100)// 小于100kb的图片不压缩 .synOrAsy(true)//同步true或异步false 压缩 默认同步 // .cropImageWideHigh()// 裁剪宽高比,设置如果大于图片本身宽高则无效 .rotateEnabled(true) // 裁剪是否可旋转图片 true or false .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false // .videoQuality(1)// 视频录制质量 0 or 1 int // .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int // .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int // .recordVideoSecond(60)//视频秒数录制 默认60s int .isDragFrame(true)// 是否可拖动裁剪框(固定) // .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code .forResult(listener);//Callback回调方式 } public void createVideo(Activity activity, OnResultCallbackListener listener, List<LocalMedia> selectList) { PictureSelector.create(activity) .openGallery(PictureMimeType.ofVideo())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio() // .theme(R.style.picture_default_style)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如:R.style.picture.white.style .setPictureStyle(mPictureParameterStyle)// 动态自定义相册主题 注意:此方法最好不要与.theme();同时存在, 二选一 .setPictureCropStyle(mCropParameterStyle)// 动态自定义裁剪主题 .setPictureWindowAnimationStyle(mWindowAnimationStyle)// 自定义相册启动退出动画 .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎,必传项 参考Demo MainActivity中代码 .isWithVideoImage(true)// 图片和视频是否可以同选,只在ofAll模式下有效 .isUseCustomCamera(false)// 是否使用自定义相机,5.0以下请不要使用,可能会出现兼容性问题 .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)// 设置相册Activity方向,不设置默认使用系统 .isOriginalImageControl(false)// 是否显示原图控制按钮,如果用户勾选了 压缩、裁剪功能将会失效 .isWeChatStyle(true)// 是否开启微信图片选择风格,此开关开启了才可使用微信主题!!! .isAndroidQTransform(false)// 是否需要处理Android Q 拷贝至应用沙盒的操作,只针对compress(false); && .enableCrop(true)//有效 // .bindCustomPlayVideoCallback(callback)// 自定义播放回调控制,用户可以使用自己的视频播放界面 .isMultipleSkipCrop(false)// 多图裁剪时是否支持跳过,默认支持 .isMultipleRecyclerAnimation(false)// 多图裁剪底部列表显示动画效果 // .setLanguage(language)// 设置语言,默认中文 .maxSelectNum(3)// 最大图片选择数量 int .minSelectNum(1)// 最小选择数量 int // .minVideoSelectNum(1)// 视频最小选择数量,如果没有单独设置的需求则可以不设置,同用minSelectNum字段 .maxVideoSelectNum(1) // 视频最大选择数量,如果没有单独设置的需求则可以不设置,同用maxSelectNum字段 .imageSpanCount(3)// 每行显示个数 int .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回 .isNotPreviewDownload(true)// 预览图片长按是否可以下载 // .queryMaxFileSize(10)// 只查多少M以内的图片、视频、音频 单位M .querySpecifiedFormatSuffix(PictureMimeType.ofMP4())// 查询指定后缀格式资源 .cameraFileName(System.currentTimeMillis() + "camera.png") // 重命名拍照文件名、注意这个只在使用相机时可以使用 .renameCompressFile(System.currentTimeMillis() + "compress.png")// 重命名压缩文件名、 注意这个不要重复,只适用于单张图压缩使用 .renameCropFileName(System.currentTimeMillis() + "crop.png")// 重命名裁剪文件名、 注意这个不要重复,只适用于单张图裁剪使用 .isSingleDirectReturn(false)// 单选模式下是否直接返回,PictureConfig.SINGLE模式下有效 // .setTitleBarBackgroundColor()//相册标题栏背景色 // .isChangeStatusBarFontColor()// 是否关闭白色状态栏字体颜色 // .setStatusBarColorPrimaryDark()// 状态栏背景色 // .setUpArrowDrawable()// 设置标题栏右侧箭头图标 // .setDownArrowDrawable()// 设置标题栏右侧箭头图标 // .isOpenStyleCheckNumMode()// 是否开启数字选择模式 类似QQ相册 .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE .previewImage(true)// 是否可预览图片 true or false .previewVideo(true)// 是否可预览视频 true or false .enablePreviewAudio(true) // 是否可播放音频 true or false .isCamera(true)// 是否显示拍照按钮 true or false .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg .isZoomAnim(true)// 图片列表点击 缩放效果 默认true .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效 .enableCrop(true)// 是否裁剪 true or false // .setCircleDimmedColor()// 设置圆形裁剪背景色值 // .setCircleDimmedBorderColor()// 设置圆形裁剪边框色值 .setCircleStrokeWidth(3)// 设置圆形裁剪边框粗细 .compress(true)// 是否压缩 true or false // .glideOverride()// int glide 加载宽高,越小图片列表越流畅,但会影响列表图片浏览的清晰度 .withAspectRatio(1,1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义 .hideBottomControls(false)// 是否显示uCrop工具栏,默认不显示 true or false .isGif(true)// 是否显示gif图片 true or false // .compressSavePath(getPath())//压缩图片保存地址 .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false .circleDimmedLayer(false)// 是否圆形裁剪 true or false .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false true or false .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false true or false .openClickSound(false)// 是否开启点击声音 true or false .selectionMedia(selectList)// 是否传入已选图片 List<LocalMedia> list .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false .cutOutQuality(80)// 裁剪输出质量 默认100 .minimumCompressSize(100)// 小于100kb的图片不压缩 .synOrAsy(true)//同步true或异步false 压缩 默认同步 // .cropImageWideHigh()// 裁剪宽高比,设置如果大于图片本身宽高则无效 .rotateEnabled(true) // 裁剪是否可旋转图片 true or false .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false .videoQuality(1)// 视频录制质量 0 or 1 int .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int // .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int .recordVideoSecond(30)//视频秒数录制 默认60s int .isDragFrame(true)// 是否可拖动裁剪框(固定) // .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code .forResult(listener);//Callback回调方式 } public PictureSelectorUtil getDefaultStyle(Context context) { // 相册主题 mPictureParameterStyle = new PictureParameterStyle(); // 是否改变状态栏字体颜色(黑白切换) mPictureParameterStyle.isChangeStatusBarFontColor = false; // 是否开启右下角已完成(0/9)风格 mPictureParameterStyle.isOpenCompletedNumStyle = false; // 是否开启类似QQ相册带数字选择风格 mPictureParameterStyle.isOpenCheckNumStyle = false; // 相册状态栏背景色 mPictureParameterStyle.pictureStatusBarColor = Color.parseColor("#393a3e"); // 相册列表标题栏背景色 mPictureParameterStyle.pictureTitleBarBackgroundColor = Color.parseColor("#393a3e"); // 相册列表标题栏右侧上拉箭头 mPictureParameterStyle.pictureTitleUpResId = R.drawable.picture_icon_arrow_up; // 相册列表标题栏右侧下拉箭头 mPictureParameterStyle.pictureTitleDownResId = R.drawable.picture_icon_arrow_down; // 相册文件夹列表选中圆点 mPictureParameterStyle.pictureFolderCheckedDotStyle = R.drawable.picture_orange_oval; // 相册返回箭头 mPictureParameterStyle.pictureLeftBackIcon = R.drawable.picture_icon_back; // 标题栏字体颜色 mPictureParameterStyle.pictureTitleTextColor = ContextCompat.getColor(context, R.color.picture_color_white); // 相册右侧取消按钮字体颜色 废弃 改用.pictureRightDefaultTextColor和.pictureRightDefaultTextColor mPictureParameterStyle.pictureCancelTextColor = ContextCompat.getColor(context, R.color.picture_color_white); // 相册列表勾选图片样式 mPictureParameterStyle.pictureCheckedStyle = R.drawable.picture_checkbox_selector; // 相册列表底部背景色 mPictureParameterStyle.pictureBottomBgColor = ContextCompat.getColor(context, R.color.picture_color_grey); // 已选数量圆点背景样式 mPictureParameterStyle.pictureCheckNumBgStyle = R.drawable.picture_num_oval; // 相册列表底下预览文字色值(预览按钮可点击时的色值) mPictureParameterStyle.picturePreviewTextColor = ContextCompat.getColor(context, R.color.picture_color_fa632d); // 相册列表底下不可预览文字色值(预览按钮不可点击时的色值) mPictureParameterStyle.pictureUnPreviewTextColor = ContextCompat.getColor(context, R.color.picture_color_white); // 相册列表已完成色值(已完成 可点击色值) mPictureParameterStyle.pictureCompleteTextColor = ContextCompat.getColor(context, R.color.picture_color_fa632d); // 相册列表未完成色值(请选择 不可点击色值) mPictureParameterStyle.pictureUnCompleteTextColor = ContextCompat.getColor(context, R.color.picture_color_white); // 预览界面底部背景色 mPictureParameterStyle.picturePreviewBottomBgColor = ContextCompat.getColor(context, R.color.picture_color_grey); // 外部预览界面删除按钮样式 mPictureParameterStyle.pictureExternalPreviewDeleteStyle = R.drawable.picture_icon_delete; // 原图按钮勾选样式 需设置.isOriginalImageControl(true); 才有效 mPictureParameterStyle.pictureOriginalControlStyle = R.drawable.picture_original_wechat_checkbox; // 原图文字颜色 需设置.isOriginalImageControl(true); 才有效 mPictureParameterStyle.pictureOriginalFontColor = ContextCompat.getColor(context, R.color.color_white); // 外部预览界面是否显示删除按钮 mPictureParameterStyle.pictureExternalPreviewGonePreviewDelete = true; // 设置NavBar Color SDK Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP有效 mPictureParameterStyle.pictureNavBarColor = Color.parseColor("#393a3e"); // // 自定义相册右侧文本内容设置 // mPictureParameterStyle.pictureRightDefaultText = ""; // // 自定义相册未完成文本内容 // mPictureParameterStyle.pictureUnCompleteText = ""; // // 自定义相册完成文本内容 // mPictureParameterStyle.pictureCompleteText = ""; // // 自定义相册列表不可预览文字 // mPictureParameterStyle.pictureUnPreviewText = ""; // // 自定义相册列表预览文字 // mPictureParameterStyle.picturePreviewText = ""; // // // 自定义相册标题字体大小 // mPictureParameterStyle.pictureTitleTextSize = 18; // // 自定义相册右侧文字大小 // mPictureParameterStyle.pictureRightTextSize = 14; // // 自定义相册预览文字大小 // mPictureParameterStyle.picturePreviewTextSize = 14; // // 自定义相册完成文字大小 // mPictureParameterStyle.pictureCompleteTextSize = 14; // // 自定义原图文字大小 // mPictureParameterStyle.pictureOriginalTextSize = 14; // 裁剪主题 mCropParameterStyle = new PictureCropParameterStyle( ContextCompat.getColor(context, R.color.app_color_grey), ContextCompat.getColor(context, R.color.app_color_grey), Color.parseColor("#393a3e"), ContextCompat.getColor(context, R.color.color_white), mPictureParameterStyle.isChangeStatusBarFontColor); return this; } public PictureSelectorUtil getWhiteStyle(Context context) { // 相册主题 mPictureParameterStyle = new PictureParameterStyle(); // 是否改变状态栏字体颜色(黑白切换) mPictureParameterStyle.isChangeStatusBarFontColor = true; // 是否开启右下角已完成(0/9)风格 mPictureParameterStyle.isOpenCompletedNumStyle = false; // 是否开启类似QQ相册带数字选择风格 mPictureParameterStyle.isOpenCheckNumStyle = false; // 相册状态栏背景色 mPictureParameterStyle.pictureStatusBarColor = Color.parseColor("#FFFFFF"); // 相册列表标题栏背景色 mPictureParameterStyle.pictureTitleBarBackgroundColor = Color.parseColor("#FFFFFF"); // 相册列表标题栏右侧上拉箭头 mPictureParameterStyle.pictureTitleUpResId = R.drawable.ic_orange_arrow_up; // 相册列表标题栏右侧下拉箭头 mPictureParameterStyle.pictureTitleDownResId = R.drawable.ic_orange_arrow_down; // 相册文件夹列表选中圆点 mPictureParameterStyle.pictureFolderCheckedDotStyle = R.drawable.picture_orange_oval; // 相册返回箭头 mPictureParameterStyle.pictureLeftBackIcon = R.drawable.ic_back_arrow; // 标题栏字体颜色 mPictureParameterStyle.pictureTitleTextColor = ContextCompat.getColor(context, R.color.color_black); // 相册右侧取消按钮字体颜色 废弃 改用.pictureRightDefaultTextColor和.pictureRightDefaultTextColor mPictureParameterStyle.pictureCancelTextColor = ContextCompat.getColor(context, R.color.color_black); // 相册列表勾选图片样式 mPictureParameterStyle.pictureCheckedStyle = R.drawable.picture_checkbox_selector; // 相册列表底部背景色 mPictureParameterStyle.pictureBottomBgColor = ContextCompat.getColor(context, R.color.picture_color_fa); // 已选数量圆点背景样式 mPictureParameterStyle.pictureCheckNumBgStyle = R.drawable.picture_num_oval; // 相册列表底下预览文字色值(预览按钮可点击时的色值) mPictureParameterStyle.picturePreviewTextColor = ContextCompat.getColor(context, R.color.picture_color_fa632d); // 相册列表底下不可预览文字色值(预览按钮不可点击时的色值) mPictureParameterStyle.pictureUnPreviewTextColor = ContextCompat.getColor(context, R.color.picture_color_9b); // 相册列表已完成色值(已完成 可点击色值) mPictureParameterStyle.pictureCompleteTextColor = ContextCompat.getColor(context, R.color.picture_color_fa632d); // 相册列表未完成色值(请选择 不可点击色值) mPictureParameterStyle.pictureUnCompleteTextColor = ContextCompat.getColor(context, R.color.picture_color_9b); // 预览界面底部背景色 mPictureParameterStyle.picturePreviewBottomBgColor = ContextCompat.getColor(context, R.color.picture_color_white); // 原图按钮勾选样式 需设置.isOriginalImageControl(true); 才有效 mPictureParameterStyle.pictureOriginalControlStyle = R.drawable.picture_original_checkbox; // 原图文字颜色 需设置.isOriginalImageControl(true); 才有效 mPictureParameterStyle.pictureOriginalFontColor = ContextCompat.getColor(context, R.color.app_color_53575e); // 外部预览界面删除按钮样式 mPictureParameterStyle.pictureExternalPreviewDeleteStyle = R.drawable.picture_icon_black_delete; // 外部预览界面是否显示删除按钮 mPictureParameterStyle.pictureExternalPreviewGonePreviewDelete = true; // // 自定义相册右侧文本内容设置 // mPictureParameterStyle.pictureRightDefaultText = ""; // // 自定义相册未完成文本内容 // mPictureParameterStyle.pictureUnCompleteText = ""; // // 自定义相册完成文本内容 // mPictureParameterStyle.pictureCompleteText = ""; // // 自定义相册列表不可预览文字 // mPictureParameterStyle.pictureUnPreviewText = ""; // // 自定义相册列表预览文字 // mPictureParameterStyle.picturePreviewText = ""; // // 自定义相册标题字体大小 // mPictureParameterStyle.pictureTitleTextSize = 18; // // 自定义相册右侧文字大小 // mPictureParameterStyle.pictureRightTextSize = 14; // // 自定义相册预览文字大小 // mPictureParameterStyle.picturePreviewTextSize = 14; // // 自定义相册完成文字大小 // mPictureParameterStyle.pictureCompleteTextSize = 14; // // 自定义原图文字大小 // mPictureParameterStyle.pictureOriginalTextSize = 14; // 裁剪主题 mCropParameterStyle = new PictureCropParameterStyle( ContextCompat.getColor(context, R.color.color_white), ContextCompat.getColor(context, R.color.color_white), ContextCompat.getColor(context, R.color.color_black), mPictureParameterStyle.isChangeStatusBarFontColor); return this; } public PictureSelectorUtil getNumStyle(Context context) { // 相册主题 mPictureParameterStyle = new PictureParameterStyle(); // 是否改变状态栏字体颜色(黑白切换) mPictureParameterStyle.isChangeStatusBarFontColor = false; // 是否开启右下角已完成(0/9)风格 mPictureParameterStyle.isOpenCompletedNumStyle = false; // 是否开启类似QQ相册带数字选择风格 mPictureParameterStyle.isOpenCheckNumStyle = true; // 相册状态栏背景色 mPictureParameterStyle.pictureStatusBarColor = Color.parseColor("#7D7DFF"); // 相册列表标题栏背景色 mPictureParameterStyle.pictureTitleBarBackgroundColor = Color.parseColor("#7D7DFF"); // 相册列表标题栏右侧上拉箭头 mPictureParameterStyle.pictureTitleUpResId = R.drawable.picture_icon_arrow_up; // 相册列表标题栏右侧下拉箭头 mPictureParameterStyle.pictureTitleDownResId = R.drawable.picture_icon_arrow_down; // 相册文件夹列表选中圆点 mPictureParameterStyle.pictureFolderCheckedDotStyle = R.drawable.picture_orange_oval; // 相册返回箭头 mPictureParameterStyle.pictureLeftBackIcon = R.drawable.picture_icon_back; // 标题栏字体颜色 mPictureParameterStyle.pictureTitleTextColor = ContextCompat.getColor(context, R.color.color_white); // 相册右侧取消按钮字体颜色 废弃 改用.pictureRightDefaultTextColor和.pictureRightDefaultTextColor mPictureParameterStyle.pictureCancelTextColor = ContextCompat.getColor(context, R.color.color_white); // 相册列表勾选图片样式 mPictureParameterStyle.pictureCheckedStyle = R.drawable.checkbox_num_selector; // 相册列表底部背景色 mPictureParameterStyle.pictureBottomBgColor = ContextCompat.getColor(context, R.color.picture_color_fa); // 已选数量圆点背景样式 mPictureParameterStyle.pictureCheckNumBgStyle = R.drawable.num_oval_blue; // 相册列表底下预览文字色值(预览按钮可点击时的色值) mPictureParameterStyle.picturePreviewTextColor = ContextCompat.getColor(context, R.color.picture_color_blue); // 相册列表底下不可预览文字色值(预览按钮不可点击时的色值) mPictureParameterStyle.pictureUnPreviewTextColor = ContextCompat.getColor(context, R.color.app_color_blue); // 相册列表已完成色值(已完成 可点击色值) mPictureParameterStyle.pictureCompleteTextColor = ContextCompat.getColor(context, R.color.app_color_blue); // 相册列表未完成色值(请选择 不可点击色值) mPictureParameterStyle.pictureUnCompleteTextColor = ContextCompat.getColor(context, R.color.app_color_blue); // 预览界面底部背景色 mPictureParameterStyle.picturePreviewBottomBgColor = ContextCompat.getColor(context, R.color.picture_color_fa); // 原图按钮勾选样式 需设置.isOriginalImageControl(true); 才有效 mPictureParameterStyle.pictureOriginalControlStyle = R.drawable.picture_original_blue_checkbox; // 原图文字颜色 需设置.isOriginalImageControl(true); 才有效 mPictureParameterStyle.pictureOriginalFontColor = ContextCompat.getColor(context, R.color.app_color_blue); // 外部预览界面删除按钮样式 mPictureParameterStyle.pictureExternalPreviewDeleteStyle = R.drawable.picture_icon_delete; // 外部预览界面是否显示删除按钮 mPictureParameterStyle.pictureExternalPreviewGonePreviewDelete = true; // // 自定义相册右侧文本内容设置 // mPictureParameterStyle.pictureRightDefaultText = ""; // // 自定义相册未完成文本内容 // mPictureParameterStyle.pictureUnCompleteText = ""; // // 自定义相册完成文本内容 // mPictureParameterStyle.pictureCompleteText = ""; // // 自定义相册列表不可预览文字 // mPictureParameterStyle.pictureUnPreviewText = ""; // // 自定义相册列表预览文字 // mPictureParameterStyle.picturePreviewText = ""; // // 自定义相册标题字体大小 // mPictureParameterStyle.pictureTitleTextSize = 18; // // 自定义相册右侧文字大小 // mPictureParameterStyle.pictureRightTextSize = 14; // // 自定义相册预览文字大小 // mPictureParameterStyle.picturePreviewTextSize = 14; // // 自定义相册完成文字大小 // mPictureParameterStyle.pictureCompleteTextSize = 14; // // 自定义原图文字大小 // mPictureParameterStyle.pictureOriginalTextSize = 14; // 裁剪主题 mCropParameterStyle = new PictureCropParameterStyle( ContextCompat.getColor(context, R.color.app_color_blue), ContextCompat.getColor(context, R.color.app_color_blue), ContextCompat.getColor(context, R.color.color_white), mPictureParameterStyle.isChangeStatusBarFontColor); return this; } public PictureSelectorUtil getSinaStyle(Context context) { // 相册主题 mPictureParameterStyle = new PictureParameterStyle(); // 是否改变状态栏字体颜色(黑白切换) mPictureParameterStyle.isChangeStatusBarFontColor = true; // 是否开启右下角已完成(0/9)风格 mPictureParameterStyle.isOpenCompletedNumStyle = true; // 是否开启类似QQ相册带数字选择风格 mPictureParameterStyle.isOpenCheckNumStyle = false; // 相册状态栏背景色 mPictureParameterStyle.pictureStatusBarColor = Color.parseColor("#FFFFFF"); // 相册列表标题栏背景色 mPictureParameterStyle.pictureTitleBarBackgroundColor = Color.parseColor("#FFFFFF"); // 相册列表标题栏右侧上拉箭头 mPictureParameterStyle.pictureTitleUpResId = R.drawable.ic_orange_arrow_up; // 相册列表标题栏右侧下拉箭头 mPictureParameterStyle.pictureTitleDownResId = R.drawable.ic_orange_arrow_down; // 相册文件夹列表选中圆点 mPictureParameterStyle.pictureFolderCheckedDotStyle = R.drawable.picture_orange_oval; // 相册返回箭头 mPictureParameterStyle.pictureLeftBackIcon = R.drawable.ic_back_arrow; // 标题栏字体颜色 mPictureParameterStyle.pictureTitleTextColor = ContextCompat.getColor(context, R.color.color_black); // 相册右侧取消按钮字体颜色 废弃 改用.pictureRightDefaultTextColor和.pictureRightDefaultTextColor mPictureParameterStyle.pictureCancelTextColor = ContextCompat.getColor(context, R.color.color_black); // 相册列表勾选图片样式 mPictureParameterStyle.pictureCheckedStyle = R.drawable.picture_checkbox_selector; // 相册列表底部背景色 mPictureParameterStyle.pictureBottomBgColor = ContextCompat.getColor(context, R.color.picture_color_fa); // 已选数量圆点背景样式 mPictureParameterStyle.pictureCheckNumBgStyle = R.drawable.picture_num_oval; // 相册列表底下预览文字色值(预览按钮可点击时的色值) mPictureParameterStyle.picturePreviewTextColor = ContextCompat.getColor(context, R.color.picture_color_fa632d); // 相册列表底下不可预览文字色值(预览按钮不可点击时的色值) mPictureParameterStyle.pictureUnPreviewTextColor = ContextCompat.getColor(context, R.color.picture_color_9b); // 相册列表已完成色值(已完成 可点击色值) mPictureParameterStyle.pictureCompleteTextColor = ContextCompat.getColor(context, R.color.picture_color_fa632d); // 相册列表未完成色值(请选择 不可点击色值) mPictureParameterStyle.pictureUnCompleteTextColor = ContextCompat.getColor(context, R.color.picture_color_9b); // 预览界面底部背景色 mPictureParameterStyle.picturePreviewBottomBgColor = ContextCompat.getColor(context, R.color.picture_color_fa); // 原图按钮勾选样式 需设置.isOriginalImageControl(true); 才有效 mPictureParameterStyle.pictureOriginalControlStyle = R.drawable.picture_original_checkbox; // 原图文字颜色 需设置.isOriginalImageControl(true); 才有效 mPictureParameterStyle.pictureOriginalFontColor = ContextCompat.getColor(context, R.color.app_color_53575e); // 外部预览界面删除按钮样式 mPictureParameterStyle.pictureExternalPreviewDeleteStyle = R.drawable.picture_icon_black_delete; // 外部预览界面是否显示删除按钮 mPictureParameterStyle.pictureExternalPreviewGonePreviewDelete = true; // // 自定义相册右侧文本内容设置 // mPictureParameterStyle.pictureRightDefaultText = ""; // 完成文案是否采用(%1$d/%2$d)的字符串,只允许俩个占位符哟 // mPictureParameterStyle.isCompleteReplaceNum = true; // // 自定义相册未完成文本内容 // mPictureParameterStyle.pictureUnCompleteText = "请选择"; // 自定义相册完成文本内容,已经支持两个占位符String 但isCompleteReplaceNum必须为true // mPictureParameterStyle.pictureCompleteText = getString(R.string.app_wechat_send_num); // // 自定义相册列表不可预览文字 // mPictureParameterStyle.pictureUnPreviewText = ""; // // 自定义相册列表预览文字 // mPictureParameterStyle.picturePreviewText = ""; // // 自定义相册标题字体大小 // mPictureParameterStyle.pictureTitleTextSize = 18; // // 自定义相册右侧文字大小 // mPictureParameterStyle.pictureRightTextSize = 14; // // 自定义相册预览文字大小 // mPictureParameterStyle.picturePreviewTextSize = 14; // // 自定义相册完成文字大小 // mPictureParameterStyle.pictureCompleteTextSize = 14; // // 自定义原图文字大小 // mPictureParameterStyle.pictureOriginalTextSize = 14; // 裁剪主题 mCropParameterStyle = new PictureCropParameterStyle( ContextCompat.getColor(context, R.color.color_white), ContextCompat.getColor(context, R.color.color_white), ContextCompat.getColor(context, R.color.color_black), mPictureParameterStyle.isChangeStatusBarFontColor); return this; } public PictureSelectorUtil getWeChatStyle(Context context) { // 相册主题 mPictureParameterStyle = new PictureParameterStyle(); // 是否改变状态栏字体颜色(黑白切换) mPictureParameterStyle.isChangeStatusBarFontColor = false; // 是否开启右下角已完成(0/9)风格 mPictureParameterStyle.isOpenCompletedNumStyle = false; // 是否开启类似QQ相册带数字选择风格 mPictureParameterStyle.isOpenCheckNumStyle = true; // 状态栏背景色 mPictureParameterStyle.pictureStatusBarColor = Color.parseColor("#393a3e"); // 相册列表标题栏背景色 mPictureParameterStyle.pictureTitleBarBackgroundColor = Color.parseColor("#393a3e"); // 相册父容器背景色 mPictureParameterStyle.pictureContainerBackgroundColor = ContextCompat.getColor(context, R.color.color_black); // 相册列表标题栏右侧上拉箭头 mPictureParameterStyle.pictureTitleUpResId = R.drawable.picture_icon_wechat_up; // 相册列表标题栏右侧下拉箭头 mPictureParameterStyle.pictureTitleDownResId = R.drawable.picture_icon_wechat_down; // 相册文件夹列表选中圆点 mPictureParameterStyle.pictureFolderCheckedDotStyle = R.drawable.picture_orange_oval; // 相册返回箭头 mPictureParameterStyle.pictureLeftBackIcon = R.drawable.picture_icon_close; // 标题栏字体颜色 mPictureParameterStyle.pictureTitleTextColor = ContextCompat.getColor(context, R.color.picture_color_white); // 相册右侧按钮字体颜色 废弃 改用.pictureRightDefaultTextColor和.pictureRightDefaultTextColor mPictureParameterStyle.pictureCancelTextColor = ContextCompat.getColor(context, R.color.picture_color_53575e); // 相册右侧按钮字体默认颜色 mPictureParameterStyle.pictureRightDefaultTextColor = ContextCompat.getColor(context, R.color.picture_color_53575e); // 相册右侧按可点击字体颜色,只针对isWeChatStyle 为true时有效果 mPictureParameterStyle.pictureRightSelectedTextColor = ContextCompat.getColor(context, R.color.picture_color_white); // 相册右侧按钮背景样式,只针对isWeChatStyle 为true时有效果 mPictureParameterStyle.pictureUnCompleteBackgroundStyle = R.drawable.picture_send_button_default_bg; // 相册右侧按钮可点击背景样式,只针对isWeChatStyle 为true时有效果 mPictureParameterStyle.pictureCompleteBackgroundStyle = R.drawable.picture_send_button_bg; // 相册列表勾选图片样式 mPictureParameterStyle.pictureCheckedStyle = R.drawable.picture_wechat_num_selector; // 相册标题背景样式 ,只针对isWeChatStyle 为true时有效果 mPictureParameterStyle.pictureWeChatTitleBackgroundStyle = R.drawable.picture_album_bg; // 微信样式 预览右下角样式 ,只针对isWeChatStyle 为true时有效果 mPictureParameterStyle.pictureWeChatChooseStyle = R.drawable.picture_wechat_select_cb; // 相册返回箭头 ,只针对isWeChatStyle 为true时有效果 mPictureParameterStyle.pictureWeChatLeftBackStyle = R.drawable.picture_icon_back; // 相册列表底部背景色 mPictureParameterStyle.pictureBottomBgColor = ContextCompat.getColor(context, R.color.picture_color_grey); // 已选数量圆点背景样式 mPictureParameterStyle.pictureCheckNumBgStyle = R.drawable.picture_num_oval; // 相册列表底下预览文字色值(预览按钮可点击时的色值) mPictureParameterStyle.picturePreviewTextColor = ContextCompat.getColor(context, R.color.picture_color_white); // 相册列表底下不可预览文字色值(预览按钮不可点击时的色值) mPictureParameterStyle.pictureUnPreviewTextColor = ContextCompat.getColor(context, R.color.picture_color_9b); // 相册列表已完成色值(已完成 可点击色值) mPictureParameterStyle.pictureCompleteTextColor = ContextCompat.getColor(context, R.color.picture_color_white); // 相册列表未完成色值(请选择 不可点击色值) mPictureParameterStyle.pictureUnCompleteTextColor = ContextCompat.getColor(context, R.color.picture_color_53575e); // 预览界面底部背景色 mPictureParameterStyle.picturePreviewBottomBgColor = ContextCompat.getColor(context, R.color.picture_color_half_grey); // 外部预览界面删除按钮样式 mPictureParameterStyle.pictureExternalPreviewDeleteStyle = R.drawable.picture_icon_delete; // 原图按钮勾选样式 需设置.isOriginalImageControl(true); 才有效 mPictureParameterStyle.pictureOriginalControlStyle = R.drawable.picture_original_wechat_checkbox; // 原图文字颜色 需设置.isOriginalImageControl(true); 才有效 mPictureParameterStyle.pictureOriginalFontColor = ContextCompat.getColor(context, R.color.color_white); // 外部预览界面是否显示删除按钮 mPictureParameterStyle.pictureExternalPreviewGonePreviewDelete = true; // 设置NavBar Color SDK Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP有效 mPictureParameterStyle.pictureNavBarColor = Color.parseColor("#393a3e"); // 完成文案是否采用(%1$d/%2$d)的字符串,只允许两个占位符哟 // mPictureParameterStyle.isCompleteReplaceNum = true; // 自定义相册右侧文本内容设置 // mPictureParameterStyle.pictureUnCompleteText = getString(R.string.app_wechat_send); //自定义相册右侧已选中时文案 支持占位符String 但只支持两个 必须isCompleteReplaceNum为true // mPictureParameterStyle.pictureCompleteText = getString(R.string.app_wechat_send_num); // // 自定义相册列表不可预览文字 // mPictureParameterStyle.pictureUnPreviewText = ""; // // 自定义相册列表预览文字 // mPictureParameterStyle.picturePreviewText = ""; // // 自定义预览页右下角选择文字文案 // mPictureParameterStyle.pictureWeChatPreviewSelectedText = ""; // // 自定义相册标题文字大小 // mPictureParameterStyle.pictureTitleTextSize = 9; // // 自定义相册右侧文字大小 // mPictureParameterStyle.pictureRightTextSize = 9; // // 自定义相册预览文字大小 // mPictureParameterStyle.picturePreviewTextSize = 9; // // 自定义相册完成文字大小 // mPictureParameterStyle.pictureCompleteTextSize = 9; // // 自定义原图文字大小 // mPictureParameterStyle.pictureOriginalTextSize = 9; // // 自定义预览页右下角选择文字大小 // mPictureParameterStyle.pictureWeChatPreviewSelectedTextSize = 9; // 裁剪主题 mCropParameterStyle = new PictureCropParameterStyle( ContextCompat.getColor(context, R.color.app_color_grey), ContextCompat.getColor(context, R.color.app_color_grey), Color.parseColor("#393a3e"), ContextCompat.getColor(context, R.color.color_white), mPictureParameterStyle.isChangeStatusBarFontColor); return this; } public PictureSelectorUtil defaultWindowStyle() { mWindowAnimationStyle = new PictureWindowAnimationStyle(); return this; } public PictureSelectorUtil upAnimationWindowStyle() { mWindowAnimationStyle = new PictureWindowAnimationStyle(); mWindowAnimationStyle.ofAllAnimation(R.anim.picture_anim_up_in, R.anim.picture_anim_down_out); return this; } }
true
8b35544ce56cc35edb97c869304c5ac888b828b8
Java
ldhisgood/graduation
/src/com/qykh/core/dao/impl/SupplierDao.java
UTF-8
393
1.921875
2
[]
no_license
package com.qykh.core.dao.impl; import org.springframework.stereotype.Repository; import com.qykh.core.dao.ISupplierDao; import com.qykh.core.domain.TSupplier; import com.qykh.frame.dao.HibernateBaseDao; @Repository public class SupplierDao extends HibernateBaseDao<TSupplier> implements ISupplierDao{ @Override public Class<TSupplier> getEntityClass() { return TSupplier.class; } }
true
55a867966236790418e927e533b353bb8ae842f9
Java
antomy-gc/art-java
/application-configurator/src/main/java/ru/art/configurator/service/ConfiguratorService.java
UTF-8
3,268
1.773438
2
[ "Apache-2.0" ]
permissive
/* * ART Java * * Copyright 2019 ART * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.art.configurator.service; import ru.art.config.remote.api.specification.*; import ru.art.configurator.api.model.*; import ru.art.core.checker.*; import ru.art.entity.*; import static ru.art.configurator.api.model.Configuration.*; import static ru.art.configurator.constants.ConfiguratorDbConstants.*; import static ru.art.configurator.dao.ConfiguratorDao.*; import static ru.art.configurator.provider.ModulesConnectionParametersProvider.*; import static ru.art.entity.Entity.*; import java.util.*; public interface ConfiguratorService { static void uploadConfiguration(Configuration configuration) { saveConfig(configuration); } static void uploadApplicationConfiguration(Configuration configuration) { saveApplicationConfiguration(configuration.getConfiguration()); } static void uploadProfileConfiguration(ProfileConfiguration configuration) { saveProfileConfiguration(configuration.getProfileId(), configuration.getConfiguration()); } static void uploadModuleConfiguration(ModuleConfiguration configuration) { saveModuleConfiguration(configuration.getModuleKey(), configuration.getConfiguration()); } static Configuration getConfiguration(ModuleKey moduleKey) { ConfigurationBuilder applicationConfigurationBuilder = builder().configuration(entityBuilder().build()); getConfig(moduleKey.formatKey()) .map(Value::asEntity) .ifPresent(applicationConfigurationBuilder::configuration); return applicationConfigurationBuilder.build(); } static Set<ModuleKey> getProfiles() { return getProfileKeys(); } static Set<ModuleKey> getModules() { return getModuleKeys(); } static Configuration getApplicationConfiguration() { return builder() .configuration(getConfig(APPLICATION).map(Value::asEntity).orElse(entityBuilder().build())) .build(); } static void deleteModuleWithConfiguration(ModuleKey moduleKey) { deleteModule(moduleKey.formatKey()); } static void deleteProfileWithConfiguration(ProfileKey profileKey) { deleteProfile(profileKey.getProfileId()); } static void applyModuleConfiguration(ModuleKey moduleKey) { getModulesConnectionParameters(moduleKey) .stream() .filter(CheckerForEmptiness::isNotEmpty) .map(parameters -> new RemoteConfigCommunicationSpecification(parameters.getGrpcHost(), parameters.getGrpcPort(), parameters.getGrpcPath())) .forEach(RemoteConfigCommunicationSpecification::applyConfiguration); } }
true
62873b495be58ae6e23062287ac07cd6150036eb
Java
amanishr/Stock-Management-Back-End
/stock_management/src/com/walmart/dao/EmployeeDaoInterface.java
UTF-8
412
2.109375
2
[]
no_license
package com.walmart.dao; import java.util.List; import com.walmart.exceptions.StockException; import com.walmart.pojo.Employee; public interface EmployeeDaoInterface { public int addEmployee(Employee e); public int updateEmployee(double salary, String active, int eid); public int deleteEmployee(int eid); public Employee getEmployeeById(int id) throws StockException; public List<Employee> getAll(); }
true
22a1823b8052aa90cee2e85f103ddb795c22c09d
Java
gaurav121/RedisSpringBoot
/demo-service/src/main/java/com/demo/configuration/GenericExceptionHandler.java
UTF-8
1,512
2.28125
2
[]
no_license
package com.demo.configuration; import com.demo.exception.StudentNotFoundException; import com.demo.object.response.BaseResponse; import org.slf4j.MDC; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import javax.servlet.http.HttpServletRequest; @RestController @ControllerAdvice public class GenericExceptionHandler extends ResponseEntityExceptionHandler{ private ResponseEntity<BaseResponse> generateErrorresponse(String message, HttpStatus responseStatus, String errorCode) { BaseResponse baseResponse = new BaseResponse(); BaseResponse.Response response=baseResponse.new Response(); response.setErrorCode(errorCode); response.setHttpStatus(responseStatus); response.setMessage(message); baseResponse.setResponse(response); return new ResponseEntity(baseResponse, HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(StudentNotFoundException.class) ResponseEntity<?> handleStudentNotFoundException(HttpServletRequest request, Throwable ex) { return generateErrorresponse(((StudentNotFoundException)ex).getMessage(),HttpStatus.NOT_FOUND , ((StudentNotFoundException)ex).getCode()); } }
true
466014ed96f02da704e8261d1939a489c1dc80a4
Java
testoftiramisu/SpringCoreCourse
/src/test/java/com/epam/spring/hometask/service/booking/CinemaBookingServiceTestConfig.java
UTF-8
1,295
1.835938
2
[ "MIT" ]
permissive
package com.epam.spring.hometask.service.booking; import com.epam.spring.hometask.dao.ticket.CinemaTicketDaoTestConfig; import com.epam.spring.hometask.dao.ticket.TicketDao; import com.epam.spring.hometask.domain.auditorium.AuditoriumsConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import({CinemaTicketDaoTestConfig.class, AuditoriumsConfig.class}) public class CinemaBookingServiceTestConfig { @Autowired @Qualifier("ticketTestDao") TicketDao ticketsDao; @Value("${highRateCoefficient}") private String highRateCoefficient; @Value("${vipSeatsCoefficient}") private String vipSeatsCoefficient; @Bean(name = "eventService") public BookingService getBookingService() { BookingService bookingService = new CinemaBookingService(ticketsDao); bookingService.setHighRateCoefficient(Double.parseDouble(highRateCoefficient)); bookingService.setVipSeatsCoefficient(Double.parseDouble(vipSeatsCoefficient)); return bookingService; } }
true
eea79fcad954c3e657116bda6d963361b98446da
Java
Alex2Apple/wsoFrame
/registry/src/main/java/com/wang/web/config/WebConfig.java
UTF-8
1,263
2.140625
2
[]
no_license
package com.wang.web.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; /** * @author wangju * */ @Configuration @EnableWebMvc @ComponentScan(basePackages = { "com.wang.web" }) public class WebConfig extends WebMvcConfigurerAdapter { private static final String VIEWS_PATH = "/WEB-INF/views/"; private static final String VIEWS_FILE_SUFFIX = ".jsp"; @Bean public ViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix(VIEWS_PATH); resolver.setSuffix(VIEWS_FILE_SUFFIX); resolver.setExposeContextBeansAsAttributes(true); return resolver; } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } }
true
8f517af4367e0545eddd2785da518be74ee36b36
Java
treCoops/Gurind
/app/src/main/java/com/dtinnovation/gurind/Activity_Recently_Completed.java
UTF-8
16,956
1.859375
2
[]
no_license
package com.dtinnovation.gurind; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import android.app.ProgressDialog; import android.content.Context; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Vibrator; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import com.andrognito.flashbar.Flashbar; import com.andrognito.flashbar.anim.FlashAnim; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.RetryPolicy; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Objects; public class Activity_Recently_Completed extends Fragment { private Flashbar flashbar; private ProgressDialog progressDialog; private Vibrator vibrate; @Nullable @Override public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.activity_recently_completed, container, false); flashbar = null;progressDialog = new ProgressDialog(view.getContext()); progressDialog.setTitle("Please Wait..!"); progressDialog.setMessage("Fetching data for the table.!"); progressDialog.setIcon(R.drawable.splashlogo); progressDialog.setCanceledOnTouchOutside(false); final TableLayout tableLayout = view.findViewById(R.id.tableLayout_RC); vibrate = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE); ConnectivityManager conMgr = (ConnectivityManager) Objects.requireNonNull(getActivity()).getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = conMgr.getActiveNetworkInfo(); if (netInfo == null){ vibrate.vibrate(20); if(flashbar == null){ flashbar = enterExitAnimationSlide("Please enable your internet connection.!"); } flashbar.show(); }else{ try { progressDialog.show(); if(Activity_SignIn.Customer_id.equals("0")){ progressDialog.dismiss(); vibrate.vibrate(20); if (flashbar == null) { flashbar = enterExitAnimationSlide("Select a customer."); } flashbar.show(); } RequestQueue queue = Volley.newRequestQueue(view.getContext()); String url = "http://220.247.238.246/gurind/mobile_API/recently_completed.php"; JSONObject Customer = new JSONObject(); Customer.put("customer_id", Activity_SignIn.Customer_id); final JsonObjectRequest jsonObject = new JsonObjectRequest(Request.Method.POST, url, Customer, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try{ if(response.getInt("status") == 500) { if (flashbar == null) { flashbar = enterExitAnimationSlide1(response.getString("message")); } flashbar.show(); progressDialog.dismiss(); vibrate.vibrate(20); } if(response.getInt("status") == 200){ JSONArray jsonArray = response.getJSONArray("data"); for(int i=0; i<jsonArray.length(); i++){ JSONObject data = jsonArray.getJSONObject(i); if(i % 2 == 0){ TableRow tr = new TableRow(view.getContext()); tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT)); TextView t1 = new TextView(view.getContext()); t1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.MATCH_PARENT)); t1.setText(data.getString("QUOTATION_NO")); t1.setTextColor(Color.parseColor("#000000")); t1.setBackground(view.getResources().getDrawable(R.drawable.table_body1)); t1.setTextSize(15); t1.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); t1.setPadding(15,3, 15, 3); tr.addView(t1); TextView t2 = new TextView(view.getContext()); t2.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.MATCH_PARENT)); t2.setText(data.getString("PROJECT_REFERENCE")); t2.setTextColor(Color.parseColor("#000000")); t2.setBackground(view.getResources().getDrawable(R.drawable.table_body1)); t2.setTextSize(15); t2.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); t2.setPadding(15,3, 15, 3); tr.addView(t2); TextView t3 = new TextView(view.getContext()); t3.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.MATCH_PARENT)); t3.setText(data.getString("TOTAL_DISPATCHED")); t3.setTextColor(Color.parseColor("#000000")); t3.setBackground(view.getResources().getDrawable(R.drawable.table_body1)); t3.setTextSize(15); t3.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); t3.setPadding(15,3, 15, 3); tr.addView(t3); TextView t4 = new TextView(view.getContext()); t4.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.MATCH_PARENT)); t4.setText(data.getString("LAST_DISP_NO")); t4.setTextColor(Color.parseColor("#000000")); t4.setBackground(view.getResources().getDrawable(R.drawable.table_body1)); t4.setTextSize(15); t4.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); t4.setPadding(15,3, 15, 3); tr.addView(t4); TextView t5 = new TextView(view.getContext()); t5.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.MATCH_PARENT)); t5.setText(data.getString("LAST_DISP_DATE")); t5.setTextColor(Color.parseColor("#000000")); t5.setBackground(view.getResources().getDrawable(R.drawable.table_body1)); t5.setTextSize(15); t5.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); t5.setPadding(15,3, 15, 3); tr.addView(t5); tableLayout.addView(tr); }else{ TableRow tr = new TableRow(view.getContext()); tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT)); TextView t1 = new TextView(view.getContext()); t1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.MATCH_PARENT)); t1.setText(data.getString("QUOTATION_NO")); t1.setTextColor(Color.parseColor("#000000")); t1.setBackground(view.getResources().getDrawable(R.drawable.table_body2)); t1.setTextSize(15); t1.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); t1.setPadding(15,3, 15, 3); tr.addView(t1); TextView t2 = new TextView(view.getContext()); t2.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.MATCH_PARENT)); t2.setText(data.getString("PROJECT_REFERENCE")); t2.setTextColor(Color.parseColor("#000000")); t2.setBackground(view.getResources().getDrawable(R.drawable.table_body2)); t2.setTextSize(15); t2.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); t2.setPadding(15,3, 15, 3); tr.addView(t2); TextView t3 = new TextView(view.getContext()); t3.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.MATCH_PARENT)); t3.setText(data.getString("TOTAL_DISPATCHED")); t3.setTextColor(Color.parseColor("#000000")); t3.setBackground(view.getResources().getDrawable(R.drawable.table_body2)); t3.setTextSize(15); t3.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); t3.setPadding(15,3, 15, 3); tr.addView(t3); TextView t4 = new TextView(view.getContext()); t4.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.MATCH_PARENT)); t4.setText(data.getString("LAST_DISP_NO")); t4.setTextColor(Color.parseColor("#000000")); t4.setBackground(view.getResources().getDrawable(R.drawable.table_body2)); t4.setTextSize(15); t4.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); t4.setPadding(15,3, 15, 3); tr.addView(t4); TextView t5 = new TextView(view.getContext()); t5.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.MATCH_PARENT)); t5.setText(data.getString("LAST_DISP_DATE")); t5.setTextColor(Color.parseColor("#000000")); t5.setBackground(view.getResources().getDrawable(R.drawable.table_body2)); t5.setTextSize(15); t5.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); t5.setPadding(15,3, 15, 3); tr.addView(t5); tableLayout.addView(tr); } } progressDialog.dismiss(); } }catch(JSONException ex){ Log.e("Error", ex.getMessage()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Error", error.toString()); } }); jsonObject.setShouldCache(false); jsonObject.setRetryPolicy(new RetryPolicy() { @Override public int getCurrentTimeout() { return 50000; } @Override public int getCurrentRetryCount() { return 50000; } @Override public void retry(VolleyError error) throws VolleyError { } }); queue.add(jsonObject); }catch(Exception e) { progressDialog.dismiss(); Log.e("Exception Error", Objects.requireNonNull(e.getMessage())); if (flashbar == null) { flashbar = enterExitAnimationSlide("There was a problem with your request. Please try again later."); } flashbar.show(); } } return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //you can set the title for your toolbar here for different fragments different titles getActivity().setTitle("Recently Completed Orders (30 Days)"); } private Flashbar enterExitAnimationSlide(String msg){ return new Flashbar.Builder(getActivity()) .gravity(Flashbar.Gravity.BOTTOM) .duration(3000) .message(msg) .messageColor(ContextCompat.getColor(getActivity(), R.color.splashBackground)) .backgroundColor(ContextCompat.getColor(getActivity(), R.color.flashBackground)) .showIcon() .iconColorFilterRes(R.color.flashIcon) .icon(R.drawable.ic_cross) .enterAnimation(FlashAnim.with(getActivity()) .animateBar() .duration(200) .slideFromLeft() .overshoot()) .exitAnimation(FlashAnim.with(getActivity()) .animateBar() .duration(2800) .slideFromLeft() .overshoot()) .build(); } private Flashbar enterExitAnimationSlide1(String msg){ return new Flashbar.Builder(getActivity()) .gravity(Flashbar.Gravity.BOTTOM) .duration(5000) .title("Oops..") .message(msg) .messageColor(ContextCompat.getColor(getActivity(), R.color.splashBackground)) .backgroundColor(ContextCompat.getColor(getActivity(), R.color.flashBackground)) .showIcon() .iconColorFilterRes(R.color.flashCaution) .icon(R.drawable.ic_caution) .enterAnimation(FlashAnim.with(getActivity()) .animateBar() .duration(200) .slideFromLeft() .overshoot()) .exitAnimation(FlashAnim.with(getActivity()) .animateBar() .duration(4800) .slideFromLeft() .overshoot()) .build(); } }
true
0b097f048cf2ef0618142b3622f23f0c053d90b8
Java
AcepcsMa/Java-offer
/src/chapter7/SerializeBT.java
UTF-8
2,047
3.90625
4
[]
no_license
package chapter7; import java.util.LinkedList; import java.util.Queue; public class SerializeBT { public static void main(String[] args) { TreeNode node1 = new TreeNode(1); TreeNode node2 = new TreeNode(2); TreeNode node3 = new TreeNode(3); TreeNode node4 = new TreeNode(4); TreeNode node5 = new TreeNode(5); TreeNode node6 = new TreeNode(6); TreeNode node7 = new TreeNode(7); node1.left = node2; node1.right = node3; node2.left = node4; node2.right = node5; node3.left = node6; node3.right = node7; String s = serializeBT(node1); TreeNode root = deserializeBT(s); inOrder(root); } /** * 序列化二叉树 * @param root 根节点 * @return 序列化字符串 */ public static String serializeBT(TreeNode root) { StringBuilder sb = new StringBuilder(); preOrder(root, sb); return sb.toString(); } /** * 先序遍历 * @param cur 当前节点 * @param sb 遍历序列 */ public static void preOrder(TreeNode cur, StringBuilder sb) { if(cur == null) { sb.append("#").append(","); } else { sb.append(cur.val).append(","); preOrder(cur.left, sb); preOrder(cur.right, sb); } } /** * 反序列化二叉树 * @param s 序列 * @return 二叉树根节点 */ public static TreeNode deserializeBT(String s) { String[] nodes = s.split(","); Queue<String> queue = new LinkedList<>(); for(String node : nodes) { queue.add(node); } return construct(queue); } /** * 利用先序思想构造二叉树 * @param queue 序列 * @return 当前树节点 */ public static TreeNode construct(Queue<String> queue) { if(queue.isEmpty()) { return null; } String cur = queue.poll(); if(cur.equals("#")) { return null; } else { TreeNode curNode = new TreeNode(Integer.parseInt(cur)); curNode.left = construct(queue); curNode.right = construct(queue); return curNode; } } public static void inOrder(TreeNode cur) { if(cur != null) { inOrder(cur.left); System.out.println(cur.val); inOrder(cur.right); } } }
true
b8861df804db8ec34d2ca641ec74b1ad33e731d9
Java
istyle1105/DA106G6
/src/com/logcom/model/Log_comDAO_interface.java
UTF-8
454
1.828125
2
[]
no_license
package com.logcom.model; import java.util.List; public interface Log_comDAO_interface { public void insert(Log_comVO log_comvo); public void update(Log_comVO log_comvo); public void delete(String com_id); public Log_comVO findByPrimaryKey(String com_id); public List<Log_comVO> getAll(); public List<Log_comVO> getLog_com(String log_id); //萬用複合查詢傳入Map 回傳List // public List<Log_comVO> getAll(Map<String, String[]> map); }
true
a2009407b51794561913b138fbea8f0b4cfa3f29
Java
tiankong6622/weisky
/newframe/admin-template/src/main/java/org/itboys/admin/entity/AdminOrgCity.java
UTF-8
851
2.03125
2
[]
no_license
package org.itboys.admin.entity; import com.google.code.morphia.annotations.Entity; /** * 城市关联对象表 * @author huml * */ @Entity(value="AdminOrgCity", noClassnameStored = true) public class AdminOrgCity extends BaseAdminEntity{ private static final long serialVersionUID = -8569025903282005492L; public static final Integer TYPE_O=1;//关联组织 public static final Integer TYPE_U=2;//关联用户 private Long objId; private Integer type; private Long cityId; public Long getCityId() { return cityId; } public void setCityId(Long cityId) { this.cityId = cityId; } public Long getObjId() { return objId; } public void setObjId(Long objId) { this.objId = objId; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } }
true
2fc4936183f20ff60cbe1edbb43320b2b1664079
Java
comelf/L3Cache
/src/main/java/org/l3cache/dao/PostManager.java
UTF-8
5,162
2.015625
2
[]
no_license
package org.l3cache.dao; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import org.apache.mahout.cf.taste.recommender.Recommender; import org.l3cache.dto.Response; import org.l3cache.model.Post; import org.l3cache.model.PostId; import org.l3cache.model.PostSel; import org.l3cache.model.WritePost; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import core.utils.ResultCode; @Component public class PostManager { private static final int RECOMMENDATION_LISTS = 0; private static final int RECENT_LISTS = 1; private static final int POPULAR_LISTS = 2; @Autowired private SqlSession sqlSession; @Autowired private Recommender recommander; private static final Logger LOG = LoggerFactory .getLogger(PostManager.class); public PostManager() { } // public PostManager(SqlSession sqlSession, Recommender recommander) { // this.sqlSession = sqlSession; // this.recommander = recommander; // } public Post getPostDetail(long pid) { return sqlSession.selectOne("PostMapper.selectOnePost", pid); } public void savePost(WritePost post) { sqlSession.insert("PostMapper.create", post); } public void updateWithImage(WritePost post) { sqlSession.update("PostMapper.updateWithImage", post); } public void updateWithoutImage(WritePost post) { sqlSession.update("PostMapper.updateWithoutImage", post); } public String getPostImageFilePath(long pid) { Post post = getPostDetail(pid); return post.getImgUrl(); } public boolean isExistentPost(long pid) { Post post = getPostDetail(pid); if (post == null) { return false; } return true; } public void deletePost(long pid, int uid) { PostId postId = new PostId(pid, uid); sqlSession.delete("PostMapper.deletePost", postId); } public void likePost(long pid, int uid) { PostId postId = new PostId(pid, uid); sqlSession.insert("PostMapper.likePost", postId); } public void unlikePost(long pid, int uid) { PostId postId = new PostId(pid, uid); sqlSession.delete("PostMapper.unlikePost", postId); } public void readPost(long pid) { sqlSession.update("PostMapper.readPost", pid); } public long getPopularRows() { return sqlSession.selectOne("PostMapper.foundPopularPows"); } public int getTotalRows() { return sqlSession.selectOne("PostMapper.foundRows"); } public List<Post> getUserPostsList(int uid, int start) { start = (start - 1) * 20; PostSel postSel = new PostSel(start, uid); return sqlSession.selectList("PostMapper.selectUserPostsList", postSel); } public long getUserPostsCount(int uid) { return sqlSession.selectOne("PostMapper.countUserPostsList", uid); } public long getUserLikesCount(int uid) { return sqlSession.selectOne("PostMapper.countUserLikesList", uid); } public List<Post> getUserLikesList(int uid, int start) { start = (start - 1) * 20; PostSel postSel = new PostSel(start, uid); return sqlSession.selectList("PostMapper.selectUserLikesList", postSel); } public Response getPostsLists(int start, int id, int sort) { if(start<1 || id <1){ return Response.arguemntError(); } switch (sort) { case RECOMMENDATION_LISTS: if(start>1){ return Response.resultZero(); } return getRecommendedLists(id); case RECENT_LISTS: return getRecentlyLists(start, id); case POPULAR_LISTS: return getPopularLists(start, id); default: return getRecentlyLists(start, id); } } public Response getRecentlyLists(int start, int uid) { start = (start - 1) * 20; PostSel postSel = new PostSel(start, uid); Response response = Response.success(); response.setTotal(getTotalRows()); response.setData(sqlSession.selectList("PostMapper.selectRecentlyList", postSel)); return response; } private Response getPopularLists(int start, int uid) { start = (start - 1) * 20; PostSel postSel = new PostSel(start, uid); Response response = Response.success(); response.setTotal(getPopularRows()); response.setData(sqlSession.selectList("PostMapper.selectPopularList", postSel)); return response; } public Response getRecommendedLists(int id) { List<String> postIDList = getRecommendedPostIDList(id); if(postIDList.isEmpty()){ return Response.resultZero(); }else{ Response response = Response.success(); response.setTotal(postIDList.size()); response.setData(sqlSession.selectList("PostMapper.selectRecommendedLists", postIDList)); return response; } } public List<String> getRecommendedPostIDList(int id) { try { List<RecommendedItem> recommendations= recommander.recommend(id, 20); List<String> postIDList = new ArrayList<String>(); for(RecommendedItem recommendation:recommendations){ postIDList.add(String.valueOf(recommendation.getItemID())); } return postIDList; } catch (TasteException e) { LOG.debug("recommendations Fail!"); return new ArrayList<String>(); } } }
true
7e1c12aa8b13d57548103294be0b874f30a029f8
Java
13767004362/VolleyHelper
/volleyhelper/src/main/java/com/xingen/volleyhelper/hook/HookVolleyManager.java
UTF-8
2,512
2.265625
2
[ "Apache-2.0" ]
permissive
package com.xingen.volleyhelper.hook; import android.util.Log; import java.lang.reflect.Field; import java.lang.reflect.Proxy; /** * Author by {xinGen} * Date on 2018/8/1 10:54 */ public class HookVolleyManager { private final String TAG=HookVolleyManager.class.getSimpleName(); public void init(Object requestQueue) { if (requestQueue == null) { return; } try { Log.i(TAG, " HookVolleyManager init() "); Class<?> requestQueueClass = requestQueue.getClass(); Field networkField = requestQueueClass.getDeclaredField("mNetwork"); networkField.setAccessible(true); //获取到BasicNetwork对象 Object network = networkField.get(requestQueue); //接下来,设置动态代理 Object networkProxy = Proxy.newProxyInstance(requestQueue.getClass().getClassLoader(), network.getClass().getInterfaces(), new NetWorkHandler(network)); networkField.set(requestQueue, networkProxy); Field mDispatchersField = requestQueueClass.getDeclaredField("mDispatchers"); mDispatchersField.setAccessible(true); //获取到NetworkDispatcher线程组 Object[] networkDispatchers = (Object[]) mDispatchersField.get(requestQueue); //代理掉网络线程中的network for (Object object : networkDispatchers) { Class<?> mClass = object.getClass(); Field networkFields = mClass.getDeclaredField("mNetwork"); networkFields.setAccessible(true); networkFields.set(object, networkProxy); } //替代传输层 Class<?> baseNetworkClass = network.getClass(); Field mBaseHttpStackField = null; try { //适配volley 1.1 mBaseHttpStackField = baseNetworkClass.getDeclaredField("mBaseHttpStack"); mBaseHttpStackField.setAccessible(true); mBaseHttpStackField.set(network, new MyHttpStack()); } catch (Exception e) { e.printStackTrace(); } if (mBaseHttpStackField == null) { //适配volley 1.0 Field httpStackField = baseNetworkClass.getDeclaredField("mHttpStack"); httpStackField.setAccessible(true); httpStackField.set(network, new MyHttpStack()); } } catch (Exception e) { e.printStackTrace(); } } }
true
a45bee0999f5e5573c32a1a3e53754f36926c5a5
Java
L1anggez1fu/blogs
/src/main/java/com/lgzf/service/CommentService.java
UTF-8
308
1.65625
2
[]
no_license
package com.lgzf.service; import com.lgzf.pojo.Comment; import java.util.List; /** * @auther lgzf * @data 2020-03-05 - 15:20 **/ public interface CommentService { List<Comment> listCommentByBlogId(Long blogId); int saveComment(Comment comment); Comment getParentCommentById(Long id); }
true
cdc6b07a664ade383e623ac2de8fb16352e38ca2
Java
MyPureCloud/platform-client-sdk-java
/build/src/main/java/com/mypurecloud/sdk/v2/model/BuScheduleListItem.java
UTF-8
7,677
1.765625
2
[ "MIT" ]
permissive
package com.mypurecloud.sdk.v2.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import java.util.Objects; import java.util.ArrayList; import java.io.IOException; import com.fasterxml.jackson.annotation.JsonProperty; import com.mypurecloud.sdk.v2.model.BuShortTermForecastReference; import com.mypurecloud.sdk.v2.model.ScheduleGenerationResultSummary; import com.mypurecloud.sdk.v2.model.WfmVersionedEntityMetadata; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.time.LocalDate; import java.io.Serializable; /** * BuScheduleListItem */ public class BuScheduleListItem implements Serializable { private String id = null; private LocalDate weekDate = null; private Integer weekCount = null; private String description = null; private Boolean published = null; private BuShortTermForecastReference shortTermForecast = null; private ScheduleGenerationResultSummary generationResults = null; private WfmVersionedEntityMetadata metadata = null; private String selfUri = null; @ApiModelProperty(example = "null", value = "The globally unique identifier for the object.") @JsonProperty("id") public String getId() { return id; } /** * The start week date for this schedule. Dates are represented as an ISO-8601 string. For example: yyyy-MM-dd **/ public BuScheduleListItem weekDate(LocalDate weekDate) { this.weekDate = weekDate; return this; } @ApiModelProperty(example = "null", value = "The start week date for this schedule. Dates are represented as an ISO-8601 string. For example: yyyy-MM-dd") @JsonProperty("weekDate") public LocalDate getWeekDate() { return weekDate; } public void setWeekDate(LocalDate weekDate) { this.weekDate = weekDate; } /** * The number of weeks spanned by this schedule **/ public BuScheduleListItem weekCount(Integer weekCount) { this.weekCount = weekCount; return this; } @ApiModelProperty(example = "null", value = "The number of weeks spanned by this schedule") @JsonProperty("weekCount") public Integer getWeekCount() { return weekCount; } public void setWeekCount(Integer weekCount) { this.weekCount = weekCount; } /** * The description of this schedule **/ public BuScheduleListItem description(String description) { this.description = description; return this; } @ApiModelProperty(example = "null", value = "The description of this schedule") @JsonProperty("description") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } /** * Whether this schedule is published **/ public BuScheduleListItem published(Boolean published) { this.published = published; return this; } @ApiModelProperty(example = "null", value = "Whether this schedule is published") @JsonProperty("published") public Boolean getPublished() { return published; } public void setPublished(Boolean published) { this.published = published; } /** * The forecast used for this schedule, if applicable **/ public BuScheduleListItem shortTermForecast(BuShortTermForecastReference shortTermForecast) { this.shortTermForecast = shortTermForecast; return this; } @ApiModelProperty(example = "null", value = "The forecast used for this schedule, if applicable") @JsonProperty("shortTermForecast") public BuShortTermForecastReference getShortTermForecast() { return shortTermForecast; } public void setShortTermForecast(BuShortTermForecastReference shortTermForecast) { this.shortTermForecast = shortTermForecast; } /** * Generation result summary for this schedule, if applicable **/ public BuScheduleListItem generationResults(ScheduleGenerationResultSummary generationResults) { this.generationResults = generationResults; return this; } @ApiModelProperty(example = "null", value = "Generation result summary for this schedule, if applicable") @JsonProperty("generationResults") public ScheduleGenerationResultSummary getGenerationResults() { return generationResults; } public void setGenerationResults(ScheduleGenerationResultSummary generationResults) { this.generationResults = generationResults; } /** * Version metadata for this schedule **/ public BuScheduleListItem metadata(WfmVersionedEntityMetadata metadata) { this.metadata = metadata; return this; } @ApiModelProperty(example = "null", value = "Version metadata for this schedule") @JsonProperty("metadata") public WfmVersionedEntityMetadata getMetadata() { return metadata; } public void setMetadata(WfmVersionedEntityMetadata metadata) { this.metadata = metadata; } @ApiModelProperty(example = "null", value = "The URI for this object") @JsonProperty("selfUri") public String getSelfUri() { return selfUri; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BuScheduleListItem buScheduleListItem = (BuScheduleListItem) o; return Objects.equals(this.id, buScheduleListItem.id) && Objects.equals(this.weekDate, buScheduleListItem.weekDate) && Objects.equals(this.weekCount, buScheduleListItem.weekCount) && Objects.equals(this.description, buScheduleListItem.description) && Objects.equals(this.published, buScheduleListItem.published) && Objects.equals(this.shortTermForecast, buScheduleListItem.shortTermForecast) && Objects.equals(this.generationResults, buScheduleListItem.generationResults) && Objects.equals(this.metadata, buScheduleListItem.metadata) && Objects.equals(this.selfUri, buScheduleListItem.selfUri); } @Override public int hashCode() { return Objects.hash(id, weekDate, weekCount, description, published, shortTermForecast, generationResults, metadata, selfUri); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class BuScheduleListItem {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" weekDate: ").append(toIndentedString(weekDate)).append("\n"); sb.append(" weekCount: ").append(toIndentedString(weekCount)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" published: ").append(toIndentedString(published)).append("\n"); sb.append(" shortTermForecast: ").append(toIndentedString(shortTermForecast)).append("\n"); sb.append(" generationResults: ").append(toIndentedString(generationResults)).append("\n"); sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n"); sb.append(" selfUri: ").append(toIndentedString(selfUri)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
true
d2bb0bad951a21ab2ded5ef75189035710536b1b
Java
JeffWoo2019/aliyun-openapi-java-sdk
/aliyun-java-sdk-ecsops/src/main/java/com/aliyuncs/ecsops/transform/v20160401/OpsSlsDescribeDashBoardResponseUnmarshaller.java
UTF-8
2,612
1.796875
2
[ "Apache-2.0" ]
permissive
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.ecsops.transform.v20160401; import java.util.ArrayList; import java.util.List; import com.aliyuncs.ecsops.model.v20160401.OpsSlsDescribeDashBoardResponse; import com.aliyuncs.ecsops.model.v20160401.OpsSlsDescribeDashBoardResponse.DashBoards; import com.aliyuncs.transform.UnmarshallerContext; public class OpsSlsDescribeDashBoardResponseUnmarshaller { public static OpsSlsDescribeDashBoardResponse unmarshall(OpsSlsDescribeDashBoardResponse opsSlsDescribeDashBoardResponse, UnmarshallerContext _ctx) { opsSlsDescribeDashBoardResponse.setRequestId(_ctx.stringValue("OpsSlsDescribeDashBoardResponse.RequestId")); opsSlsDescribeDashBoardResponse.setMessage(_ctx.stringValue("OpsSlsDescribeDashBoardResponse.Message")); opsSlsDescribeDashBoardResponse.setCode(_ctx.stringValue("OpsSlsDescribeDashBoardResponse.Code")); opsSlsDescribeDashBoardResponse.setSuccess(_ctx.stringValue("OpsSlsDescribeDashBoardResponse.Success")); opsSlsDescribeDashBoardResponse.setPageSize(_ctx.longValue("OpsSlsDescribeDashBoardResponse.PageSize")); opsSlsDescribeDashBoardResponse.setPageNo(_ctx.longValue("OpsSlsDescribeDashBoardResponse.PageNo")); opsSlsDescribeDashBoardResponse.setTotal(_ctx.longValue("OpsSlsDescribeDashBoardResponse.Total")); List<DashBoards> data = new ArrayList<DashBoards>(); for (int i = 0; i < _ctx.lengthValue("OpsSlsDescribeDashBoardResponse.Data.Length"); i++) { DashBoards dashBoards = new DashBoards(); dashBoards.setDashboardName(_ctx.stringValue("OpsSlsDescribeDashBoardResponse.Data["+ i +"].DashboardName")); dashBoards.setDescription(_ctx.stringValue("OpsSlsDescribeDashBoardResponse.Data["+ i +"].Description")); dashBoards.setDisplayName(_ctx.stringValue("OpsSlsDescribeDashBoardResponse.Data["+ i +"].DisplayName")); dashBoards.setAttribute(_ctx.stringValue("OpsSlsDescribeDashBoardResponse.Data["+ i +"].Attribute")); data.add(dashBoards); } opsSlsDescribeDashBoardResponse.setData(data); return opsSlsDescribeDashBoardResponse; } }
true
f57bafc5ce8a0b245136fe97e722c50b08131efb
Java
josemiguesuarez/annotations-reader
/spooned/code/biblioteca/interfaz/PanelAcciones.java
UTF-8
12,769
2.453125
2
[]
no_license
package code.biblioteca.interfaz; @code.annotation.MyAnnotation(myAttribute = "Class") public class PanelAcciones extends javax.swing.JPanel implements java.awt.event.ActionListener , java.awt.event.MouseListener { private static final long serialVersionUID = 1L; private static final java.lang.String INSERTAR_USUARIO = "Insertar Usuario"; private static final java.lang.String ENTRAR = "Entrar"; private static final java.lang.String CANCELAR = "Cancelar"; private javax.swing.JLabel labelLogin; private javax.swing.JTextField textNombreUsuario; private javax.swing.JLabel labelContrasenia; private javax.swing.JPasswordField textoContrasenia; private javax.swing.JButton botonEntrar; private javax.swing.JLabel labelRegistrarse; private javax.swing.JLabel labelUsuarioNuevo; private javax.swing.JLabel labelContraseniaNueva; private javax.swing.JLabel labelNombre; private javax.swing.JTextField textoUsuarioNuevo; private javax.swing.JTextField textoNombreNuevo; private javax.swing.JPasswordField passwordNuevo; private javax.swing.JButton botonAceptar = null; private javax.swing.JButton botonCancelar = null; private code.biblioteca.interfaz.InterfazBiblioteca principal; public PanelAcciones(code.biblioteca.interfaz.InterfazBiblioteca nPrincipal) { principal = nPrincipal; java.awt.GridBagConstraints gridBagConstraints9 = new java.awt.GridBagConstraints(); gridBagConstraints9.gridx = 1; gridBagConstraints9.gridy = 7; java.awt.GridBagConstraints gridBagConstraints8 = new java.awt.GridBagConstraints(); gridBagConstraints8.gridx = 0; gridBagConstraints8.insets = new java.awt.Insets(0, 9, 0, 0); gridBagConstraints8.gridy = 7; java.awt.GridBagConstraints gridBagConstraints7 = new java.awt.GridBagConstraints(); gridBagConstraints7.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints7.gridy = 5; gridBagConstraints7.weightx = 1.0; gridBagConstraints7.gridx = 1; java.awt.GridBagConstraints gridBagConstraints6 = new java.awt.GridBagConstraints(); gridBagConstraints6.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints6.gridy = 6; gridBagConstraints6.weightx = 1.0; gridBagConstraints6.gridx = 1; java.awt.GridBagConstraints gridBagConstraints51 = new java.awt.GridBagConstraints(); gridBagConstraints51.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints51.gridy = 4; gridBagConstraints51.weightx = 1.0; gridBagConstraints51.gridx = 1; java.awt.GridBagConstraints gridBagConstraints41 = new java.awt.GridBagConstraints(); gridBagConstraints41.gridx = 0; gridBagConstraints41.gridy = 6; labelNombre = new javax.swing.JLabel(); labelNombre.setText("Nombre:"); labelNombre.setVisible(false); java.awt.GridBagConstraints gridBagConstraints22 = new java.awt.GridBagConstraints(); gridBagConstraints22.gridx = 0; gridBagConstraints22.gridy = 5; labelContraseniaNueva = new javax.swing.JLabel(); labelContraseniaNueva.setText("Contrase�a:"); labelContraseniaNueva.setVisible(false); java.awt.GridBagConstraints gridBagConstraints11 = new java.awt.GridBagConstraints(); gridBagConstraints11.gridx = 0; gridBagConstraints11.gridy = 4; labelUsuarioNuevo = new javax.swing.JLabel(); labelUsuarioNuevo.setText("Usuario:"); labelUsuarioNuevo.setVisible(false); java.awt.GridBagConstraints gridBagConstraints21 = new java.awt.GridBagConstraints(); gridBagConstraints21.gridx = 0; gridBagConstraints21.gridwidth = 2; gridBagConstraints21.fill = java.awt.GridBagConstraints.NONE; gridBagConstraints21.insets = new java.awt.Insets(0, 54, 40, 0); gridBagConstraints21.gridheight = 1; gridBagConstraints21.weightx = 0.0; gridBagConstraints21.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints21.gridy = 3; labelRegistrarse = new javax.swing.JLabel(); labelRegistrarse.setText("�Sin cuenta? Registrese"); labelRegistrarse.setFont(new java.awt.Font("Dialog", java.awt.Font.BOLD, 10)); labelRegistrarse.setForeground(java.awt.Color.blue); labelRegistrarse.addMouseListener(code.biblioteca.interfaz.PanelAcciones.this); java.awt.GridBagConstraints gridBagConstraints5 = new java.awt.GridBagConstraints(); gridBagConstraints5.gridx = 0; gridBagConstraints5.fill = java.awt.GridBagConstraints.NONE; gridBagConstraints5.gridwidth = 2; gridBagConstraints5.gridy = 2; java.awt.GridBagConstraints gridBagConstraints4 = new java.awt.GridBagConstraints(); gridBagConstraints4.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints4.gridy = 1; gridBagConstraints4.weightx = 1.0; gridBagConstraints4.ipadx = 0; gridBagConstraints4.insets = new java.awt.Insets(10, 10, 10, 10); gridBagConstraints4.gridx = 1; java.awt.GridBagConstraints gridBagConstraints2 = new java.awt.GridBagConstraints(); gridBagConstraints2.gridx = 0; gridBagConstraints2.insets = new java.awt.Insets(10, 10, 10, 0); gridBagConstraints2.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints2.gridy = 1; labelContrasenia = new javax.swing.JLabel(); labelContrasenia.setText("Contrase�a:"); java.awt.GridBagConstraints gridBagConstraints1 = new java.awt.GridBagConstraints(); gridBagConstraints1.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints1.gridy = 0; gridBagConstraints1.weightx = 1.0; gridBagConstraints1.insets = new java.awt.Insets(0, 10, 0, 10); gridBagConstraints1.gridx = 1; java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.gridy = 0; labelLogin = new javax.swing.JLabel(); labelLogin.setText("Usuario:"); setSize(214, 368); setLayout(new java.awt.GridBagLayout()); setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Login", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", java.awt.Font.BOLD, 12), new java.awt.Color(51, 51, 51))); setMaximumSize(new java.awt.Dimension(214, 368)); setBackground(new java.awt.Color(255, 255, 204)); setMinimumSize(new java.awt.Dimension(214, 358)); setPreferredSize(new java.awt.Dimension(214, 368)); code.biblioteca.interfaz.PanelAcciones.this.add(labelLogin, gridBagConstraints); textNombreUsuario = new javax.swing.JTextField(); code.biblioteca.interfaz.PanelAcciones.this.add(textNombreUsuario, gridBagConstraints1); code.biblioteca.interfaz.PanelAcciones.this.add(labelContrasenia, gridBagConstraints2); textoContrasenia = new javax.swing.JPasswordField(); code.biblioteca.interfaz.PanelAcciones.this.add(textoContrasenia, gridBagConstraints4); botonEntrar = new javax.swing.JButton(); botonEntrar.setText("Entrar"); botonEntrar.setActionCommand(code.biblioteca.interfaz.PanelAcciones.ENTRAR); botonEntrar.addActionListener(code.biblioteca.interfaz.PanelAcciones.this); add(botonEntrar, gridBagConstraints5); add(labelRegistrarse, gridBagConstraints21); add(labelUsuarioNuevo, gridBagConstraints11); add(labelContraseniaNueva, gridBagConstraints22); add(labelNombre, gridBagConstraints41); textoUsuarioNuevo = new javax.swing.JTextField(); textoUsuarioNuevo.setVisible(false); add(textoUsuarioNuevo, gridBagConstraints51); textoNombreNuevo = new javax.swing.JTextField(); textoNombreNuevo.setVisible(false); add(textoNombreNuevo, gridBagConstraints6); passwordNuevo = new javax.swing.JPasswordField(); passwordNuevo.setVisible(false); add(passwordNuevo, gridBagConstraints7); botonAceptar = new javax.swing.JButton(); botonAceptar.setText("Aceptar"); botonAceptar.setVisible(false); botonAceptar.addActionListener(code.biblioteca.interfaz.PanelAcciones.this); botonAceptar.setActionCommand(code.biblioteca.interfaz.PanelAcciones.INSERTAR_USUARIO); add(botonAceptar, gridBagConstraints8); botonCancelar = new javax.swing.JButton(); botonCancelar.setText("Cancelar"); botonCancelar.setVisible(false); botonCancelar.addActionListener(code.biblioteca.interfaz.PanelAcciones.this); botonCancelar.setActionCommand(code.biblioteca.interfaz.PanelAcciones.CANCELAR); add(botonCancelar, gridBagConstraints9); } public void actionPerformed(java.awt.event.ActionEvent e) { if (e.getActionCommand().equals(code.biblioteca.interfaz.PanelAcciones.INSERTAR_USUARIO)) { if (((textoUsuarioNuevo.getText().equals("")) || (passwordNuevo.getPassword().equals(""))) || (textoNombreNuevo.getText().equals(""))) javax.swing.JOptionPane.showMessageDialog(principal, "Ingrese todos los datos", "Error", javax.swing.JOptionPane.ERROR_MESSAGE); else try { principal.registrarUsuario(textoUsuarioNuevo.getText(), new java.lang.String(passwordNuevo.getPassword()), textoNombreNuevo.getText()); textNombreUsuario.setEnabled(true); textoContrasenia.setEnabled(true); textoNombreNuevo.setVisible(false); passwordNuevo.setVisible(false); textoUsuarioNuevo.setVisible(false); labelUsuarioNuevo.setVisible(false); labelContraseniaNueva.setVisible(false); labelNombre.setVisible(false); botonAceptar.setVisible(false); botonCancelar.setVisible(false); } catch (code.biblioteca.mundo.excepciones.UsuarioPreexistenteException e1) { javax.swing.JOptionPane.showMessageDialog(code.biblioteca.interfaz.PanelAcciones.this, e1.getMessage(), "Error", javax.swing.JOptionPane.INFORMATION_MESSAGE); } textoUsuarioNuevo.setText(""); passwordNuevo.setText(""); textoNombreNuevo.setText(""); } if (e.getActionCommand().equals(code.biblioteca.interfaz.PanelAcciones.ENTRAR)) { principal.autenticar(textNombreUsuario.getText(), new java.lang.String(textoContrasenia.getPassword())); textNombreUsuario.setText(""); textoContrasenia.setText(""); } if (e.getActionCommand().equals(code.biblioteca.interfaz.PanelAcciones.CANCELAR)) { textNombreUsuario.setEnabled(true); textoContrasenia.setEnabled(true); textoNombreNuevo.setVisible(false); passwordNuevo.setVisible(false); textoUsuarioNuevo.setVisible(false); labelUsuarioNuevo.setVisible(false); labelContraseniaNueva.setVisible(false); labelNombre.setVisible(false); botonAceptar.setVisible(false); botonCancelar.setVisible(false); textoUsuarioNuevo.setText(""); passwordNuevo.setText(""); textoNombreNuevo.setText(""); } } public void mouseEntered(java.awt.event.MouseEvent e) { labelRegistrarse.setFont(new java.awt.Font("Dialog", java.awt.Font.BOLD, 10)); labelRegistrarse.setText("<html><u>�Sin cuenta? Registrese</u></html>"); } public void mouseClicked(java.awt.event.MouseEvent e) { textNombreUsuario.setEnabled(false); textoContrasenia.setEnabled(false); textoNombreNuevo.setVisible(true); passwordNuevo.setVisible(true); textoUsuarioNuevo.setVisible(true); labelUsuarioNuevo.setVisible(true); labelContraseniaNueva.setVisible(true); labelNombre.setVisible(true); botonAceptar.setVisible(true); botonCancelar.setVisible(true); } public void mousePressed(java.awt.event.MouseEvent e) { } public void mouseReleased(java.awt.event.MouseEvent e) { } public void mouseExited(java.awt.event.MouseEvent e) { labelRegistrarse.setText("�Sin cuenta? Registrese"); } }
true
2454ea1fa1d1b5819610f04b919ab528618545ea
Java
RicardoBrancas/CRC_1
/java/ApproximateNeighbourhoodFunctionStats.java
UTF-8
3,176
2.640625
3
[]
no_license
/*- * Copyright (c) 2013, Pedro Rijo * Copyright (c) 2013, Alexandre P Francisco * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ import it.unimi.dsi.stat.Jackknife; import it.unimi.dsi.webgraph.algo.ApproximateNeighbourhoodFunctions; import it.unimi.dsi.webgraph.algo.NeighbourhoodFunction; import it.unimi.dsi.fastutil.objects.ObjectList; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import java.io.BufferedReader; import java.io.*; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; public class ApproximateNeighbourhoodFunctionStats { public static void main(String[] args) { ObjectList<double[]> anfs = new ObjectArrayList<double[]>(); for (int i = 0; i < args.length; i++) { LinkedList<String> values = new LinkedList<String>(); try { BufferedReader br = new BufferedReader(new FileReader(args[i])); String line = null; while ((line = br.readLine()) != null) values.add(line); } catch (IOException e) { System.err.println(e); } double[] anf = new double[values.size()]; Iterator<String> li = values.iterator(); int k = 0; while (li.hasNext()) { anf[k] = Double.parseDouble(li.next()); k++; } anfs.add(anf); } anfs = ApproximateNeighbourhoodFunctions.evenOut(anfs); Jackknife jack = Jackknife.compute(anfs, ApproximateNeighbourhoodFunctions.AVERAGE_DISTANCE); System.out.println("ADst:\t" + jack.estimate[0] + "\t(+/- " + jack.standardError[0] + ")"); jack = Jackknife.compute(anfs, ApproximateNeighbourhoodFunctions.EFFECTIVE_DIAMETER); System.out.println("EDmt:\t" + jack.estimate[0] + "\t(+/- " + jack.standardError[0] + ")"); jack = Jackknife.compute(anfs, ApproximateNeighbourhoodFunctions.HARMONIC_DIAMETER); System.out.println("HDmt:\t" + jack.estimate[0] + "\t(+/- " + jack.standardError[0] + ")"); jack = Jackknife.compute(anfs, ApproximateNeighbourhoodFunctions.SPID); System.out.println("SPID:\t" + jack.estimate[0] + "\t(+/- " + jack.standardError[0] + ")"); jack = Jackknife.compute(anfs, ApproximateNeighbourhoodFunctions.PMF); for (int i = 0; i < jack.estimate.length; i++) System.out.println("PMF " + i + " " + jack.estimate[i] + " " + jack.standardError[i]); jack = Jackknife.compute(anfs, ApproximateNeighbourhoodFunctions.CDF); for (int i = 0; i < jack.estimate.length; i++) System.out.println("CDF " + i + " " + jack.estimate[i] + " " + jack.standardError[i]); } }
true
be168a2757375d43c24f69ce098a933587c8fe4f
Java
rkalz/CS203
/Lab13/CS203_Lab13/src/linkedlistiterator/Main.java
UTF-8
782
3.53125
4
[]
no_license
package linkedlistiterator; import java.util.LinkedList; public class Main { public static void main(String[] args){ MyLinkedList myNumbers = new MyLinkedList(); ListIterator it = myNumbers.listIterator(); for(int i = 0; i < 10; i++){ it.add(new Integer(i)); } it = myNumbers.listIterator(); it.next(); it.remove(); it = myNumbers.listIterator(); while(it.hasNext()){ System.out.print(it.next() + " "); } System.out.println(); MyLinkedList myCharacters = new MyLinkedList(); it = myCharacters.listIterator(); for(int i = 0; i < 10; i++){ it.add(new String("a" + i)); } it = myCharacters.listIterator(); it.next(); it.remove(); it = myCharacters.listIterator(); while(it.hasNext()){ System.out.print(it.next() + " "); } } }
true
65a1e98a46c64649e264ffe2efa318ab64a12b31
Java
QueesQuees/Project-Human-resources
/HumanResources/src/ICalculator.java
UTF-8
92
2.21875
2
[]
no_license
//trừu tương 100%. public interface ICalculator { double calculateSalary(); }
true
b8df00761c30f986f8332cf559177c3b8085c6fa
Java
rystrauss/algorithms-and-data-structures
/core/src/com/rystrauss/collections/Collection.java
UTF-8
3,806
3.8125
4
[ "MIT" ]
permissive
package com.rystrauss.collections; import java.util.Iterator; /** * A collection represents a group of objects, known as its elements. Some collections allow duplicate elements * and others do not. Some are ordered and others unordered. * <p> * This interface is based on Java's Collection interface. * * @param <E> the type of elements in this collection * @author Ryan Strauss */ public interface Collection<E> extends Iterable<E> { /** * Ensures that this collection contains the specified element (optional operation). Returns true if this * collection changed as a result of the call. (Returns false if this collection does not permit duplicates * and already contains the specified element.) * * @param e element whose presence in this collection is to be ensured * @return true if this collection changed as a result of the call */ boolean add(E e); /** * Adds all of the elements in the specified collection to this collection. * * @param c collection containing elements to be added to this collection * @return true if this collection changed as a result of the call */ boolean addAll(Collection<? extends E> c); /** * Removes all of the elements from this collection. The collection will be empty after this method returns. */ void clear(); /** * Returns true if this collection contains the specified element. More formally, returns true if and only if this * collection contains at least one element e such that (o==null ? e==null : o.equals(e)). * * @param o element whose presence in this collection is to be tested * @return true if this collection contains the specified element */ boolean contains(Object o); /** * Returns true if this collection contains all of the elements in the specified collection. * * @param c collection to be checked for containment in this collection * @return true if this collection contains all of the elements in the specified collection */ boolean containsAll(Collection<?> c); /** * Returns true if this collection contains no elements. * * @return true if this collection contains no elements */ boolean isEmpty(); /** * Returns an iterator over the elements in this collection. There are no guarantees concerning the order in which * the elements are returned (unless this collection is an instance of some class that provides a guarantee). * * @return an Iterator over the elements in this collection */ Iterator<E> iterator(); /** * Removes a single instance of the specified element from this collection, if it is present. * More formally, removes an element e such that (o==null ? e==null : o.equals(e)), if this collection contains * one or more such elements. Returns true if this collection contained the specified element (or equivalently, * if this collection changed as a result of the call). * * @param o element to be removed from this collection, if present * @return true if an element was removed as a result of this call */ boolean remove(Object o); /** * Removes all of this collection's elements that are also contained in the specified collection. After this call * returns, this collection will contain no elements in common with the specified collection. * * @param c collection containing elements to be removed from this collection * @return true if this collection changed as a result of the call */ boolean removeAll(Collection<? extends E> c); /** * Returns the number of elements in this collection. * * @return the number of elements in this collection */ int size(); }
true
35d3534376afac3b47f9600fa74011c1d8f2c098
Java
sivajik/LeetCode
/src/leetcode/f7/medium/Prob167_TwoSum2InputArrayIsSorted.java
UTF-8
920
3.5
4
[]
no_license
package leetcode.f7.medium; import java.util.Arrays; public class Prob167_TwoSum2InputArrayIsSorted { public static void main(String[] args) { System.out.println(Arrays.toString(twoSum(new int[] { 2, 7, 11, 15 }, 9))); System.out.println(Arrays.toString(twoSum(new int[] { 5, 25, 75 }, 100))); } public static int[] twoSum(int[] numbers, int target) { for (int i = 0; i < numbers.length; i++) { int elem = numbers[i]; int lookFor = target - elem; int foundAt = contains(numbers, i + 1, numbers.length - 1, lookFor); if (foundAt != -1) { return new int[] { i + 1, foundAt + 1 }; } } return null; } private static int contains(int[] numbers, int l, int h, int lookFor) { while (l <= h) { int mid = l + (h - l) / 2; if (numbers[mid] == lookFor) { return mid; } if (numbers[mid] < lookFor) { l = mid + 1; } else { h = mid - 1; } } return -1; } }
true
641fda6abaec8e392d3be40ff0eff0f4344da00a
Java
MAQUANQUAN/prize
/ProtectAppDataWhenReset/PrizeFactoryDataProvider/src/com/android/factorydata/PhoneInfoHelper.java
UTF-8
3,483
2.390625
2
[]
no_license
package com.android.factorydata; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; public class PhoneInfoHelper extends SDSQLiteOpenHelper { private final static String DATABASE_NAME = "prize_factory_data"; private final static int DATABASE_VERSION = 1; private final static String TABLE_NAME = "prize_phone"; public final static String TIMER_NB = "prize_nb"; public final static String TASK_ATTRIBUTE = "prize_info"; public final static String TASK_CONTENT = "prize_data"; public PhoneInfoHelper (Context context) { // TODO Auto-generated constructor stub super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE " + TABLE_NAME + " (" + TIMER_NB + " INTEGER primary key autoincrement, " + TASK_ATTRIBUTE + " text, "+ TASK_CONTENT +" text);"; db.execSQL(sql); initDatabase(db); } public void initDatabase(SQLiteDatabase db){ ContentValues cv = new ContentValues(); cv.put(TASK_ATTRIBUTE,"imeiNo1"); cv.put(TASK_CONTENT, ""); db.insert(TABLE_NAME, null, cv); cv.put(TASK_ATTRIBUTE,"imeiNo2"); cv.put(TASK_CONTENT, ""); db.insert(TABLE_NAME, null, cv); cv.put(TASK_ATTRIBUTE,"snNo"); cv.put(TASK_CONTENT, "N00"); db.insert(TABLE_NAME, null, cv); cv.put(TASK_ATTRIBUTE,"pcbaResult"); cv.put(TASK_CONTENT, "0"); db.insert(TABLE_NAME, null, cv); cv.put(TASK_ATTRIBUTE,"mobileResult"); cv.put(TASK_CONTENT, "0"); db.insert(TABLE_NAME, null, cv); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql = "DROP TABLE IF EXISTS " + TABLE_NAME; db.execSQL(sql); onCreate(db); } public Cursor select() { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db .query(TABLE_NAME, null, null, null, null, null, null); return cursor; } public Cursor queryItem(String selectiion,String[] selectionArgs) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db .query(TABLE_NAME, null,selectiion,selectionArgs, null, null, null); //Cursor cursor = db.rawQuery("select from tasks_table where task_nb <?",whereValue); return cursor; } public long insert(String task_attribute , String task_content) { SQLiteDatabase db = this.getWritableDatabase(); /* ContentValues */ ContentValues cv = new ContentValues(); cv.put(TASK_ATTRIBUTE, task_attribute); cv.put(TASK_CONTENT, task_content); long row = db.insert(TABLE_NAME, null, cv); return row; } public void delete(int id) { SQLiteDatabase db = this.getWritableDatabase(); String where = TIMER_NB + " = ?"; String[] whereValue ={ Integer.toString(id) }; db.delete(TABLE_NAME, where, whereValue); } public int update(ContentValues values,String selection,String[] selectionArgs) { SQLiteDatabase db = this.getWritableDatabase(); int tureorfalse=db.update(TABLE_NAME, values, selection, selectionArgs); return tureorfalse; } public void clearFeedTable(){ String sql = "DELETE FROM " + TABLE_NAME +";"; SQLiteDatabase db = this.getWritableDatabase(); db.execSQL(sql); revertSeq(); } private void revertSeq() { String sql = "update sqlite_sequence set seq=0 where name='"+TABLE_NAME+"'"; SQLiteDatabase db = this.getWritableDatabase(); db.execSQL(sql); } }
true
796d49079a3d275c3a661529203bb639aec881c4
Java
eetpang/JavaLearning
/04-springboot/liaosx-sell/src/main/java/cn/freesaber/sell/controller/WechatController.java
UTF-8
3,203
2.078125
2
[]
no_license
package cn.freesaber.sell.controller; import cn.freesaber.sell.config.ProjectUrlConfig; import cn.freesaber.sell.enums.ResultEnum; import cn.freesaber.sell.exception.SellException; import me.chanjar.weixin.common.api.WxConsts; import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; @Controller @RequestMapping("/wechat") public class WechatController { private final Logger logger = LoggerFactory.getLogger(WechatController.class); @Autowired private WxMpService wxMpService; // 配置 @Autowired private WxMpService wxOpenService; @Autowired private ProjectUrlConfig projectUrlConfig; // 1.微信用户访问主页projectUrlConfig.getSell()后,判断是否有cookie,如果没有前端重定向到下面的授权连接 // projectUrlConfig.getSell()+"/wechat/authorize?returnUrl"+首页地址 // 2.用户点击链接后,会进入到下面的authorize @GetMapping("/authorize") public String authorize(@RequestParam("returnUrl") String returnUrl) throws UnsupportedEncodingException { String url = projectUrlConfig.getWechatMpAuthorize() + "/wechat/userInfo"; String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE, URLEncoder.encode(returnUrl, "UTF-8")); logger.info("【微信网页授权url】{}", redirectUrl); // 3.authorize方法构建一个微信授权redirectUrl,重定向到微信服务器接口 // 4.微信接口在接受请求后,获取点击操作的用户,将用户信息放入code,将接受参数放入state,然后进入下面的userInfo return "redirect:" + redirectUrl; } // 5.这里就可以拿到用户信息code,以及上面方法传入的参数returnUrl @GetMapping("/userInfo") public String userInfo(@RequestParam("code") String code, @RequestParam("state") String returnUrl) { WxMpOAuth2AccessToken wxMpOAuth2AccessToken; try { wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code); } catch (WxErrorException e) { logger.error("【微信网页授权】{}", e); throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(), e.getError().getErrorMsg()); } String openId = wxMpOAuth2AccessToken.getOpenId(); // 6.重定向到首页,带上openid,就能获取访问应用的用户 return "redirect:" + returnUrl + "?openid=" + openId; } @GetMapping("qrAuthorize") public String qrAuthorize(@RequestParam("returnUrl") String returnUrl) { return ""; } @GetMapping("qrUserInfo") public String qrUserInfo(@RequestParam("code") String code, @RequestParam("state") String returnUrl) { return ""; } }
true
9b5865f3b256649995a4487c77e092b24a629067
Java
MightyBOBcnc/planet-generator
/ch.obermuhlner.planetgen/src/main/java/ch/obermuhlner/planetgen/planet/texture/awt/BufferedImageTextureWriter.java
UTF-8
966
3.078125
3
[ "MIT" ]
permissive
package ch.obermuhlner.planetgen.planet.texture.awt; import ch.obermuhlner.planetgen.math.Color; import ch.obermuhlner.planetgen.planet.texture.TextureWriter; import java.awt.image.BufferedImage; public class BufferedImageTextureWriter implements TextureWriter<BufferedImage> { private final BufferedImage image; public BufferedImageTextureWriter(int textureWidth, int textureHeight) { image = new BufferedImage(textureWidth, textureHeight, BufferedImage.TYPE_INT_ARGB); } @Override public BufferedImage getTexture() { return image; } @Override public void setColor(int x, int y, Color color) { int[] pixel = new int[4]; pixel[0] = (int) (255 * color.getRed() + 0.5); pixel[1] = (int) (255 * color.getGreen() + 0.5); pixel[2] = (int) (255 * color.getBlue() + 0.5); pixel[3] = (int) (255 * color.getAlpha() + 0.5); image.getRaster().setPixel(x, y, pixel); } }
true
bb9d606cad034ab1e97218ffce15b956416da666
Java
lanshifu/FFmpegDemo
/src/main/java/io/reactivex/internal/operators/observable/by.java
UTF-8
3,871
1.976563
2
[]
no_license
package io.reactivex.internal.operators.observable; import defpackage.wh; import defpackage.xk; import io.reactivex.disposables.b; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.disposables.EmptyDisposable; import io.reactivex.k; import io.reactivex.r; import java.util.Iterator; /* compiled from: ObservableZipIterable */ public final class by<T, U, V> extends k<V> { final k<? extends T> a; final Iterable<U> b; final wh<? super T, ? super U, ? extends V> c; /* compiled from: ObservableZipIterable */ static final class a<T, U, V> implements b, r<T> { final r<? super V> a; final Iterator<U> b; final wh<? super T, ? super U, ? extends V> c; b d; boolean e; a(r<? super V> rVar, Iterator<U> it, wh<? super T, ? super U, ? extends V> whVar) { this.a = rVar; this.b = it; this.c = whVar; } public void onSubscribe(b bVar) { if (DisposableHelper.validate(this.d, bVar)) { this.d = bVar; this.a.onSubscribe(this); } } public void dispose() { this.d.dispose(); } public boolean isDisposed() { return this.d.isDisposed(); } public void onNext(T t) { if (!this.e) { try { try { this.a.onNext(io.reactivex.internal.functions.a.a(this.c.apply(t, io.reactivex.internal.functions.a.a(this.b.next(), "The iterator returned a null value")), "The zipper function returned a null value")); try { if (!this.b.hasNext()) { this.e = true; this.d.dispose(); this.a.onComplete(); } } catch (Throwable th) { io.reactivex.exceptions.a.b(th); a(th); } } catch (Throwable th2) { io.reactivex.exceptions.a.b(th2); a(th2); } } catch (Throwable th22) { io.reactivex.exceptions.a.b(th22); a(th22); } } } /* Access modifiers changed, original: 0000 */ public void a(Throwable th) { this.e = true; this.d.dispose(); this.a.onError(th); } public void onError(Throwable th) { if (this.e) { xk.a(th); return; } this.e = true; this.a.onError(th); } public void onComplete() { if (!this.e) { this.e = true; this.a.onComplete(); } } } public by(k<? extends T> kVar, Iterable<U> iterable, wh<? super T, ? super U, ? extends V> whVar) { this.a = kVar; this.b = iterable; this.c = whVar; } public void subscribeActual(r<? super V> rVar) { try { Iterator it = (Iterator) io.reactivex.internal.functions.a.a(this.b.iterator(), "The iterator returned by other is null"); try { if (it.hasNext()) { this.a.subscribe(new a(rVar, it, this.c)); } else { EmptyDisposable.complete((r) rVar); } } catch (Throwable th) { io.reactivex.exceptions.a.b(th); EmptyDisposable.error(th, (r) rVar); } } catch (Throwable th2) { io.reactivex.exceptions.a.b(th2); EmptyDisposable.error(th2, (r) rVar); } } }
true
7b6b6b3359128e62d04b46d495a5a1fef4db1fcc
Java
shoxrux-javaDev/app-secondWarehouseProject
/src/main/java/uz/spring/appanotherwarehouseproject/Dto/OutputDto.java
UTF-8
422
1.757813
2
[]
no_license
package uz.spring.appanotherwarehouseproject.Dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.time.LocalDate; @Data @AllArgsConstructor @NoArgsConstructor public class OutputDto { private LocalDate date; private Integer warehouseId; private Integer currencyId; private String factureNumber; private String code; private Integer clientId; }
true
cfd536f31e2a1ca484c14acb0056ff632bc09228
Java
icnNubby/PryanikiTest
/app/src/main/java/ru/nubby/pryanikitest/Injection.java
UTF-8
822
1.851563
2
[]
no_license
package ru.nubby.pryanikitest; import ru.nubby.pryanikitest.data.remote.RemoteApi; import ru.nubby.pryanikitest.data.remote.RemoteRepository; import ru.nubby.pryanikitest.data.Repository; import ru.nubby.pryanikitest.data.test.TestRepository; import ru.nubby.pryanikitest.util.BaseSchedulerProvider; import ru.nubby.pryanikitest.util.SchedulerProvider; /** * Enables injection of mock implementations for * {@link Repository} at compile time. */ public class Injection { public static Repository provideRepository() { return new RemoteRepository(RemoteApi.getInstance()); } public static BaseSchedulerProvider provideSchedulerProvider() { return SchedulerProvider.getInstance(); } public static Repository provideTestRepository() { return new TestRepository(); } }
true
dbfdc04c93d51b32a2d64ba63c0d2691c53e6f46
Java
jewelcse/rabbitmq-saga-demo
/service-account/src/main/java/app/services/BudgetService.java
UTF-8
1,088
2.78125
3
[]
no_license
package app.services; import javax.security.auth.login.AccountNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import app.entities.Account; import app.exceptions.InsufficientBudgetException; import app.repositories.AccountRepository; @Service public class BudgetService { @Autowired AccountRepository accountRepo; public boolean hasEnoughBudget(int userId, double cost) throws AccountNotFoundException { if (!accountRepo.existsByUserId(userId)) throw new AccountNotFoundException(); Account account = accountRepo.findByUserId(userId); return account.getDeposit() >= cost; } public void withdrawn(int userId, double amount) throws AccountNotFoundException, InsufficientBudgetException { if (!hasEnoughBudget(userId, amount)) throw new InsufficientBudgetException(); // make payment here Account account = accountRepo.findByUserId(userId); double subtraction = account.getDeposit() - amount; account.setDeposit(subtraction); accountRepo.save(account); } }
true
4cd7a7fc5e1073f1029deec7e683f5f96166399a
Java
networker02/TaxiAppProject
/app/src/main/java/com/handycartaxi/taxiappproject/webserviceconection/Utilities.java
UTF-8
1,450
2.84375
3
[]
no_license
package com.handycartaxi.taxiappproject.webserviceconection; /** * Created by Joan on 04-May-15. */ public class Utilities { public static String combinePaths(String... paths) { String absolutePath = ""; for(String path : paths) { if (absolutePath.endsWith("/") && path.startsWith("/")) { absolutePath += path.substring(0,path.length() - 1); } else if(!absolutePath.endsWith("/") && !path.startsWith("/") && !absolutePath.equals("")) { absolutePath += "/" + path; } else{ absolutePath += path; } } return absolutePath; } public static String appendParametersToURL(String url, DictionaryImp<String, String> params) { if(!url.endsWith("?") && params != null && !params.isEmpty()) url += "?"; // if the url contains parameters // and the user pass more parameters, then append // the dictionary paramerers if(params != null && !params.isEmpty()) { /*if(!url.contains("&")) { url += "&"; }*/ for(PairKeyValue<String,String> element : params) { url += element.getKey() + "=" + element.getValue() + "&"; } url = url.substring(0,url.length() - 1); } return url; } }
true
1282789f3ccc47db3d8774635b0ad847286203f6
Java
ccyzml/WowGame
/app/src/main/java/com/nju/meanlay/wowgame/GameData/Ability/BaseAbility.java
UTF-8
152
1.664063
2
[]
no_license
package com.nju.meanlay.wowgame.GameData.Ability; import java.io.Serializable; public abstract class BaseAbility implements Ability, Serializable { }
true
a5d3fdd99260675417f3af1c629c0f7be43ef924
Java
tbeckett1123/Learning
/College/mscc/java/Stnd.java
UTF-8
1,303
3.328125
3
[]
no_license
import javax.swing.JOptionPane; public class Stnd { public static void out(String outMessage){ JOptionPane.showMessageDialog(null, outMessage, "standard output dialog box", JOptionPane.INFORMATION_MESSAGE); } public static String getStr(String outMessage) { String temp; for(;;) { temp = JOptionPane.showInputDialog(null, outMessage, "standard input dialog box", JOptionPane.QUESTION_MESSAGE); //checking to see if temp has something in it if(temp == null) out("YOU MUST ENTER SOMETHING TO PROGRESS ANY FURTHER."); else if(temp.length() <= 0) out("YOU MUST ENTER SOMETHING TO PROGRESS ANY FURTHER."); else break; } return temp; } public static byte getB(String passMessage){ return Byte.parseByte(getStr(passMessage)); } public static int getI(String passMessage){ return Integer.parseInt(getStr(passMessage)); } public static short getS(String passMessage){ return Short.parseShort(getStr(passMessage)); } public static long getL(String passMessage){ return Long.parseLong(getStr(passMessage)); } public static float getF(String passMessage){ return Float.parseFloat(getStr(passMessage)); } public static double getD(String passMessage){ return Double.parseDouble(getStr(passMessage)); } }
true
5b81e1964ae442b41f6896f810b1df9120841de7
Java
qqhappy/mesh-omc
/WEB/com.xinwei.minas.server/src/com/xinwei/minas/server/mcbts/facade/oamManage/McBtsOnlineTerminalListFacadeImpl.java
GB18030
1,169
2.03125
2
[]
no_license
package com.xinwei.minas.server.mcbts.facade.oamManage; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.List; import com.xinwei.minas.mcbts.core.facade.oamManage.McBtsOnlineTerminalListFacade; import com.xinwei.minas.mcbts.core.model.common.ActiveUserInfo; import com.xinwei.minas.server.mcbts.service.oamManage.McBtsOnlineTerminalListService; import com.xinwei.minas.server.platform.AppContext; /** * BTSնб_ʵ * * @author fangping * */ public class McBtsOnlineTerminalListFacadeImpl extends UnicastRemoteObject implements McBtsOnlineTerminalListFacade{ private McBtsOnlineTerminalListService service; public McBtsOnlineTerminalListFacadeImpl() throws RemoteException { super(); service = AppContext.getCtx().getBean(McBtsOnlineTerminalListService.class); } @Override public List<ActiveUserInfo> queryOnlineTerminalListFromNE(Long moId) throws RemoteException, Exception { return service.queryOnlineTerminalListFromNE(moId); } @Override public List<ActiveUserInfo> queryOnlineTerminalListFromDB(long moId) throws RemoteException, Exception { return null; } }
true
fc29adc86dd6a4b17697d9f7154277a4a7b3d7d8
Java
flybo/mindeeper
/app/src/main/java/com/bob/flyboymvp/ui/fragment/ContactsFragment.java
UTF-8
2,811
2.03125
2
[]
no_license
package com.bob.flyboymvp.ui.fragment; import android.support.v4.app.Fragment; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.bob.flyboymvp.R; import com.bob.flyboymvp.ui.activity.MainActivity; import com.bob.flyboymvp.ui.adapter.TabFragmentPagerAdapter; import com.bob.flyboymvp.ui.base.BaseFragment; import com.bob.flyboymvp.ui.fragment.contacts.PersonalFragment; import com.bob.flyboymvp.ui.fragment.contacts.UnitFragment; import com.bob.flyboymvp.ui.presenter.ContactsFgPter; import com.bob.flyboymvp.ui.view.IContactsFgView; import com.bob.flyboymvp.util.UIUtils; import com.bob.flyboymvp.widget.NoScrollViewPager; import java.util.ArrayList; import java.util.List; import butterknife.BindView; /** * 名录模块 * Created on 2018/5/30. */ public class ContactsFragment extends BaseFragment<IContactsFgView,ContactsFgPter> implements IContactsFgView{ @BindView(R.id.vp_cts) NoScrollViewPager mVpCts; @BindView(R.id.ll_topbar) LinearLayout layoutToolbar; @BindView(R.id.main) LinearLayout layoutMain; @BindView(R.id.lay_a) LinearLayout layA; @BindView(R.id.lay_b) LinearLayout layB; @BindView(R.id.lay_c) LinearLayout layC; @BindView(R.id.lay_d) LinearLayout layD; @BindView(R.id.lay_e) LinearLayout layE; private List<LinearLayout> mToolList=new ArrayList<>(); private List<Fragment> mFragmentList = new ArrayList<>(); @Override public void initView(View rootView) { mToolList.add(layA); mToolList.add(layB); mToolList.add(layC); mToolList.add(layD); mToolList.add(layE); mFragmentList.add(new PersonalFragment()); mFragmentList.add(new UnitFragment()); mVpCts.setAdapter(new TabFragmentPagerAdapter(getChildFragmentManager(), mFragmentList)); mVpCts.setNoScroll(true); UIUtils.initViews(layoutMain); changeTit(4); } @Override public void initListener() { super.initListener(); layA.setOnClickListener(v -> changeTit(0)); layB.setOnClickListener(v -> changeTit(1)); layC.setOnClickListener(v -> changeTit(2)); layD.setOnClickListener(v -> changeTit(3)); layE.setOnClickListener(v -> changeTit(4)); } @Override protected ContactsFgPter createPresenter() { return new ContactsFgPter((MainActivity)getActivity()); } @Override protected int provideContentViewId() { return R.layout.fragment_contacts; } public void changeTit(int index){ int i=0; for (LinearLayout view : mToolList) { view.setBackgroundColor(UIUtils.getColor(i==index?"#50ffffff":"#00000000")); i++; } mVpCts.setCurrentItem(index); } }
true
8425431315c8a41e906f7333fe64b1e7d0d9b3ea
Java
leelingco/opendental
/java/OpenDental/OneCalendarDay.java
UTF-8
5,002
2.6875
3
[]
no_license
// // Translated by CS2J (http://www.cs2j.com): 2/15/2016 8:00:27 PM // package OpenDental; import OpenDental.OneCalendarDay; /* //horizontal lines: for(int i=1;i<=RowCount;i++) { g.DrawLine(LinePen,0,HeaderHeight+DayHeadHeight+RowHeight*i,Width,HeaderHeight+DayHeadHeight+RowHeight*i); } //vertical lines for(int i=0;i<=ColCount;i++) { g.DrawLine(LinePen,ColWidth*i,HeaderHeight,ColWidth*i,Height-HeaderHeight); }*/ /*private void ContrCalendar_MouseDown(object sender,System.Windows.Forms.MouseEventArgs e) { //Graphics g=this.CreateGraphics(); int OldSelected=SelectedDay; for(int i=1;i<=DaysInMonth;i++) { if(e.X >= ListDays[i].Bounds.X && e.X <= ListDays[i].Bounds.X+ListDays[i].Bounds.Width && e.Y >= ListDays[i].Bounds.Y && e.Y <= ListDays[i].Bounds.Y+ListDays[i].Bounds.Height) { SelectedDay=ListDays[i].Date.Day; selectedDate=ListDays[i].Date; ListDays[i].IsSelected=true; ListDays[OldSelected].IsSelected=false; /* //unpainting selected and repainting Windows color if(List[OldSelected].color.Equals(Color.Empty)){ grfx.FillRectangle(new SolidBrush(DayOpenColor),List[OldSelected].Rec); grfx.DrawString(List[OldSelected].Day.ToString() ,FontText,Brushes.Black,List[OldSelected].xPos,List[OldSelected].yPos); DrawRowsOfText(OldSelected,grfx); } else{ grfx.FillRectangle(new SolidBrush(List[OldSelected].color),List[OldSelected].Rec); grfx.DrawString(List[OldSelected].Day.ToString() ,FontText,Brushes.Black,List[OldSelected].xPos,List[OldSelected].yPos); DrawRowsOfText(OldSelected,grfx); } //painting Selected grfx.FillRectangle(new SolidBrush(SelectedDayColor),List[i].Rec); grfx.DrawString(List[i].Day.ToString() ,FontText,Brushes.Black,List[i].xPos,List[i].yPos); DrawRowsOfText(i,grfx); DrawMonthGrid(grfx); MarkTodayDate(grfx); } } //g.Dispose(); }*/ //<summary></summary> //public void ChangeColor(int day,Color color) { // ListDays[day].color=color; //} //<summary></summary> //public void AddText(int day,string s) { /*if(ListDays[day].NumRowsText!=MaxRowsText) { for(int i=0;i<ListDays[day].RowsOfText.Count;i++) { if(ListDays[day].RowsOfText[i]=="" || ListDays[day].RowsOfText[i]==null) { ListDays[day].RowsOfText[i]=s; ListDays[day].NumRowsText++; return; } } }*/ //else{ //MessageBox.Show(Lan.g(this,"Too Many Rows of Text. Can Only Have "+MaxRowsText.ToString())); //} //} /*//<summary></summary> public void ResetList() { for(int i=1;i<ListDays.Count;i++) { ListDays[i].color=Color.Empty; ListDays[i].RowsOfText=new List<string>(); ListDays[i].NumRowsText=0; } }*/ /*private void butPrevious_Click(object sender,System.EventArgs e) { //Graphics g=this.CreateGraphics(); selectedDate=selectedDate.AddMonths(-1); //DisplayDaysInMonth(g); OnChangeMonth(e); //grfx.Dispose(); this.Invalidate(); //this.OnPaint(new PaintEventArgs(this.CreateGraphics(),this.ClientRectangle)); } private void butNext_Click(object sender,System.EventArgs e) { //Graphics grfx=this.CreateGraphics(); selectedDate=selectedDate.AddMonths(1); //DisplayDaysInMonth(grfx); //grfx.Dispose(); OnChangeMonth(e); this.Invalidate(); //this.OnPaint(new PaintEventArgs(this.CreateGraphics(),this.ClientRectangle)); }*/ /* ///<summary></summary> public delegate void CellEventHandler(object sender,CellEventArgs e); ///<summary></summary> public delegate void EventHandler(object sender,EventArgs e); ///<summary></summary> public event CellEventHandler CellClicked; ///<summary></summary> public event CellEventHandler CellDoubleClicked; ///<summary></summary> public event EventHandler ChangeMonth; ///<summary></summary> protected virtual void OnCellClicked(CellEventArgs e) { if(CellClicked !=null) { CellClicked(this,e); } } ///<summary></summary> protected virtual void OnCellDoubleClicked(CellEventArgs e) { if(CellDoubleClicked !=null) { CellDoubleClicked(this,e); } } ///<summary></summary> protected virtual void OnChangeMonth(EventArgs e) { if(ChangeMonth !=null) { ChangeMonth(this,e); } }*/ //Object keeps track of drawing coords,text, and date. each day is stored in List to draw each month /** * */ public class OneCalendarDay { /** * */ public Rectangle Bounds = new Rectangle(); /** * */ public DateTime Date = new DateTime(); /** * */ public Color color = new Color(); //<summary></summary> //public bool IsSelected; /** * */ public String RowsOfText = new String(); //<summary></summary> //public int NumRowsText; //public OneCalendarDay() { // RowsOfText=new List<string>(); //} public OneCalendarDay copy() throws Exception { return (OneCalendarDay)this.MemberwiseClone(); } }
true
1bef79218ad06efe0c3dda374cb605f5a9bfd482
Java
Goldiriath/Goldiriath
/src/main/java/net/goldiriath/plugin/player/info/Info.java
UTF-8
264
1.75
2
[]
no_license
package net.goldiriath.plugin.player.info; import net.goldiriath.plugin.player.AbstractAttachement; import net.goldiriath.plugin.player.PlayerData; public class Info extends AbstractAttachement { public Info(PlayerData data) { super(data); } }
true
25d28b4b9095bc86652f54e8585e0c73f3b03536
Java
zhongxingyu/Seer
/Diff-Raw-Data/33/33_831ef3e33bf40a9003b7bc855fe399c0e2135a7a/DrugListActivity/33_831ef3e33bf40a9003b7bc855fe399c0e2135a7a_DrugListActivity_t.java
UTF-8
18,134
1.578125
2
[]
no_license
/** * Copyright (C) 2011 Joseph Lehner <joseph.c.lehner@gmail.com> * * This file is part of RxDroid. * * RxDroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * RxDroid 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 RxDroid. If not, see <http://www.gnu.org/licenses/>. * * */ package at.caspase.rxdroid; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import android.app.Activity; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.SpannableString; import android.text.format.DateFormat; import android.text.style.UnderlineSpan; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.MotionEvent; import android.view.View; import android.view.View.OnLongClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.Window; import android.view.animation.AnimationUtils; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.ViewSwitcher; import android.widget.ViewSwitcher.ViewFactory; import at.caspase.rxdroid.db.Database; import at.caspase.rxdroid.db.Drug; import at.caspase.rxdroid.db.Intake; import at.caspase.rxdroid.util.CollectionUtils; import at.caspase.rxdroid.util.Constants; import at.caspase.rxdroid.util.DateTime; public class DrugListActivity extends Activity implements OnLongClickListener, OnDateSetListener, OnSharedPreferenceChangeListener, ViewFactory, OnGestureListener, OnTouchListener { public static final String TAG = DrugListActivity.class.getName(); public static final int MENU_ADD = 0; public static final int MENU_PREFERENCES = 1; public static final int MENU_TOGGLE_FILTERING = 2; public static final int CMENU_TOGGLE_INTAKE = 0; //public static final int CMENU_CHANGE_DOSE = 1; public static final int CMENU_EDIT_DRUG = 2; //public static final int CMENU_SHOW_SUPPLY_STATUS = 3; public static final int CMENU_IGNORE_DOSE = 4; public static final String EXTRA_DAY = "day"; public static final String EXTRA_STARTED_BY_NOTIFICATION = "started_from_notification"; private static final int TAG_ID = R.id.tag_drug_id; private LayoutInflater mInflater; private ViewSwitcher mViewSwitcher; private TextView mMessageOverlay; private GestureDetector mGestureDetector; private TextView mTextDate; private Calendar mDate; private boolean mShowingAll = false; private SharedPreferences mSharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.drug_list); mInflater = LayoutInflater.from(this); mViewSwitcher = (ViewSwitcher) findViewById(R.id.drug_list_view_flipper); mMessageOverlay = (TextView) findViewById(android.R.id.empty); mTextDate = (TextView) findViewById(R.id.med_list_footer); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); mSharedPreferences.registerOnSharedPreferenceChangeListener(this); GlobalContext.set(getApplicationContext()); Database.load(); // must be called before mViewSwitcher.setFactory! mViewSwitcher.setFactory(this); mTextDate.setOnLongClickListener(this); findViewById(R.id.view_switcher_container).setOnTouchListener(this); mGestureDetector = new GestureDetector(this, this); } @Override protected void onResume() { super.onResume(); /*final Intent intent = getIntent(); final String action = intent.getAction(); if(Intent.ACTION_VIEW.equals(action) || Intent.ACTION_MAIN.equals(action)) { Serializable date = intent.getSerializableExtra(EXTRA_DAY); if(!(date instanceof Calendar)) { if(date != null) Log.e(TAG, "onResume: EXTRA_DAY set, but wrong type"); shiftDate(0); } else setDate((Calendar) date); } else shiftDate(0);*/ Log.d(TAG, "onResume"); shiftDate(0); startNotificationService(); } @Override protected void onDestroy() { super.onDestroy(); mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_TOGGLE_FILTERING, 0, R.string._title_toggle_filtering).setIcon(android.R.drawable.ic_menu_view); menu.add(0, MENU_ADD, 0, R.string._title_add).setIcon(android.R.drawable.ic_menu_add); menu.add(0, MENU_PREFERENCES, 0, R.string._title_preferences).setIcon(android.R.drawable.ic_menu_preferences); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case MENU_ADD: { Intent intent = new Intent(Intent.ACTION_INSERT); intent.setClass(this, DrugEditActivity.class); startActivity(intent); return true; } case MENU_PREFERENCES: { Intent intent = new Intent(); intent.setClass(this, PreferencesActivity.class); startActivity(intent); return true; } case MENU_TOGGLE_FILTERING: { mShowingAll = !mShowingAll; final ListView currentView = (ListView) mViewSwitcher.getCurrentView(); final DrugAdapter adapter = (DrugAdapter) currentView.getAdapter(); if(mShowingAll) adapter.setFilter(null); else adapter.setFilter(new DrugFilter()); return true; } } return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { final DoseView doseView = (DoseView) v; final Drug drug = Database.getDrug(doseView.getDrugId()); final int doseTime = doseView.getDoseTime(); //menu.setHeaderIcon(android.R.drawable.ic_menu_agenda); menu.setHeaderTitle(drug.getName()); final boolean wasDoseTaken = doseView.wasDoseTaken(); final int toggleIntakeMessageId; if(wasDoseTaken) toggleIntakeMessageId = R.string._title_mark_not_taken; else toggleIntakeMessageId = R.string._title_mark_taken; ////////////////////////////////////////////////// menu.add(0, CMENU_TOGGLE_INTAKE, 0, toggleIntakeMessageId).setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if(!wasDoseTaken) doseView.performClick(); else { Fraction dose = new Fraction(); for(Intake intake : Database.findIntakes(drug, mDate, doseTime)) { dose.add(intake.getDose()); Database.delete(intake); } Log.d(TAG, "onMenuItemClick: adding " + dose + " to current supply of " + drug.getName()); drug.setCurrentSupply(drug.getCurrentSupply().plus(dose)); Database.update(drug); } return true; } }); ///////////////////////////////////////////////// //menu.add(0, CMENU_CHANGE_DOSE, 0, R.string._title_change_dose); final Intent editIntent = new Intent(this, DrugEditActivity.class); editIntent.setAction(Intent.ACTION_EDIT); editIntent.putExtra(DrugEditActivity.EXTRA_DRUG, drug); menu.add(0, CMENU_EDIT_DRUG, 0, R.string._title_edit_drug).setIntent(editIntent); //menu.add(0, CMENU_SHOW_SUPPLY_STATUS, 0, "Show supply status"); if(!wasDoseTaken) { menu.add(0, CMENU_IGNORE_DOSE, 0, R.string._title_ignore_dose) .setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Database.create(new Intake(drug, mDate.getTime(), doseTime)); return true; } } ); } } public void onNavigationClick(View view) { setProgressBarIndeterminateVisibility(true); switch(view.getId()) { case R.id.med_list_footer: shiftDate(0); break; case R.id.med_list_prev: shiftDate(-1); break; case R.id.med_list_next: shiftDate(+1); break; default: Log.w(TAG, "onNavigationClick: unhandled view id " + view.getId()); } setProgressBarIndeterminateVisibility(false); } public void onDrugNameClick(View view) { Intent intent = new Intent(Intent.ACTION_EDIT); intent.setClass(this, DrugEditActivity.class); Drug drug = Database.getDrug((Integer) view.getTag(TAG_ID)); intent.putExtra(DrugEditActivity.EXTRA_DRUG, (Serializable) drug); startActivityForResult(intent, 0); } @Override public boolean onLongClick(View view) { if(view.getId() == R.id.med_list_footer) { final int year = mDate.get(Calendar.YEAR); final int month = mDate.get(Calendar.MONTH); final int day = mDate.get(Calendar.DAY_OF_MONTH); DatePickerDialog dialog = new DatePickerDialog(this, this, year, month, day); dialog.show(); return true; } return false; } @Override public void onDateSet(DatePicker view, int year, int month, int day) { setDate(DateTime.date(year, month, day)); } public void onDoseClick(final View view) { final DoseView v = (DoseView) view; final Drug drug = Database.getDrug(v.getDrugId()); final int doseTime = v.getDoseTime(); IntakeDialog dialog = new IntakeDialog(this, drug, doseTime, mDate.getTime()); dialog.show(); } @Override public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { // causes the ListView to be refreshed setDate(mDate); } @Override public View makeView() { ListView lv = new ListView(this); return lv; } ///////////// @Override public boolean onDown(MotionEvent e) { return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { final float begX = e1 != null ? e1.getX() : 0.0f; final float endX = e2 != null ? e2.getX() : 0.0f; final float diffX = Math.abs(begX - endX); Log.d(TAG, "onFling: diffX=" + diffX + ", velocityX=" + velocityX); // TODO determine whether these are suitable values for this purpose if(diffX > 50 && Math.abs(velocityX) > 800) { shiftDate(begX < endX ? -1 : 1); return true; } return false; } @Override public void onLongPress(MotionEvent e) {} @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public void onShowPress(MotionEvent e) {} @Override public boolean onSingleTapUp(MotionEvent e) { return false; } ///////////// @Override public boolean onTouch(View v, MotionEvent event) { super.onTouchEvent(event); return mGestureDetector.onTouchEvent(event); } ///////////// private void startNotificationService() { Intent serviceIntent = new Intent(); serviceIntent.setClass(this, NotificationService.class); startService(serviceIntent); } private void setDate(Calendar newDate) { setOrShiftDate(0, newDate); } private void shiftDate(int shiftBy) { setOrShiftDate(shiftBy, null); } // shift to previous (-1) or next(1) date. passing 0 // will reset to specified date, or current date // if newDate is -1 private void setOrShiftDate(int shiftBy, Calendar newDate) { setProgressBarIndeterminateVisibility(true); if(shiftBy == 0) { if(newDate == null) mDate = Settings.instance().getActiveDate(); else if(mDate != newDate) mDate = newDate; mViewSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in)); mViewSwitcher.setOutAnimation(null); } else { mDate.add(Calendar.DAY_OF_MONTH, shiftBy); if(shiftBy == 1) { mViewSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_in_right)); mViewSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.slide_out_left)); } else if(shiftBy == -1) { mViewSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left)); mViewSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right)); } else throw new IllegalArgumentException(); } updateNextView(); mViewSwitcher.showNext(); if(Database.getDrugs().isEmpty()) { mMessageOverlay.setText(getString(R.string._msg_empty_list_text, getString(R.string._title_add))); mMessageOverlay.setVisibility(View.VISIBLE); } else if(((ListView) mViewSwitcher.getCurrentView()).getAdapter().getCount() == 0) { mMessageOverlay.setText(getString(R.string._msg_no_doses_on_this_day)); mMessageOverlay.setVisibility(View.VISIBLE); } else mMessageOverlay.setVisibility(View.GONE); final SpannableString dateString = new SpannableString(DateFormat.getDateFormat(this).format(mDate.getTime())); if(mDate.equals(DateTime.today())) dateString.setSpan(new UnderlineSpan(), 0, dateString.length(), 0); mTextDate.setText(dateString); //setTitle(getString(R.string.app_name) + " - " + dateString.toString()); // update the intent so our Activity is restarted with the last opened date setIntent(getIntent().putExtra(EXTRA_DAY, (Serializable) mDate)); setProgressBarIndeterminateVisibility(false); } private void updateNextView() { final ListView nextView = (ListView) mViewSwitcher.getNextView(); final DrugAdapter adapter = new DrugAdapter(this, R.layout.dose_view, Database.getDrugs(), mDate); adapter.setFilter(mShowingAll ? null : new DrugFilter()); nextView.setAdapter(adapter); nextView.setOnTouchListener(this); } private class DrugAdapter extends ArrayAdapter<Drug> { private ArrayList<Drug> mAllItems; private ArrayList<Drug> mItems; private Calendar mAdapterDate; public DrugAdapter(Context context, int viewResId, List<Drug> items, Calendar date) { super(context, viewResId, items); mAllItems = new ArrayList<Drug>(items); mAdapterDate = (Calendar) date.clone(); } public void setFilter(CollectionUtils.Filter<Drug> filter) { if(filter != null) mItems = (ArrayList<Drug>) CollectionUtils.filter(mAllItems, filter); else { //mItems = (ArrayList<Drug>) CollectionUtils.copy(mAllItems); mItems = mAllItems; } notifyDataSetChanged(); } @Override public Drug getItem(int position) { return mItems.get(position); } @Override public int getPosition(Drug drug) { return mItems.indexOf(drug); } @Override public int getCount() { return mItems.size(); } @Override public View getView(int position, View v, ViewGroup parent) { // This function currently is the bottleneck when switching between dates, causing // laggish animations if there are more than 3 or 4 drugs (i.e. 12-16 DoseViews) // // All measurements were done using an HTC Desire running Cyanogenmod 7! final DoseViewHolder holder; if(v == null) { v = mInflater.inflate(R.layout.drug_view2, null); holder = new DoseViewHolder(); holder.name = (TextView) v.findViewById(R.id.drug_name); holder.icon = (ImageView) v.findViewById(R.id.drug_icon); for(int i = 0; i != holder.doseViews.length; ++i) { final int doseViewId = Constants.DOSE_VIEW_IDS[i]; holder.doseViews[i] = (DoseView) v.findViewById(doseViewId); registerForContextMenu(holder.doseViews[i]); } v.setTag(holder); } else holder = (DoseViewHolder) v.getTag(); final Drug drug = getItem(position); holder.name.setText(drug.getName()); holder.name.setTag(TAG_ID, drug.getId()); holder.icon.setImageResource(drug.getFormResourceId()); // This part often takes more than 90% of the time spent in this function, // being rougly 0.025s when hasInfo returns false, and 0.008s when it // returns true. // // Assuming that, in the worst case, all calls to hasInfo return false, this // means that this part alone will, in total, take more than 100ms to complete // for 4 drugs. for(DoseView doseView : holder.doseViews) { if(!doseView.hasInfo(mAdapterDate, drug)) doseView.setInfo(mAdapterDate, drug); } return v; } } private class DrugFilter implements CollectionUtils.Filter<Drug> { @Override public boolean matches(Drug drug) { final boolean showDoseless = mSharedPreferences.getBoolean("show_doseless", true); final boolean showInactive = mSharedPreferences.getBoolean("show_inactive", true); if(!showDoseless && mDate != null) { if(!drug.hasDoseOnDate(mDate)) return !Database.findIntakes(drug, mDate, null).isEmpty(); } else if(!showInactive && !drug.isActive()) return false; return true; } } private static class DoseViewHolder { TextView name; ImageView icon; DoseView[] doseViews = new DoseView[4]; } }
true
83b2002395baa32a251d7c09258dc3539333a7b4
Java
fllaryora/IUATesisMSDED
/Bootstrap/src/main/java/ar/com/cron/Bootstrap/OSHelper.java
UTF-8
2,969
2.90625
3
[]
no_license
package ar.com.cron.Bootstrap; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import com.mongodb.DBObject; import ar.com.cron.Bootstrap.constants.ProjectsFiels; import ar.com.cron.Bootstrap.constants.ProjectsValues; public class OSHelper { /** * Busca en el sistema operativo si * hay un proceso corriendo con el nombre MPI * Linux guarda el nombre del proceso en el archivo de texto: /proc/XXXX/comm * @return */ public static boolean isBotqueueRunning(){ final File folder = new File("/proc"); for (final File fileEntry : folder.listFiles()) { if (fileEntry.isDirectory() && isNum(fileEntry.getName())) { File procName = new File("/proc/" + fileEntry.getName() + "/comm"); StringBuffer fileData = new StringBuffer(); char[] buf = new char[1024]; int numRead=0; try { BufferedReader reader = new BufferedReader( new FileReader(procName)); while((numRead=reader.read(buf)) != -1){ String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); } reader.close(); } catch (IOException e) { e.printStackTrace(); } if(fileData.toString().contains(ProjectsValues.BOTQUEUE_PROGRAM)) return true; } } return false; } /** * Funcion auxiliar para saber si es un numero * @param value * @return */ private static boolean isNum(String value){ try{ Integer.parseInt(value); return true; } catch(NumberFormatException nfe){ return false; } } /** * Busca el texto que esta en el archivo de salida del botQueue y lo borra tras extraerlo * Si no hay noda dentro o no existe el archivo trae null o vacio */ public static String getOutput() { File newTextFile = new File(ProjectsValues.BOTQUEUE_OUTPUT_FILE); if(newTextFile.exists()){ StringBuffer fileData = new StringBuffer(); char[] buf = new char[1024]; int numRead=0; try { BufferedReader reader = new BufferedReader( new FileReader(newTextFile)); while((numRead=reader.read(buf)) != -1){ String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); } reader.close(); } catch (IOException e) { e.printStackTrace(); } newTextFile.deleteOnExit(); return fileData.toString(); } else return null; } /** * Escribe en el archivo de entra de de botqueue, * el json toRead * @param toRead * @return */ public static boolean writeFile(DBObject toRead ){ try { File newTextFile = new File(ProjectsValues.BOTQUEUE_INPUT_FILE); if(newTextFile.exists())newTextFile.delete(); FileWriter fw = new FileWriter(newTextFile); fw.write(toRead.get(ProjectsFiels.INPUT_FIELD).toString()); fw.close(); } catch (IOException iox) { iox.printStackTrace(); return false; } return true; } }
true
7595da784f1b0a883d6002e26f06d28c6c347236
Java
evikadar/Dog-shelter-back-end
/src/main/java/com/codecool/dogshelter/repository/ShelterRepository.java
UTF-8
699
2.109375
2
[]
no_license
package com.codecool.dogshelter.repository; import com.codecool.dogshelter.model.shelter.Shelter; import com.codecool.dogshelter.model.shelter.ShelterDetails; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import javax.transaction.Transactional; import java.util.List; public interface ShelterRepository extends JpaRepository<Shelter, Long> { @Query("SELECT s FROM Shelter s where s.id = :shelter_id") List<ShelterDetails> findByShelterId(@Param("shelter_id") Long id); Shelter getById(Long id); }
true
a367294492bbc9f842b7375ec97c8b89415eb070
Java
cgy529387306/Schedule
/app/src/main/java/com/android/mb/schedule/base/BaseMvpActivity.java
UTF-8
1,902
2.15625
2
[]
no_license
package com.android.mb.schedule.base; import android.content.DialogInterface; import android.content.DialogInterface.OnKeyListener; import android.os.Bundle; import android.view.KeyEvent; import com.android.mb.schedule.utils.Helper; import com.android.mb.schedule.utils.ProgressDialogHelper; import com.android.mb.schedule.utils.ToastUtils; /** * @Description * @Created by cgy on 2017/7/19 * @Version v1.0 */ public abstract class BaseMvpActivity<P extends Presenter<V>,V extends BaseMvpView> extends BaseActivity implements BaseMvpView{ protected P mPresenter; @Override protected void onCreate(Bundle savedInstanceState) { mPresenter = createPresenter(); mPresenter.attachView((V)this); super.onCreate(savedInstanceState); } protected abstract P createPresenter(); @Override protected void onStart() { super.onStart(); } @Override protected void onDestroy() { mPresenter.detachView(); ToastUtils.setView(null); super.onDestroy(); } @Override public void back() { finish(); } @Override public void showProgressDialog(String message) { ProgressDialogHelper.showProgressDialog(this, Helper.isEmpty(message)?"加载中...":message); } @Override public void dismissProgressDialog() { if (isFinishing()) { return; } ProgressDialogHelper.dismissProgressDialog(); } /** * add a keylistener for progress dialog */ private OnKeyListener onKeyListener = new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { dismissProgressDialog(); } return false; } }; }
true
7cccdffbbf3d3c878e30fead576dd6fb8c0bcf85
Java
sandeshds/VehicleSurvey
/src/main/java/com/sandesh/constants/TimeConstants.java
UTF-8
416
2.25
2
[]
no_license
package com.sandesh.constants; public class TimeConstants { public static final int HOURS_IN_A_DAY = 24; public static final int MINUTES_IN_HOUR = 60; public static final int SECONDS_IN_A_MINUTE = 60; public static final int MILLISECONDS_IN_A_SECOND = 1000; public static final int MAX_MILLISECONDS_IN_A_DAY = HOURS_IN_A_DAY * MINUTES_IN_HOUR * SECONDS_IN_A_MINUTE * MILLISECONDS_IN_A_SECOND; }
true
d346ea1b39a1f689d7586256ee43a56dc39148a8
Java
791837060/java-sanguosha
/src/org/dizem/sanguosha/model/card/equipment/EquipmentCard.java
UTF-8
2,232
2.734375
3
[]
no_license
package org.dizem.sanguosha.model.card.equipment; import org.dizem.sanguosha.model.card.AbstractCard; import org.dizem.sanguosha.model.card.ICard; public class EquipmentCard extends AbstractCard { public static final int TYPE_HORSE_CARD_MINUS = 3; public static final int TYPE_HORSE_CARD_PLUS = 2; public static final int TYPE_ARMOR_CARD = 1; public static final int TYPE_WEAPON_CARD = 0; private int cardType; private int range; public boolean isSelectable() { return name.startsWith("丈八蛇矛") || name.startsWith("雌雄双股剑") || name.startsWith("寒冰剑"); } public EquipmentCard(String pattern, String number, String name, String description, String filename) { super(pattern, number, name, description, filename); } public EquipmentCard(String pattern, String number, String name, String description, String filename, int cardType) { this(pattern, number, name, description, filename); this.cardType = cardType; } public EquipmentCard(String pattern, String number, String name, String description, String filename, int cardType, int range) { this(pattern, number, name, description, filename, cardType); this.range = range; } public static EquipmentCard create(String pattern, String number, String name, String description, String filename, String tag) { if (tag.equals("h1")) { return new EquipmentCard(pattern, number, name + "(+1)", description, filename, TYPE_HORSE_CARD_PLUS); } else if (tag.equals("h-1")) { return new EquipmentCard(pattern, number, name + "(-1)", description, filename, TYPE_HORSE_CARD_MINUS); } else if (tag.startsWith("w")) { int range = Integer.parseInt(tag.substring(1, tag.length())); return new EquipmentCard(pattern, number, name + "(+" + range + ")", description, filename, TYPE_WEAPON_CARD, range); } else { return new EquipmentCard(pattern, number, name, description, filename, TYPE_ARMOR_CARD); } } public int getCardType() { return cardType; } public int getRange() { return range; } public int getCategory() { return ICard.CATEGORY_EQUIPMENT; } }
true
eb7f4dd6020cd0cfae7d17490ea239ffb5be2879
Java
parth12/ProgrammingClubDAIICT
/source/src/com/umeng/fb/audio/b.java
UTF-8
3,765
1.835938
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.umeng.fb.audio; import android.media.AudioRecord; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class b { class a implements Runnable { final b a; public void run() { if (b.a(a) != null) { b.b(a); } } a() { a = b.this; super(); } } private static String e; private static String f; private final String a = com/umeng/fb/audio/b.getName(); private int b; private AudioRecord c; private boolean d; private long g; public b() { b = 0; d = false; } static AudioRecord a(b b1) { return b1.c; } static void b(b b1) { b1.e(); } private boolean d() { boolean flag = true; b = AudioRecord.getMinBufferSize(16000, 16, 2) * 2; if (-2 == b) { flag = false; } else { c = new AudioRecord(1, 16000, 16, 2, b); if (c.getState() != 1) { return false; } } return flag; } private void e() { Object obj; byte abyte0[]; if (c == null) { return; } abyte0 = new byte[b]; try { obj = new File(e); if (((File) (obj)).exists()) { ((File) (obj)).delete(); } obj = new FileOutputStream(((File) (obj))); } // Misplaced declaration of an exception variable catch (Object obj) { ((Exception) (obj)).printStackTrace(); obj = null; } c.startRecording(); _L3: if (d && -3 != c.read(abyte0, 0, b)) goto _L2; else goto _L1 _L1: a(); try { ((FileOutputStream) (obj)).close(); return; } // Misplaced declaration of an exception variable catch (Object obj) { ((IOException) (obj)).printStackTrace(); } return; _L2: ((FileOutputStream) (obj)).write(abyte0); g = g + (long)b; goto _L3 IOException ioexception; ioexception; ioexception.printStackTrace(); goto _L1 } protected int a() { this; JVM INSTR monitorenter ; d = false; if (c == null) goto _L2; else goto _L1 _L1: int i = c.getRecordingState(); if (1 != i) goto _L4; else goto _L3 _L3: i = -1; _L6: this; JVM INSTR monitorexit ; return i; _L4: c.stop(); c.release(); c = null; _L2: i = b; if (true) goto _L6; else goto _L5 _L5: Exception exception; exception; throw exception; } protected boolean a(String s, String s1) { this; JVM INSTR monitorenter ; boolean flag; e = s; f = s1; flag = d(); if (!flag) { break MISSING_BLOCK_LABEL_47; } d = true; g = 0L; (new Thread(new a())).start(); this; JVM INSTR monitorexit ; return flag; s; throw s; } protected boolean b() { boolean flag = true; if (c.getRecordingState() == 1) { flag = false; } return flag; } public long c() { return g / 16000L / 2L; } }
true
1f1b39a95c48baef31f0f978a0daa06875ba050f
Java
SuperZle/-
/LX713/src/XianCengTest.java
UTF-8
685
2.390625
2
[]
no_license
import DanLi.EHan; import DanLi.LanHan; /** * current user 张++ * 2020/7/13 0013 * 19:49 * 2020 */ public class XianCengTest implements Runnable{ private int i=100; private Object object=new Object(); @Override public void run() { while (true){ try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (EHan.fun()){ if (i>0){ i--; System.out.println(Thread.currentThread().getName()+"成功购买一张票,还剩 "+i+"张"); } } } } }
true
ba8b1f4c1897b12382a9b1e8100de36f5841dd6a
Java
ErickGuillen17/ProyectoDesarrolloWeb
/src/main/java/model/Sla.java
UTF-8
817
2.34375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; /** * * @author Alejandro */ public class Sla { private String idSla; private Severidad laSeveridad; private Urgencia laUrgencia; private String duracion; public String getIdSla() { return idSla; } public void setIdSla(String idSla) { this.idSla = idSla; } public String getDuracion() { return duracion; } public void setDuracion(String duracion) { this.duracion = duracion; } public Severidad getLaSeveridad() { return laSeveridad; } public Urgencia getLaUrgencia() { return laUrgencia; } }
true
dcf551fee7d4180b0ee1589ce175ee6eb03545b5
Java
satyac11/DSA
/Patterns/SlidingWindow/LongestSubstringwithKDistinctCharacters.java
UTF-8
1,373
3.765625
4
[]
no_license
package Patterns.SlidingWindow; import java.util.HashMap; import java.util.Map; public class LongestSubstringwithKDistinctCharacters { public static int longestSubString(String string, int k){ int start=0,longestStringLength=0; Map<Character,Integer> map = new HashMap<>(); for(int end=0;end<string.length();end++){ Character chr = string.charAt(end); map.put(chr,map.getOrDefault(chr,0)+1); while(map.size()>k){ int length = end-start; if(longestStringLength<length) longestStringLength = length; Character firstChar = string.charAt(start); if(map.get(firstChar)==1) map.remove(firstChar); else map.put(firstChar,map.get(firstChar)-1); start++; } } return longestStringLength; } public static void main(String[] args) { System.out.println("The longest substring with no more than k distinct characters is: "+longestSubString("araaci",2)); System.out.println("The longest substring with no more than k distinct characters is: "+longestSubString("araaci",1)); System.out.println("The longest substring with no more than k distinct characters is: "+longestSubString("cbbebi",3)); } }
true
9085180a94bdb49c3de793eaf1dddc1dbbd58b9a
Java
roymithun/JavaWork_2015
/src/com/peto/datastructures/stack/SortStack.java
UTF-8
1,171
3.734375
4
[]
no_license
package com.peto.datastructures.stack; import java.util.Stack; public class SortStack { public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); stack.push(2); stack.push(5); stack.push(3); stack.push(1); stack.push(8); stack.push(9); System.out.println(stack); System.out.println(sort(stack)); // System.out.println(sort1(stack)); } protected static Stack<Integer> sort(Stack<Integer> stack) { Stack<Integer> temp = new Stack<>(); if (stack.isEmpty()) return stack; temp.push(stack.pop()); while (!stack.isEmpty()) { int sTop = stack.pop(); if (sTop < temp.peek()) temp.push(sTop); else { while (!temp.isEmpty() && temp.peek() < sTop) { stack.push(temp.pop()); } temp.push(sTop); } } return temp; } public static Stack<Integer> sort1(Stack<Integer>stack){ Stack<Integer>temp=new Stack<Integer>(); if(stack.isEmpty()) return stack; temp.push(stack.pop()); while(!stack.isEmpty()){ int val=stack.pop(); while(!temp.isEmpty()){ if(temp.peek()<val) stack.push(temp.pop()); else break; } temp.push(val); } return temp; } }
true
c27c923fa46c4606f9aba975750efbf46980b064
Java
NecoHorne/HomeTribe
/app/src/main/java/com/necohorne/hometribe/Activities/Fragments/AboutFragment.java
UTF-8
2,894
2.203125
2
[]
no_license
package com.necohorne.hometribe.Activities.Fragments; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.TextView; import com.necohorne.hometribe.R; import java.io.IOException; import java.io.InputStream; /** * Created by necoh on 2018/03/20. */ public class AboutFragment extends Fragment { private static final String TAG = "AboutFragment"; private View mView; private Context mContext; private TextView versionNum; private TextView link; private TextView facebookLink; private WebView mWebView; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mView = inflater.inflate( R.layout.fragment_about, container, false); mContext = getActivity(); versionNum = (TextView) mView.findViewById( R.id.about_version_num ); link = (TextView) mView.findViewById( R.id.about_link); facebookLink = (TextView) mView.findViewById( R.id.about_follow_link); mWebView = (WebView) mView.findViewById( R.id.about_webview); try { PackageInfo pInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0); String version = pInfo.versionName; versionNum.setText(version); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } link.setText(Html.fromHtml("<a href=\"https://www.necohorne.com/hometribe\">hometribe</a>")); link.setMovementMethod(LinkMovementMethod.getInstance()); facebookLink.setText(Html.fromHtml( "<a href=\"https://www.facebook.com/hometribeapp/\">Facebook</a>")); facebookLink.setMovementMethod(LinkMovementMethod.getInstance()); String mData = getStringFromAssets( "Acknowledgements.html", mContext ); mWebView.loadDataWithBaseURL("file///android_asset/",mData, "text/html", "utf-8", null ); return mView; } public static String getStringFromAssets(String name, Context p_context){ try{ InputStream is = p_context.getAssets().open(name); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); String bufferString = new String(buffer); return bufferString; }catch (IOException e){ e.printStackTrace(); } return null; } }
true
9014fb67e5683888cd3a1f0c0235d3c6db929afa
Java
mercieau/projet2015
/src/Aeroport.java
UTF-8
5,053
3.0625
3
[]
no_license
/** * @author Natacha, Aurélie * @version 1.1 */ import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Scanner; public class Aeroport { private ArrayList<Point> listePoint; private ArrayList<Line> listeLine; private ArrayList<Runway> listeRunway; private String name; public Coord getMin() { return min; } public void setMin(Coord min) { this.min = min; } public Coord getMax() { return max; } public void setMax(Coord max) { this.max = max; } private Coord min = new Coord(0,0); private Coord max = new Coord(0,0); public String getName() { return name; } public void setName(String name) { this.name = name; } public ArrayList<Point> getListePoint() { return listePoint; } public void setListePoint(ArrayList<Point> listePoint) { this.listePoint = listePoint; } public ArrayList<Line> getListeLine() { return listeLine; } public void setListeLine(ArrayList<Line> listeLine) { this.listeLine = listeLine; } public ArrayList<Runway> getListeRunway() { return listeRunway; } public void setListeRunway(ArrayList<Runway> listeRunway) { this.listeRunway = listeRunway; } public Aeroport() { listePoint = new ArrayList<Point>(); listeLine = new ArrayList<Line>(); listeRunway = new ArrayList<Runway>(); } public void chargerTexte(String ficname) { Scanner scan = null; try { scan = new Scanner(new FileReader(ficname)); scan.useDelimiter("\n"); name = scan.next(); //Extraction du nom de l'aéroport listePoint.clear(); while(scan.hasNext()) { Scanner pt = new Scanner(scan.next()); pt.useDelimiter(" "); String element = pt.next(); /* Si la ligne de texte correspond à un point */ if(element.equals("P")) { String name = pt.next(); int type = pt.nextInt(); String coordonnees[]; coordonnees = pt.next().split(","); int x = Integer.parseInt(coordonnees[0]); int y = Integer.parseInt(coordonnees[1]); y = -y; if (x>max.getX()) max.setX(x); if (y>max.getY()) max.setY(y); if (x<min.getX()) min.setX(x); if (y<min.getY()) min.setY(y); listePoint.add(new Point(name, type, new Coord(x,y))); } /* Si la ligne de texte correspond à une ligne */ if(element.equals("L")) { ArrayList<Coord> listeCoord = new ArrayList<Coord>(); String name = pt.next(); int speedlimit = pt.nextInt(); String category = pt.next(); String direction = pt.next(); Scanner pl = new Scanner(pt.next()); pl.useDelimiter(";"); //pl = Point Line while(pl.hasNext()) //tant qu'on trouve des points on les ajoute à la liste { String coordonnees[]; coordonnees = pl.next().split(","); int x = Integer.parseInt(coordonnees[0]); int y = Integer.parseInt(coordonnees[1]); y = -y; if (x>max.getX()) max.setX(x); if (y>max.getY()) max.setY(y); if (x<min.getX()) min.setX(x); if (y<min.getY()) min.setY(y); listeCoord.add(new Coord(x,y)); } listeLine.add(new Line(name, speedlimit, category, direction, listeCoord)); } /* Si la ligne de texte correspond à un runway */ if(element.equals("R")) { String name = pt.next(); String QFU[] = new String[2]; String QFU1 = pt.next(); String QFU2 = pt.next(); QFU[0] = QFU1; QFU[1] = QFU2; String coordonnees[]; coordonnees = pt.next().split(";"); String cd[]; cd = coordonnees[0].split(","); int cdX = Integer.parseInt(cd[0],10); int cdY = Integer.parseInt(cd[1],10); cdY = -cdY; Coord coordDebut = new Coord(cdX, cdY); String cf[]; cf = coordonnees[1].split(","); int cfX = Integer.parseInt(cf[0],10); int cfY = Integer.parseInt(cf[1],10); cfY = -cfY; Coord coordFin = new Coord(cfX, cfY); if (cdX>max.getX()) max.setX(cdX); if (cdY>max.getY()) max.setY(cdY); if (cdX<min.getX()) min.setX(cdX); if (cdY<min.getY()) min.setY(cdY); if (cfX>max.getX()) max.setX(cfX); if (cfY>max.getY()) max.setY(cfY); if (cfX<min.getX()) min.setX(cfX); if (cfY<min.getY()) min.setY(cfY); ArrayList<Point> listePoint = new ArrayList<Point>(); Scanner pr = new Scanner(pt.next()); pr.useDelimiter(";"); while(pr.hasNext()) //tant qu'on trouve des points on les ajoute à la liste { listePoint.add(new Point(pr.next(), 0, new Coord(0, 0))); } listeRunway.add(new Runway(name, QFU, coordDebut, coordFin, listePoint)); } } } catch(FileNotFoundException e1) { e1.printStackTrace(); } /** Partie Test: Affichage dans la console **/ System.out.println(name); for(int i=0;i<listePoint.size();i++) { listePoint.get(i).affichePoint(); } for(int i=0;i<listeLine.size();i++) { listeLine.get(i).afficheLine(); } for(int i=0;i<listeRunway.size();i++) { listeRunway.get(i).afficheRunway(); } } }
true
b4cddb34de5d0f9ed4b7570d6cc508754f8e8fc7
Java
jayden123456/xiaoaimei
/StudioProjects/miaoying/app/src/main/java/com/yidan/xiaoaimei/presenter/EvaluatePresenter.java
UTF-8
1,961
1.992188
2
[]
no_license
package com.yidan.xiaoaimei.presenter; import com.yidan.xiaoaimei.contract.EvaluateContract; import com.yidan.xiaoaimei.http.base.OnHttpCallBack; import com.yidan.xiaoaimei.model.CommonEmptyInfo; import com.yidan.xiaoaimei.model.detail.EvaluateInfo; import com.yidan.xiaoaimei.model.detail.EvaluateModel; /** * 评价presenter * Created by jaydenma on 2017/7/17. */ public class EvaluatePresenter implements EvaluateContract.IEvaluatePresenter { private EvaluateContract.IEvaluateView mEvaluateView; private EvaluateContract.IEvaluateModel mEvaluateModel; public EvaluatePresenter(EvaluateContract.IEvaluateView mEvaluateView) { this.mEvaluateView = mEvaluateView; mEvaluateModel = new EvaluateModel(); } @Override public void getEvaluate() { mEvaluateView.showProgress(); mEvaluateModel.getEvaluate(new OnHttpCallBack<EvaluateInfo>() { @Override public void onSuccessful(EvaluateInfo evaluateInfo) { mEvaluateView.hideProgress(); mEvaluateView.showEvaluate(evaluateInfo); } @Override public void onFaild(String errorMsg) { mEvaluateView.hideProgress(); mEvaluateView.showError(errorMsg); } }); } @Override public void evaluate() { mEvaluateView.showProgress(); mEvaluateModel.evaluate(mEvaluateView.getToken(), mEvaluateView.getEvaId(), mEvaluateView.getUid(), new OnHttpCallBack<CommonEmptyInfo>() { @Override public void onSuccessful(CommonEmptyInfo commonEmptyInfo) { mEvaluateView.hideProgress(); mEvaluateView.showInfo("提交成功"); } @Override public void onFaild(String errorMsg) { mEvaluateView.hideProgress(); mEvaluateView.showError(errorMsg); } }); } }
true
7cae60dd2844c69484ae41708cc1b2fcc3e82e44
Java
Spole0168/pay_ssh
/CommonModules/frameworkimpl/server/main/com/ibs/common/module/frameworkimpl/data/excel/ExcelImporter.java
UTF-8
16,400
1.84375
2
[]
no_license
package com.ibs.common.module.frameworkimpl.data.excel; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.TimeZone; import jxl.Cell; import jxl.CellType; import jxl.DateCell; import jxl.Sheet; import jxl.Workbook; import jxl.WorkbookSettings; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.util.CycleDetectionStrategy; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.io.IOUtils; import org.dom4j.Document; import org.dom4j.io.SAXReader; import org.springframework.util.NumberUtils; import com.ibs.common.module.frameworkimpl.data.BaseImporter; import com.ibs.common.module.frameworkimpl.data.biz.IImporterBiz; import com.ibs.common.module.frameworkimpl.data.domain.ImportData; import com.ibs.common.module.frameworkimpl.data.domain.ImportInfo; import com.ibs.common.module.frameworkimpl.data.excel.setting.ExcelSetting; import com.ibs.common.module.frameworkimpl.data.excel.setting.ExcelSettingColumn; import com.ibs.common.module.frameworkimpl.data.excel.setting.ExcelSettingHelper; import com.ibs.common.module.frameworkimpl.data.handling.ImportDataHandling; import com.ibs.common.module.frameworkimpl.data.handling.ImportDataPreviewHandling; import com.ibs.common.module.frameworkimpl.file.domain.FilePersistence; import com.ibs.portal.framework.server.exception.BizException; import com.ibs.portal.framework.server.interceptor.support.JsonDateValueProcessor; import com.ibs.portal.framework.util.DateUtils; import com.ibs.portal.framework.util.RandomUtils; import com.ibs.portal.framework.util.StringUtils; /** * Excel 导入类 * @author * $Id: ExporterFactory.java 39293 2011-05-30 08:45:11Z $ */ public class ExcelImporter extends BaseImporter { public static String EXCEL_NEXT_ACTION = "excel.nextAction"; private Map<Class<?>, ExcelSetting> mappings = new HashMap<Class<?>, ExcelSetting>(); private IImporterBiz importerBiz; public void setImporterBiz(IImporterBiz importerBiz) { this.importerBiz = importerBiz; } public ExcelImporter() { try { SAXReader reader = new SAXReader(); Document document = reader.read(this.getClass().getResourceAsStream("/excel.xml")); List<ExcelSetting> settings = ExcelSettingHelper.parseExcelSettings(document); for(ExcelSetting setting : settings) { mappings.put(Class.forName(setting.getClassName()), setting); } } catch (Exception e) { logger.error("no excel.xml"); } } // ************************* public methods ************************* // @SuppressWarnings("unchecked") @Override public <E> String importFile(Class<E> clz, File file, Map<String, String> params) { logger.trace("entering importer..."); if (mappings == null) throw new BizException("excel配置信息加载失败!"); String importId = null; Date now = new Date(Calendar.getInstance().getTimeInMillis()); // 读取配置信息 ExcelSetting setting = mappings.get(clz); List<E> list = null; ImportDataHandling<E> handling = null; // 读取excel Workbook book = null; try { File newFile = fillNewFile(file); WorkbookSettings workbookSettings = new WorkbookSettings(); workbookSettings.setEncoding("ISO-8859-1"); // 关键代码,解决中文乱码 book = Workbook.getWorkbook(newFile, workbookSettings); Sheet sheet = book.getSheet(0); // 生成两个对象 FilePersistence filePersistence = fillFilePersistence(newFile, now); ImportInfo importInfo = fillImportInfo(setting, now, filePersistence.getId(), params); // 获取handling对象 Object obj = ExcelSettingHelper.getImportDataHanler(setting.getHandleClass()); // if ( !ImportDataPreviewHandling.class.isAssignableFrom()) if (!(obj instanceof ImportDataHandling)) { throw new BizException("handleClass 必须是ImportDataHandling的子类"); } handling = (ImportDataHandling<E>) obj; // 不做动态列选择 long time1 = System.nanoTime()/1000000; list = readExcel(clz, sheet, setting); long time2 = System.nanoTime()/1000000; // 不用预览,不保存数据 importId = importerBiz.saveImportData(filePersistence, importInfo, null); long time3 = System.nanoTime()/1000000; logger.info("解析Excel时间:" + (time2 - time1)); logger.info("导入数据库时间:" + (time3 - time2)); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (book != null) book.close(); } // 同线程中处理导入数据 handling.handleDatas(list, params); return importId; } @Override public <E> String importFilePreview(Class<E> clz, File file, Map<String, String> params) { logger.trace("entering importer..."); if (mappings == null) throw new BizException("excel配置信息加载失败!"); String importId = null; Date now = new Date(Calendar.getInstance().getTimeInMillis()); // 读取配置信息 ExcelSetting setting = mappings.get(clz); // 读取excel Workbook book = null; try { File newFile = fillNewFile(file); WorkbookSettings workbookSettings = new WorkbookSettings(); workbookSettings.setEncoding("ISO-8859-1"); // 关键代码,解决中文乱码 book = Workbook.getWorkbook(newFile, workbookSettings); Sheet sheet = book.getSheet(0); // 生成两个对象 FilePersistence filePersistence = fillFilePersistence(newFile, now); ImportInfo importInfo = fillImportInfo(setting, now, filePersistence.getId(), params); List<ImportData> datas = null; if (setting.isDefaultConfig()) { long time1 = System.nanoTime()/1000000; datas = readExcelPreview(clz, sheet, setting, params); long time2 = System.nanoTime()/1000000; importId = importerBiz.saveImportData(filePersistence, importInfo, datas); long time3 = System.nanoTime()/1000000; logger.info("解析Excel时间:" + (time2 - time1)); logger.info("导入数据库时间:" + (time3 - time2)); } else { // 预读取数据,并在界面上由用户选择列 } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (book != null) book.close(); } return importId; } // ************************* private methods ************************* // private <E> List<E> readExcel(Class<E> clz, Sheet sheet, ExcelSetting setting) throws Exception { Map<Integer, ExcelSettingColumn> columns = setting.getColumns(); int row = sheet.getRows(); int column = sheet.getColumns(); List<ImportData> datas = new ArrayList<ImportData>(column); List<ImportData> successDatas = new ArrayList<ImportData>(column); List<E> es = new ArrayList<E>(column); List<E> successEs = new ArrayList<E>(column); // 一行一行读Excel数据 for (int i = setting.getStartRow(); i < row; i++) { // 处理一行数据 E e = clz.newInstance(); Cell[] cells = sheet.getRow(i); ImportData data = readRow(e, columns, cells); data.setRowNo(Long.valueOf(i)); if (data.getIsSuccess()) { // 通过配置校验 successDatas.add(data); successEs.add(e); } // logger.debug(ToStringBuilder.reflectionToString(data)); datas.add(data); es.add(e); } // 校验数据 callback // handling.checkData(successEs, successDatas); return es; } @SuppressWarnings("unchecked") private <E> List<ImportData> readExcelPreview(Class<E> clz, Sheet sheet, ExcelSetting setting, Map<String, String> params) throws Exception { Map<Integer, ExcelSettingColumn> columns = setting.getColumns(); ImportDataPreviewHandling<E> handling = null; // 获取handling对象 Object obj = ExcelSettingHelper.getImportDataHanler(setting.getHandleClass()); // if ( !ImportDataPreviewHandling.class.isAssignableFrom()) if (!(obj instanceof ImportDataPreviewHandling)) { throw new BizException("handleClass 必须是ImportDataPreviewHandling的子类"); } handling = (ImportDataPreviewHandling<E>) obj; JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.NOPROP); jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor()); int row = sheet.getRows(); int column = sheet.getColumns(); List<ImportData> datas = new ArrayList<ImportData>(column); List<ImportData> successDatas = new ArrayList<ImportData>(column); List<E> es = new ArrayList<E>(column); List<E> successEs = new ArrayList<E>(column); // 一行一行读Excel数据 for (int i = setting.getStartRow(); i < row; i++) { // 处理一行数据 E e = clz.newInstance(); Cell[] cells = sheet.getRow(i); ImportData data = readRow(e, columns, cells); data.setRowNo(Long.valueOf(i)); if(StringUtils.isNotEmpty(setting.getIdField())) { Object excelRowId = PropertyUtils.getProperty(e, setting.getIdField()); if (excelRowId != null) data.setExcelRowId(excelRowId.toString()); } if(StringUtils.isNotEmpty(setting.getCodeField())) { Object excelRowCode = PropertyUtils.getProperty(e, setting.getIdField()); if (excelRowCode != null) data.setExcelRowCode(excelRowCode.toString()); } // data.setExcelData(Hibernate.createClob(JSONObject.fromObject(e).toString())); // data.setExcelData(JSONObject.fromObject(e).toString()); data.setExcelData(StringUtils.getCompactStringFromJson(JSONObject.fromObject(e, jsonConfig))); if (data.getIsSuccess()) { // 通过配置校验 successDatas.add(data); successEs.add(e); } // logger.debug(ToStringBuilder.reflectionToString(data)); datas.add(data); es.add(e); } // 校验数据 callback handling.checkData(successEs, successDatas, params); return datas; } /** * 读取行数据 * @param <E> * @param e * @param columns * @param cells * @return * @throws Exception */ private <E>ImportData readRow(E e, Map<Integer, ExcelSettingColumn> columns, Cell[] cells) throws Exception { ImportData data = new ImportData(); boolean isSuccess = true; StringBuffer errorMessage = new StringBuffer(); for (Entry<Integer, ExcelSettingColumn> entry : columns.entrySet()) { int j = entry.getKey(); ExcelSettingColumn excelSettingColumn = entry.getValue(); Class<?> type = excelSettingColumn.getType(); Object obj = null; if(j>cells.length-1)//如果最后1列或者多列为空,则跳过判断。 break; Cell cell = cells[j]; // Cell cell = sheet.getCell(j, i); if(CellType.EMPTY == cell.getType()) { if (excelSettingColumn.isRequired()) { isSuccess = false; errorMessage.append(excelSettingColumn.getName() + "不能为空!"); } } else if (CellType.DATE == cell.getType()) { if (!(Date.class.isAssignableFrom(type))){ isSuccess = false; errorMessage.append(excelSettingColumn.getName() + "格式有误!"); }else{ DateCell dateCell = (DateCell) cell; obj = convertDate4JXL(dateCell.getDate()); } } else if (CellType.NUMBER == cell.getType()) { if (String.class.isAssignableFrom(type)) { obj = cell.getContents(); } else { if (!(Number.class.isAssignableFrom(type))){ isSuccess = false; errorMessage.append(excelSettingColumn.getName() + "格式有误!"); }else{ obj = NumberUtils.parseNumber(cell.getContents(), type); } } //2012-2-15 caoslin 判断导入列是否需要作统计,如果需要就把值赋给统计列 (sum1 sum2 sum3) if(excelSettingColumn.getColumnName()!=null){ if(excelSettingColumn.getColumnName().equals("sum1")) data.setSum1((Double)obj); if(excelSettingColumn.getColumnName().equals("sum2")) data.setSum2((Double)obj); if(excelSettingColumn.getColumnName().equals("sum3")) data.setSum3((Double)obj); if(excelSettingColumn.getColumnName().equals("sum4")) data.setSum4((Double)obj); if(excelSettingColumn.getColumnName().equals("sum5")) data.setSum5((Double)obj); } // NumberCell numberCell = (NumberCell) cell; // obj = numberCell.getValue(); }else if (CellType.LABEL == cell.getType()) { if (Date.class.isAssignableFrom(type)) { // label 格式中存放日期数据 obj = DateUtils.convert(cell.getContents()); } else if (Number.class.isAssignableFrom(type)) { // label 格式中存放数字格式 try{ obj = NumberUtils.parseNumber(cell.getContents(), type); } catch (Exception ex){ isSuccess = false; errorMessage.append(excelSettingColumn.getName()+"数字格式错误!"); } } else if (String.class.isAssignableFrom(type)) { obj = cell.getContents(); if (excelSettingColumn.getMinLength() != null && ((String)obj).length() < excelSettingColumn.getMinLength()) { isSuccess = false; errorMessage.append(excelSettingColumn.getName() + ":长度不能小于" + excelSettingColumn.getMinLength()); } if (excelSettingColumn.getMaxLength() != null && ((String)obj).length() > excelSettingColumn.getMaxLength()) { isSuccess = false; errorMessage.append(excelSettingColumn.getName() + ":长度不能大于" + excelSettingColumn.getMaxLength()); } } } PropertyUtils.setProperty(e, excelSettingColumn.getField(), obj); } data.setIsSuccess(isSuccess); data.setErrorMessage(errorMessage.toString()); return data; } private FilePersistence fillFilePersistence(File file, Date now) { //创建文件对象 FilePersistence fp = new FilePersistence(); fp.setId(StringUtils.getUUID()); fp.setFileName(file.getName()); fp.setOwnerModule(IMPORT_MODULE); // fp.setContentType(null); // TODO // fp.setOperatorID(getCurrentUser().getUserId()); fp.setLogDate(now); fp.setPhsicalName(file.getAbsolutePath()); return fp; } private ImportInfo fillImportInfo(ExcelSetting setting, Date now, String fileId, Map<String, String> params) { if(params!=null){ //设置动态的下一步action String nextAction = params.get(EXCEL_NEXT_ACTION); if (StringUtils.isNotEmpty(nextAction)) { setting.setNextAction(nextAction); } } ImportInfo importInfo = new ImportInfo(); importInfo.setDefaultConfig(setting.isDefaultConfig()); importInfo.setExcelConfig(ExcelSettingHelper.createExcelSetting(setting)); importInfo.setExcelId(setting.getId()); importInfo.setImportTime(now); if (params != null && params.size() > 0) { JSONObject json = new JSONObject(); json.putAll(params); importInfo.setImportParams(json.toString()); } return importInfo; } private File fillNewFile(File file) { String direcotry = importerDirectory + IMPORT_MODULE + File.separator + System.currentTimeMillis() + "_" + Math.abs(RandomUtils.getRandom().nextInt()) + ".xls"; // String direcotry = file.getParent() + File.separator + System.currentTimeMillis() + "_" + Math.abs(RandomUtils.getRandom().nextInt()) + ".xls"; File newFile = new File(direcotry); if (!newFile.getParentFile().exists()) { newFile.getParentFile().mkdirs(); } // file.renameTo(newFile); logger.info(file.getAbsolutePath() + " to " + newFile.getAbsolutePath()); InputStream is = null; OutputStream os = null; try { is = new FileInputStream(file); os = new FileOutputStream(newFile); IOUtils.copy(is, os); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } return newFile; } public Date convertDate4JXL(Date jxlDate) throws ParseException { if (jxlDate == null) return null; TimeZone gmt = TimeZone.getTimeZone("GMT"); DateFormat dateFormat = new SimpleDateFormat(DateUtils.DATE_TIME_FORMAT, Locale.getDefault()); dateFormat.setTimeZone(gmt); String str = dateFormat.format(jxlDate); TimeZone local = TimeZone.getDefault(); dateFormat.setTimeZone(local); return dateFormat.parse(str); } }
true
aca637b58fc57b24ed7555b09e70d6e2641c88c2
Java
pulumi/pulumi-gcp
/sdk/java/src/main/java/com/pulumi/gcp/storage/outputs/TransferJobTransferSpecObjectConditions.java
UTF-8
8,783
1.921875
2
[ "BSD-3-Clause", "MPL-2.0", "Apache-2.0" ]
permissive
// *** WARNING: this file was generated by pulumi-java-gen. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package com.pulumi.gcp.storage.outputs; import com.pulumi.core.annotations.CustomType; import java.lang.String; import java.util.List; import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; @CustomType public final class TransferJobTransferSpecObjectConditions { /** * @return `exclude_prefixes` must follow the requirements described for `include_prefixes`. See [Requirements](https://cloud.google.com/storage-transfer/docs/reference/rest/v1/TransferSpec#ObjectConditions). * */ private @Nullable List<String> excludePrefixes; /** * @return If `include_prefixes` is specified, objects that satisfy the object conditions must have names that start with one of the `include_prefixes` and that do not start with any of the `exclude_prefixes`. If `include_prefixes` is not specified, all objects except those that have names starting with one of the `exclude_prefixes` must satisfy the object conditions. See [Requirements](https://cloud.google.com/storage-transfer/docs/reference/rest/v1/TransferSpec#ObjectConditions). * */ private @Nullable List<String> includePrefixes; /** * @return If specified, only objects with a &#34;last modification time&#34; before this timestamp and objects that don&#39;t have a &#34;last modification time&#34; are transferred. A timestamp in RFC3339 UTC &#34;Zulu&#34; format, with nanosecond resolution and up to nine fractional digits. Examples: &#34;2014-10-02T15:01:23Z&#34; and &#34;2014-10-02T15:01:23.045123456Z&#34;. * */ private @Nullable String lastModifiedBefore; /** * @return If specified, only objects with a &#34;last modification time&#34; on or after this timestamp and objects that don&#39;t have a &#34;last modification time&#34; are transferred. A timestamp in RFC3339 UTC &#34;Zulu&#34; format, with nanosecond resolution and up to nine fractional digits. Examples: &#34;2014-10-02T15:01:23Z&#34; and &#34;2014-10-02T15:01:23.045123456Z&#34;. * */ private @Nullable String lastModifiedSince; /** * @return A duration in seconds with up to nine fractional digits, terminated by &#39;s&#39;. Example: &#34;3.5s&#34;. * */ private @Nullable String maxTimeElapsedSinceLastModification; /** * @return A duration in seconds with up to nine fractional digits, terminated by &#39;s&#39;. Example: &#34;3.5s&#34;. * */ private @Nullable String minTimeElapsedSinceLastModification; private TransferJobTransferSpecObjectConditions() {} /** * @return `exclude_prefixes` must follow the requirements described for `include_prefixes`. See [Requirements](https://cloud.google.com/storage-transfer/docs/reference/rest/v1/TransferSpec#ObjectConditions). * */ public List<String> excludePrefixes() { return this.excludePrefixes == null ? List.of() : this.excludePrefixes; } /** * @return If `include_prefixes` is specified, objects that satisfy the object conditions must have names that start with one of the `include_prefixes` and that do not start with any of the `exclude_prefixes`. If `include_prefixes` is not specified, all objects except those that have names starting with one of the `exclude_prefixes` must satisfy the object conditions. See [Requirements](https://cloud.google.com/storage-transfer/docs/reference/rest/v1/TransferSpec#ObjectConditions). * */ public List<String> includePrefixes() { return this.includePrefixes == null ? List.of() : this.includePrefixes; } /** * @return If specified, only objects with a &#34;last modification time&#34; before this timestamp and objects that don&#39;t have a &#34;last modification time&#34; are transferred. A timestamp in RFC3339 UTC &#34;Zulu&#34; format, with nanosecond resolution and up to nine fractional digits. Examples: &#34;2014-10-02T15:01:23Z&#34; and &#34;2014-10-02T15:01:23.045123456Z&#34;. * */ public Optional<String> lastModifiedBefore() { return Optional.ofNullable(this.lastModifiedBefore); } /** * @return If specified, only objects with a &#34;last modification time&#34; on or after this timestamp and objects that don&#39;t have a &#34;last modification time&#34; are transferred. A timestamp in RFC3339 UTC &#34;Zulu&#34; format, with nanosecond resolution and up to nine fractional digits. Examples: &#34;2014-10-02T15:01:23Z&#34; and &#34;2014-10-02T15:01:23.045123456Z&#34;. * */ public Optional<String> lastModifiedSince() { return Optional.ofNullable(this.lastModifiedSince); } /** * @return A duration in seconds with up to nine fractional digits, terminated by &#39;s&#39;. Example: &#34;3.5s&#34;. * */ public Optional<String> maxTimeElapsedSinceLastModification() { return Optional.ofNullable(this.maxTimeElapsedSinceLastModification); } /** * @return A duration in seconds with up to nine fractional digits, terminated by &#39;s&#39;. Example: &#34;3.5s&#34;. * */ public Optional<String> minTimeElapsedSinceLastModification() { return Optional.ofNullable(this.minTimeElapsedSinceLastModification); } public static Builder builder() { return new Builder(); } public static Builder builder(TransferJobTransferSpecObjectConditions defaults) { return new Builder(defaults); } @CustomType.Builder public static final class Builder { private @Nullable List<String> excludePrefixes; private @Nullable List<String> includePrefixes; private @Nullable String lastModifiedBefore; private @Nullable String lastModifiedSince; private @Nullable String maxTimeElapsedSinceLastModification; private @Nullable String minTimeElapsedSinceLastModification; public Builder() {} public Builder(TransferJobTransferSpecObjectConditions defaults) { Objects.requireNonNull(defaults); this.excludePrefixes = defaults.excludePrefixes; this.includePrefixes = defaults.includePrefixes; this.lastModifiedBefore = defaults.lastModifiedBefore; this.lastModifiedSince = defaults.lastModifiedSince; this.maxTimeElapsedSinceLastModification = defaults.maxTimeElapsedSinceLastModification; this.minTimeElapsedSinceLastModification = defaults.minTimeElapsedSinceLastModification; } @CustomType.Setter public Builder excludePrefixes(@Nullable List<String> excludePrefixes) { this.excludePrefixes = excludePrefixes; return this; } public Builder excludePrefixes(String... excludePrefixes) { return excludePrefixes(List.of(excludePrefixes)); } @CustomType.Setter public Builder includePrefixes(@Nullable List<String> includePrefixes) { this.includePrefixes = includePrefixes; return this; } public Builder includePrefixes(String... includePrefixes) { return includePrefixes(List.of(includePrefixes)); } @CustomType.Setter public Builder lastModifiedBefore(@Nullable String lastModifiedBefore) { this.lastModifiedBefore = lastModifiedBefore; return this; } @CustomType.Setter public Builder lastModifiedSince(@Nullable String lastModifiedSince) { this.lastModifiedSince = lastModifiedSince; return this; } @CustomType.Setter public Builder maxTimeElapsedSinceLastModification(@Nullable String maxTimeElapsedSinceLastModification) { this.maxTimeElapsedSinceLastModification = maxTimeElapsedSinceLastModification; return this; } @CustomType.Setter public Builder minTimeElapsedSinceLastModification(@Nullable String minTimeElapsedSinceLastModification) { this.minTimeElapsedSinceLastModification = minTimeElapsedSinceLastModification; return this; } public TransferJobTransferSpecObjectConditions build() { final var o = new TransferJobTransferSpecObjectConditions(); o.excludePrefixes = excludePrefixes; o.includePrefixes = includePrefixes; o.lastModifiedBefore = lastModifiedBefore; o.lastModifiedSince = lastModifiedSince; o.maxTimeElapsedSinceLastModification = maxTimeElapsedSinceLastModification; o.minTimeElapsedSinceLastModification = minTimeElapsedSinceLastModification; return o; } } }
true
ee5c367287d8135b5a3757e15e696da54bdbab1c
Java
joeywhalen/3ThumbsUpReviewSite_WCCI
/src/main/java/org/wecancodeit/pojos/Hashtags.java
UTF-8
567
2.4375
2
[]
no_license
package org.wecancodeit.pojos; import javax.persistence.*; import java.util.Set; @Entity public class Hashtags { @Id @GeneratedValue private Long id; private String hashName; @ManyToMany(mappedBy = "hashtags") private Set<Movie> movies; public Hashtags(String hashName) { this.hashName = hashName; } protected Hashtags() { } public Long getId() { return id; } public String getHashName() { return hashName; } public Set<Movie> getMovies() { return movies; } }
true
6c9983ef2519d3d2d96e490d131ed5154e2e4a14
Java
MarioEcheve/lo-digital-backend-prod-gcp
/src/main/java/com/lodigital/web/rest/TipoLibroResource.java
UTF-8
5,019
2.40625
2
[]
no_license
package com.lodigital.web.rest; import com.lodigital.domain.TipoLibro; import com.lodigital.repository.TipoLibroRepository; import com.lodigital.web.rest.errors.BadRequestAlertException; import io.github.jhipster.web.util.HeaderUtil; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; /** * REST controller for managing {@link com.lodigital.domain.TipoLibro}. */ @RestController @RequestMapping("/api") @Transactional public class TipoLibroResource { private final Logger log = LoggerFactory.getLogger(TipoLibroResource.class); private static final String ENTITY_NAME = "tipoLibro"; @Value("${jhipster.clientApp.name}") private String applicationName; private final TipoLibroRepository tipoLibroRepository; public TipoLibroResource(TipoLibroRepository tipoLibroRepository) { this.tipoLibroRepository = tipoLibroRepository; } /** * {@code POST /tipo-libros} : Create a new tipoLibro. * * @param tipoLibro the tipoLibro to create. * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new tipoLibro, or with status {@code 400 (Bad Request)} if the tipoLibro has already an ID. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PostMapping("/tipo-libros") public ResponseEntity<TipoLibro> createTipoLibro(@RequestBody TipoLibro tipoLibro) throws URISyntaxException { log.debug("REST request to save TipoLibro : {}", tipoLibro); if (tipoLibro.getId() != null) { throw new BadRequestAlertException("A new tipoLibro cannot already have an ID", ENTITY_NAME, "idexists"); } TipoLibro result = tipoLibroRepository.save(tipoLibro); return ResponseEntity.created(new URI("/api/tipo-libros/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) .body(result); } /** * {@code PUT /tipo-libros} : Updates an existing tipoLibro. * * @param tipoLibro the tipoLibro to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated tipoLibro, * or with status {@code 400 (Bad Request)} if the tipoLibro is not valid, * or with status {@code 500 (Internal Server Error)} if the tipoLibro couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PutMapping("/tipo-libros") public ResponseEntity<TipoLibro> updateTipoLibro(@RequestBody TipoLibro tipoLibro) throws URISyntaxException { log.debug("REST request to update TipoLibro : {}", tipoLibro); if (tipoLibro.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } TipoLibro result = tipoLibroRepository.save(tipoLibro); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, tipoLibro.getId().toString())) .body(result); } /** * {@code GET /tipo-libros} : get all the tipoLibros. * * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of tipoLibros in body. */ @GetMapping("/tipo-libros") public List<TipoLibro> getAllTipoLibros() { log.debug("REST request to get all TipoLibros"); return tipoLibroRepository.findAll(); } /** * {@code GET /tipo-libros/:id} : get the "id" tipoLibro. * * @param id the id of the tipoLibro to retrieve. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the tipoLibro, or with status {@code 404 (Not Found)}. */ @GetMapping("/tipo-libros/{id}") public ResponseEntity<TipoLibro> getTipoLibro(@PathVariable Long id) { log.debug("REST request to get TipoLibro : {}", id); Optional<TipoLibro> tipoLibro = tipoLibroRepository.findById(id); return ResponseUtil.wrapOrNotFound(tipoLibro); } /** * {@code DELETE /tipo-libros/:id} : delete the "id" tipoLibro. * * @param id the id of the tipoLibro to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/tipo-libros/{id}") public ResponseEntity<Void> deleteTipoLibro(@PathVariable Long id) { log.debug("REST request to delete TipoLibro : {}", id); tipoLibroRepository.deleteById(id); return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); } }
true