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
615a8654141d28187e68b41ccc21fe51f1367f95
Java
garima3292/PerfectlyFine
/app/src/main/java/uidesign/cs465/com/perfectlyfine/AddPaymentMethodActivity.java
UTF-8
2,952
2.25
2
[]
no_license
package uidesign.cs465.com.perfectlyfine; import android.content.Intent; import android.provider.MediaStore; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import uidesign.cs465.com.perfectlyfine.model.PaymentMethod; public class AddPaymentMethodActivity extends AppCompatActivity { private RestaurantsLookupDb restuarantsData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_payment_method); restuarantsData = RestaurantsLookupDb.getInstance(); Button addPaymentMethodButton = (Button) findViewById(R.id.addCard); addPaymentMethodButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { RadioGroup cardProvider = (RadioGroup) findViewById(R.id.card_provider); EditText name = (EditText) findViewById(R.id.name); EditText cardNo = (EditText) findViewById(R.id.card_no); EditText cvc = (EditText) findViewById(R.id.cvc); EditText expMonth = (EditText) findViewById(R.id.exp_month); EditText expYear = (EditText) findViewById(R.id.exp_year); if (isEmpty(name) || isEmpty(cardNo) || isEmpty(cvc) || isEmpty(expMonth) || isEmpty(expYear)) { Snackbar snackbar = Snackbar.make(findViewById(R.id.addPaymentMethod), "Please fill out all fields!", Snackbar.LENGTH_SHORT); View sbView = snackbar.getView(); sbView.setBackgroundColor(getResources().getColor(R.color.red)); snackbar.show(); return; } PaymentMethod.Provider provider; if (cardProvider.equals("VISA")) provider = PaymentMethod.Provider.VISA; else if (cardProvider.equals("Mastercard")) provider = PaymentMethod.Provider.MASTERCARD; else provider = PaymentMethod.Provider.AMERICANEXPRESS; PaymentMethod paymentMethod = new PaymentMethod(name.getText().toString(), cardNo.getText().toString(), cvc.getText().toString(), expMonth.getText().toString(), expYear.getText().toString(), provider); restuarantsData.addPaymentMethod(paymentMethod); Intent intent = new Intent(AddPaymentMethodActivity.this, ManagePaymentMethodActivity.class); intent.putExtra("cardAdded", "true"); startActivity(intent); } }); } private boolean isEmpty(EditText myeditText) { return myeditText.getText().toString().trim().length() == 0; } }
true
45a1b21f61c3ffec1590e0272943657f2d4e1857
Java
luojianhe1992/CareerCup
/src/OneStackTwoType/Dog.java
UTF-8
600
3.328125
3
[]
no_license
package OneStackTwoType; public class Dog extends Animal { int dogValue; public Dog() { super(); } public Dog(int dogValue) { super(); this.dogValue = dogValue; } @Override public void shout() { // TODO Auto-generated method stub System.out.println("I am a dog."); } public int getDogValue() { return dogValue; } public void setDogValue(int dogValue) { this.dogValue = dogValue; } @Override public String toString() { // TODO Auto-generated method stub StringBuilder sb = new StringBuilder(); sb.append("dog "+dogValue); return sb.toString(); } }
true
44598faf70217c91c8127e7cb1e2fcaba1e9d72f
Java
invisiblejoke/duxcom
/duxcom/src/main/java/uq/deco2800/duxcom/coop/GameCountdown.java
UTF-8
2,551
2.90625
3
[]
no_license
package uq.deco2800.duxcom.coop; import uq.deco2800.duxcom.coop.listeners.CountdownListener; import uq.deco2800.duxcom.sound.SoundPlayer; /** * Manages the game countdown * * Created by liamdm on 18/10/2016. */ public class GameCountdown { private final CountdownListener listener; private boolean isBlocking = true; private boolean isCountdownStarted = false; private boolean defsNotCountingDown = false; private static final double[] countdownStages = {1136, 2180, 3204, 4299, 5251, 6336, 7585, 8578, 9458, 10420, 12022}; long countdownStarted = 0; public GameCountdown(CountdownListener listener) { this.listener = listener; } /** * If this should be blocking input */ public boolean isBlocking(){ return isCountingDown() || isBlocking; } /** * Start the game countdown */ public void start(){ isCountdownStarted = true; isBlocking = false; countdownStarted = System.currentTimeMillis(); SoundPlayer.playGameCountdown(); Thread countdownThread = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep((long)countdownStages[countdownStages.length - 1]); } catch (InterruptedException i){ Thread.currentThread().interrupt(); } defsNotCountingDown = true; listener.onCountdownEnded(); } }); countdownThread.start(); } /** * Returns the game countdown delta */ public double getCountdownDelta() { long now = System.currentTimeMillis(); return now - countdownStarted; } /** * Returns the number corresponding to the current countdown stage */ public int getCountdownNumber() { double delta = getCountdownDelta(); for (int i = 0; i < countdownStages.length; ++i) { double stage = countdownStages[i] + 250; if (delta < stage) { return 11 - i; } } return 0; } /** * Returns true if the game is counting down to game start */ public boolean isCountingDown() { if(defsNotCountingDown) { return false; } if (!this.isCountdownStarted) { return false; } if (getCountdownDelta() > 13000) { this.isCountdownStarted = false; } return isCountdownStarted; } }
true
94bf9804f054ab3766f5e6fb890c6094a69ae5c2
Java
cncq-kycb/MovieRecommend
/Recommend/src/main/java/cn/edu/cqu/Recommend/Pojo/UserKey.java
UTF-8
403
2.171875
2
[]
no_license
package cn.edu.cqu.Recommend.Pojo; public class UserKey { private Integer userId; private Long userTel; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Long getUserTel() { return userTel; } public void setUserTel(Long userTel) { this.userTel = userTel; } }
true
80b81767746a011146b9d1bccaf3b96ee826c333
Java
se-wook/java
/javaSE/src/chapter03/LabelTest.java
UHC
568
3.9375
4
[]
no_license
package chapter03; import java.util.Scanner; /** * * label : * - ݺ ̸ ο * - Ư ݺ break or continue ִ. * - * label ̸: * ݺ */ public class LabelTest { public static void main(String[] args) { // TODO Auto-generated method stub first: for(int i=1;i<=100;i++) { second: for(int j=1;j<=100;j++) { System.out.printf("%d * %d = %d ", i,j,i*j); if(i*j > 50) { break first; }else if(i*j >= 30){ break second; } } System.out.println(); } } }
true
6b8e13f6060995eade436358e5c40801084bdf27
Java
wheeller/web-content
/src/main/java/hello/exceptions/NullPointerException.java
UTF-8
187
1.960938
2
[]
no_license
//package hello.exceptions; // //public class NullPointerException extends RuntimeException { // // public NullPointerException (String message){ // super(message); // } //}
true
46e7fb3d96c556843457742fea8da120c6c4e3f7
Java
eliekozah/myexplore
/android/native/mydemos/NeuralTheraputicTest/src/com/neural/view/MultiTouchView.java
UTF-8
9,655
2.171875
2
[]
no_license
/** * Copyright Trimble Inc., 2014 - 2015 All rights reserved. * * Licensed Software Confidential and Proprietary Information of Trimble Inc., * made available under Non-Disclosure Agreement OR License as applicable. * * Product Name: * * * Module Name: com.neural.view * * File name: MultiTouchView.java * * Author: sprabhu * * Created On: 17-Jan-201512:58:34 pm * * Abstract: * * * Environment: Mobile Profile : Mobile Configuration : * * Notes: * * Revision History: * * */ package com.neural.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.Path; import android.graphics.PointF; import android.graphics.Rect; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import com.neural.demo.R; import java.util.Collections; import java.util.Comparator; import java.util.Vector; /** * @author sprabhu * */ public class MultiTouchView extends View { private Paint circlePaint = new Paint( Paint.ANTI_ALIAS_FLAG); private Paint linePaint = new Paint( Paint.ANTI_ALIAS_FLAG); private Paint scorePaint = new Paint( Paint.ANTI_ALIAS_FLAG); private String stTopScore=null; private String stCurrentScore=null; final int MAX_NUMBER_OF_POINT = 10; private PointSort pointSort = null; private MyPoints baryCenter = null; private Vector<MyPoints> vecPointFs = null; private Path mPath = null; private transient int iRadius= 50; private Rect bounds = new Rect(); private double dTopArea=0; private double dCurrentArea=0; public MultiTouchView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } public MultiTouchView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public MultiTouchView(Context context) { super(context); init(context); } void init(final Context context) { circlePaint.setStyle(Paint.Style.FILL); circlePaint.setStrokeWidth(1); circlePaint.setColor(Color.YELLOW); linePaint.setColor(0XFF7BC7F2); linePaint.setStyle(Paint.Style.FILL); linePaint.setStrokeWidth(1); scorePaint.setColor(Color.BLACK); scorePaint.setFakeBoldText(true); scorePaint.setTextSize(context.getResources().getDimensionPixelSize(R.dimen.score_text_size)); scorePaint.setStyle(Style.STROKE); scorePaint.setStrokeCap(Cap.ROUND); scorePaint.setStrokeJoin(Join.ROUND); mPath = new Path(); pointSort = new PointSort(); vecPointFs = new Vector<MyPoints>(MAX_NUMBER_OF_POINT); for (int i =0;i< MAX_NUMBER_OF_POINT;i++) { vecPointFs.add(new MyPoints()); } stTopScore=getResources().getString(R.string.Top_score); stCurrentScore=getResources().getString(R.string.Current_score); iRadius=getResources().getDimensionPixelSize(R.dimen.touch_radius); } @Override protected synchronized void onDraw(Canvas canvas) { canvas.drawColor(0xEFDFDFDF); boolean isTouch = false; for (int i = 0; i < vecPointFs.size(); i++) { final MyPoints myPoints = vecPointFs.get(i); if (myPoints.isTouching && myPoints.x != 0 && myPoints.y != 0) { isTouch = true; canvas.drawCircle(myPoints.x, myPoints.y, iRadius, circlePaint); } } if (isTouch) { canvas.drawPath(mPath, linePaint); } else { mPath.reset(); } final String sttopScore=String.format(stTopScore, dTopArea); final String stcurrentScore=String.format(stCurrentScore, dCurrentArea); int iTextWidth= (int)scorePaint.measureText(sttopScore); int iHeight= (int) ( Math.abs(scorePaint.ascent()) + Math.abs(scorePaint.descent())); int xPos = (canvas.getWidth() -iTextWidth ); int yPos = (int) getTop() +iHeight ; canvas.drawText(sttopScore, xPos, yPos, scorePaint); iTextWidth= (int)scorePaint.measureText(stcurrentScore); iHeight= (int) ( Math.abs(scorePaint.ascent()) + Math.abs(scorePaint.descent())); xPos = (canvas.getWidth() -iTextWidth ); yPos = (int) yPos+ +iHeight ; //((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center. canvas.drawText(stcurrentScore, xPos, yPos, scorePaint); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec)); } private class PointSort implements Comparator<MyPoints> { @Override public int compare(MyPoints lhs, MyPoints rhs) { if (lhs.isTouching == false || rhs.isTouching == false) { return 0; } if (lhs.angle < rhs.angle) { return -1; } else if (lhs.angle > rhs.angle) { return 1; } else { return 0; } } } @Override public synchronized boolean onTouchEvent(MotionEvent event) { int action = (event.getAction() & MotionEvent.ACTION_MASK); int pointCount = event.getPointerCount(); for (int i = 0; i < pointCount; i++) { int id = event.getPointerId(i); // Ignore pointer higher than our max. if (id < MAX_NUMBER_OF_POINT && id < vecPointFs.size()) { final MyPoints myPoints = vecPointFs.get(id); if ((action == MotionEvent.ACTION_DOWN) || (action == MotionEvent.ACTION_POINTER_DOWN) || (action == MotionEvent.ACTION_MOVE)) { myPoints.isTouching = true; myPoints.set((int) event.getX(i), (int) event.getY(i)); } else { myPoints.isTouching = false; } } } baryCenter = polygonCenterOfMass(); if (baryCenter != null) { for (MyPoints myPoints : vecPointFs) { if (myPoints.isTouching == false) { continue; } myPoints.angle = Math.atan2(myPoints.y - baryCenter.y, myPoints.x - baryCenter.x); } Collections.sort(vecPointFs, pointSort); mPath.reset(); for (MyPoints myPoints : vecPointFs) { if (myPoints.isTouching == false) { continue; } if (mPath.isEmpty()) { mPath.moveTo(myPoints.x, myPoints.y); } else { mPath.lineTo(myPoints.x, myPoints.y); } } } invalidate(); return true; } public MyPoints polygonCenterOfMass() { double cx = 0, cy = 0; int N = vecPointFs.size() ; if (N < 3) { return null; } double dArea = signedPolygonArea(); dCurrentArea= (dArea < 0 ?-dArea:dArea )/ 1000; if(dCurrentArea > dTopArea ){ dTopArea =dCurrentArea; } final MyPoints res = new MyPoints(0, 0); int i, j; double factor = 0; for (i = 0; i < N; i++) { j = (i + 1) % N; if (!vecPointFs.get(i).isTouching || !vecPointFs.get(j).isTouching) { continue; } double lat1 = vecPointFs.get(i).y; double lon1 = vecPointFs.get(i).x; double lat2 = vecPointFs.get(j).y; double lon2 = vecPointFs.get(j).x; factor = (lon1 * lat2 - lon2 * lat1); cx += (lon1 + lon2) * factor; cy += (lat1 + lat2) * factor; } dArea *= 6.0f; factor = 1 / dArea; cx *= factor; cy *= factor; res.setXY((float) cx, (float) cy); return res; } public double signedPolygonArea() { final int N = vecPointFs.size() ; int i, j; double area = 0; for (i = 0; i < N; i++) { j = (i + 1) % N; if (!vecPointFs.get(i).isTouching || !vecPointFs.get(j).isTouching) { continue; } double lat1 = vecPointFs.get(i).y; double lon1 = vecPointFs.get(i).x; double lat2 = vecPointFs.get(j).y; double lon2 = vecPointFs.get(j).x; area += lon1 * lat2; area -= lat1 * lon2; } area /= 2.0; return (area); // for unsigned // return(area < 0 ? -area : area); } private final static class MyPoints extends PointF { private boolean isTouching = false; private double angle = 0; /** * */ public MyPoints(final float x, final float y) { super(x, y); } /** * */ public MyPoints() { } public void setXY(final float x, final float y) { set(x, y); } /** * @param isTouching * the isTouching to set */ public void setTouching(boolean isTouching) { this.isTouching = isTouching; } /** * @return the isTouching */ public boolean isTouching() { return isTouching; } } }
true
d935a4956120fc81e2751bb5d5f7b1770e527b41
Java
elegentJava/laboratory
/sem-corre/src/main/java/com/bupt/ltb/sem/corre/pojo/CorreCategory.java
UTF-8
694
2
2
[]
no_license
package com.bupt.ltb.sem.corre.pojo; import java.util.List; /** * 函电类别 * * @author Hogan * */ public class CorreCategory { private Integer ccid; private String content; private List<CorreCategory> sonCategories; public Integer getCcid() { return ccid; } public void setCcid(Integer ccid) { this.ccid = ccid; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public List<CorreCategory> getSonCategories() { return sonCategories; } public void setSonCategories(List<CorreCategory> sonCategories) { this.sonCategories = sonCategories; } }
true
160526bd046df7dc685c340643c4d5e43a5a2bdd
Java
mrugenmike/AirNote
/services/src/main/java/com/airnote/services/notes/NotesContent.java
UTF-8
816
2.109375
2
[]
no_license
package com.airnote.services.notes; public class NotesContent { String accessToken; String userName; String noteTitle; String noteContent; public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getNoteTitle() { return noteTitle; } public void setNoteTitle(String noteTitle) { this.noteTitle = noteTitle; } public String getNoteContent() { return noteContent; } public void setNoteContent(String noteContent) { this.noteContent = noteContent; } }
true
254fc08b4cef7bda8639115b596d3e0f856b93ec
Java
MrIvanPlays/GotoServer
/src/main/java/com/mrivanplays/server/LinkController.java
UTF-8
10,239
2.0625
2
[ "MIT" ]
permissive
package com.mrivanplays.server; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StreamUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.AllArgsConstructor; import at.favre.lib.crypto.bcrypt.BCrypt; @Controller public class LinkController { @Autowired private ApplicationConfiguration appConfiguration; @GetMapping("/") public String render(Model model, HttpServletRequest request) { model.addAttribute("gotoInfo", new LinkCreateRequest()); String baseUrl = getBaseUrl(request); model.addAttribute("customKeyword", baseUrl + "/customCreate"); model.addAttribute("siteUrl", baseUrl); return "shortenLink"; } @GetMapping("/favicon.ico") public void renderFavicon(HttpServletResponse response) { response.setContentType("image/vnd.microsoft.icon"); try (InputStream in = new FileInputStream(appConfiguration.getFavicon())) { StreamUtils.copy(in, response.getOutputStream()); } catch (IOException ignored) { } } @GetMapping("/{id}") public void redirect(@PathVariable String id, HttpServletResponse response) throws IOException { File file = new File("./links", id + ".json"); if (!file.exists()) { response.sendError(404, "Link not found"); return; } try (Reader reader = new FileReader(file)) { String link = ServerConstants.JSON_MAPPER.reader().readTree(reader).get("link").asText(); response.sendRedirect(link); } } @GetMapping("/customCreate") public String renderCustom(Model model, HttpServletRequest request) { model.addAttribute("gotoInfo", new CustomLinkCreateRequest()); String baseUrl = getBaseUrl(request); model.addAttribute("normalShort", baseUrl); model.addAttribute("siteUrl", baseUrl + "/customCreate"); return "customShortenLink"; } @PostMapping("/customCreate") public ModelAndView renderCustomPost(@ModelAttribute CustomLinkCreateRequest gotoInfo, HttpServletRequest request) { String baseUrl = getBaseUrl(request); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("homePage", baseUrl); String url = gotoInfo.getLongUrl(); try { new URL(url); } catch (MalformedURLException e) { modelAndView.setViewName("error-406"); return modelAndView; } String password = gotoInfo.getPassword(); boolean verify = BCrypt.verifyer().verify(password.toCharArray(), appConfiguration.getEncodedPassword()).verified; if (!verify) { modelAndView.setViewName("error-403"); return modelAndView; } try { String linkId = createLinkShorted(gotoInfo.getLongUrl(), gotoInfo.getKeyword()); modelAndView.setViewName("shortenLinkResult"); modelAndView.addObject("gotoInfo", new LinkCreateResponse(baseUrl + "/" + linkId)); modelAndView.addObject("another", baseUrl + "/customCreate"); return modelAndView; } catch (IOException e) { e.printStackTrace(); modelAndView.setViewName("error-500"); return modelAndView; } finally { System.gc(); } } @PostMapping("/") public ModelAndView renderPost(@ModelAttribute LinkCreateRequest gotoInfo, HttpServletRequest request) { String baseUrl = getBaseUrl(request); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("homePage", baseUrl); String url = gotoInfo.getUrl(); try { new URL(url); } catch (MalformedURLException e) { modelAndView.setViewName("error-406"); return modelAndView; } String password = gotoInfo.getPassword(); boolean verify = BCrypt.verifyer().verify(password.toCharArray(), appConfiguration.getEncodedPassword()).verified; if (!verify) { modelAndView.setViewName("error-403"); return modelAndView; } try { String linkId = createLinkShorted(url, null); modelAndView.setViewName("shortenLinkResult"); modelAndView.addObject("gotoInfo", new LinkCreateResponse(baseUrl + "/" + linkId)); modelAndView.addObject("another", baseUrl); return modelAndView; } catch (IOException e) { e.printStackTrace(); modelAndView.setViewName("error-500"); return modelAndView; } finally { System.gc(); } } @PostMapping("/api/create") public ResponseEntity<LinkCreateResponse> createRequest(@RequestBody LinkCreateRequest linkRequest, HttpServletRequest request) { String baseUrl = getBaseUrl(request); String url = linkRequest.getUrl(); try { new URL(url); } catch (MalformedURLException e) { throw new PostError("URL Invalid", 406); } String password = linkRequest.getPassword(); boolean verify = BCrypt.verifyer().verify(password.toCharArray(), appConfiguration.getEncodedPassword()).verified; if (!verify) { throw new PostError("Cannot verify password", 403); } try { String linkId = createLinkShorted(url, null); return ResponseEntity.ok().body(new LinkCreateResponse(baseUrl + "/" + linkId)); } catch (IOException e) { e.printStackTrace(); throw new PostError("Internal error", 500); } finally { System.gc(); } } @PostMapping("/api/createCustom") public ResponseEntity<LinkCreateResponse> customCreateRequest(@RequestBody CustomLinkCreateRequest linkRequest, HttpServletRequest request) { String baseUrl = getBaseUrl(request); String url = linkRequest.getLongUrl(); try { new URL(url); } catch (MalformedURLException e) { throw new PostError("URL Invalid", 406); } String password = linkRequest.getPassword(); boolean verify = BCrypt.verifyer().verify(password.toCharArray(), appConfiguration.getEncodedPassword()).verified; if (!verify) { throw new PostError("Cannot verify password", 403); } try { String linkId = createLinkShorted(url, linkRequest.getKeyword()); return ResponseEntity.ok().body(new LinkCreateResponse(baseUrl + "/" + linkId)); } catch (IOException e) { e.printStackTrace(); throw new PostError("Internal error", 500); } finally { System.gc(); } } private String createLinkShorted(String url, String keyword) throws IOException { String existing = checkForExisting(url); if (existing != null) { return existing; } Information info; if (keyword != null) { info = getInfo(keyword); } else { info = getInfo(StringRandomCreator.generateRandomString(11)); } File file = info.file; if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } file.createNewFile(); String linkId = info.linkId; ObjectNode object = new ObjectNode(ServerConstants.JSON_MAPPER.getNodeFactory()); object.put("link", url); try (Writer writer = new FileWriter(file)) { ServerConstants.JSON_MAPPER.writeValue(writer, object); } return linkId; } private String checkForExisting(String link) { File directory = new File(".", "links"); if (!directory.exists()) { directory.mkdirs(); return null; } File[] files = directory.listFiles(($, name) -> name.endsWith(".json")); if (files == null || files.length == 0) { return null; } for (File file : files) { try (Reader reader = new FileReader(file)) { JsonNode node = ServerConstants.JSON_MAPPER.readTree(reader); if (node.get("link").asText().equalsIgnoreCase(link)) { return file.getName().replace(".json", ""); } } catch (IOException ignored) { } } return null; } private Information getInfo(String id) { File file = new File("./links", id + ".json"); if (file.exists()) { return getInfo(StringRandomCreator.generateRandomString(11)); } return new Information(file, id); } private String getBaseUrl(HttpServletRequest request) { String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request) .replacePath(null) .build().toUriString(); if (appConfiguration.shouldUseHTTPS()) { return baseUrl.replace("http", "https"); } else { return baseUrl; } } @AllArgsConstructor private static final class Information { private File file; private String linkId; } }
true
45fab06668c97215e2ffd1d2787b1567d5822efb
Java
KinyoshiMods/Ancient-Tree-Root
/mod_AncientTreeRoot.java
UTF-8
6,175
2.203125
2
[ "BSD-2-Clause" ]
permissive
package net.minecraft.src; import java.util.Random; import java.io.*; import java.util.*; import net.minecraft.client.Minecraft; public class mod_AncientTreeRoot extends BaseMod { public mod_AncientTreeRoot() { // readWriteProperties(); BlockAncientTreeRoot = new BlockAncientTreeRoot(BlockAncientTreeRootID).setStepSound(Block.soundWoodFootstep).setUnlocalizedName("BlockAncientTreeRoot").setHardness(0.3F).setResistance(0.3F).setLightValue(0.0F); ItemAncientTreeRoot = new Item(ItemAncientTreeRootID).setUnlocalizedName("ItemAncientTreeRoot"); ModLoader.addName(BlockAncientTreeRoot, "Ancient Tree Root"); BlockAncientTreeRoot.setCreativeTab(CreativeTabs.tabBlock); ModLoader.addName(ItemAncientTreeRoot, "Ancient Tree Root"); ItemAncientTreeRoot.setCreativeTab(CreativeTabs.tabMaterials); ModLoader.addSmelting(ItemAncientTreeRoot.itemID, new ItemStack(Item.coal, 1, 1), 0.1F); ModLoader.addRecipe(new ItemStack(Item.stick, 1), new Object[] {"W", 'W', ItemAncientTreeRoot}); ModLoader.addShapelessRecipe(new ItemStack(Block.sapling, 1), new Object[] {Item.seeds, ItemAncientTreeRoot}); } public void readWriteProperties() { Properties properties = new Properties(); try { File file = new File((new StringBuilder()).append(Minecraft.getMinecraftDir()).append("/mods/AncientTreeRoot.config").toString()); boolean flag = file.createNewFile(); if(flag) { FileOutputStream fileoutputstream = new FileOutputStream(file); properties.setProperty("BlockAncientTreeRootID", Integer.toString(231)); properties.setProperty("ItemAncientTreeRootID", Integer.toString(2043)); properties.setProperty("ShouldMoreOreSpawn", Boolean.toString(false)); properties.store(fileoutputstream, "Change the ID's to fix ID incompatibilities."); fileoutputstream.close(); } properties.load(new FileInputStream((new StringBuilder()).append(Minecraft.getMinecraftDir()).append("/mods/AncientTreeRoot.config").toString())); BlockAncientTreeRootID = Integer.parseInt(properties.getProperty("BlockAncientTreeRootID")); ItemAncientTreeRootID = Integer.parseInt(properties.getProperty("ItemAncientTreeRootID")); ShouldMoreOreSpawn = Boolean.parseBoolean(properties.getProperty("ShouldMoreOreSpawn")); } catch(IOException ioexception) { ioexception.printStackTrace(); BlockAncientTreeRootID = 231; ItemAncientTreeRootID = 2043; ShouldMoreOreSpawn = false; } } public static Block BlockAncientTreeRoot; public static int BlockAncientTreeRootID; public static Item ItemAncientTreeRoot; public static int ItemAncientTreeRootID; public static boolean ShouldMoreOreSpawn; public String getVersion() { return "MineCraft1.5.2__AncientTreeRoot1.5.2r1"; } public void generateSurface(World world, Random r, int i, int j) { if (ShouldMoreOreSpawn == true) { for(int k = 0; k < 5 + r.nextInt(14); k++) { int randPosX = i + r.nextInt(8); int randPosY = r.nextInt(128); int randPosZ = j + r.nextInt(8); //stone (new WorldGenMinable(BlockAncientTreeRoot.blockID, 5 + r.nextInt(10))).generate(world, r, randPosX, randPosY, randPosZ); } for(int k = 0; k < 9 + r.nextInt(16); k++) { int randPosX = i + r.nextInt(8); int randPosY = r.nextInt(128); int randPosZ = j + r.nextInt(8); //dirt (new WorldGenAncientTreeRoot(BlockAncientTreeRoot.blockID, 7 + r.nextInt(14))).generate(world, r, randPosX, randPosY, randPosZ); } for(int k = 0; k < 8 + r.nextInt(16); k++) { int randPosX = i + r.nextInt(8); int randPosY = r.nextInt(128); int randPosZ = j + r.nextInt(8); //grass (new WorldGenAncientTreeRoot2(BlockAncientTreeRoot.blockID, 9 + r.nextInt(17))).generate(world, r, randPosX, randPosY, randPosZ); } for(int k = 0; k < 9 + r.nextInt(18); k++) { int randPosX = i + r.nextInt(8); int randPosY = r.nextInt(128); int randPosZ = j + r.nextInt(8); //sand (new WorldGenAncientTreeRoot3(BlockAncientTreeRoot.blockID, 7 + r.nextInt(14))).generate(world, r, randPosX, randPosY, randPosZ); } } else { for(int k = 0; k < 3 + r.nextInt(5); k++) { int randPosX = i + r.nextInt(8); int randPosY = r.nextInt(128); int randPosZ = j + r.nextInt(8); //stone (new WorldGenMinable(BlockAncientTreeRoot.blockID, 2 + r.nextInt(4))).generate(world, r, randPosX, randPosY, randPosZ); } for(int k = 0; k < 6 + r.nextInt(9); k++) { int randPosX = i + r.nextInt(8); int randPosY = r.nextInt(128); int randPosZ = j + r.nextInt(8); //dirt (new WorldGenAncientTreeRoot(BlockAncientTreeRoot.blockID, 3 + r.nextInt(7))).generate(world, r, randPosX, randPosY, randPosZ); } for(int k = 0; k < 6 + r.nextInt(9); k++) { int randPosX = i + r.nextInt(8); int randPosY = r.nextInt(128); int randPosZ = j + r.nextInt(8); //grass (new WorldGenAncientTreeRoot2(BlockAncientTreeRoot.blockID, 4 + r.nextInt(6))).generate(world, r, randPosX, randPosY, randPosZ); } for(int k = 0; k < 8 + r.nextInt(12); k++) { int randPosX = i + r.nextInt(8); int randPosY = r.nextInt(128); int randPosZ = j + r.nextInt(8); //sand (new WorldGenAncientTreeRoot3(BlockAncientTreeRoot.blockID, 3 + r.nextInt(5))).generate(world, r, randPosX, randPosY, randPosZ); } } } public int addFuel(int par1, int par2) { if(par1 == ItemAncientTreeRoot.itemID) { return 800; } return 0; } public void load() { ModLoader.registerBlock(BlockAncientTreeRoot); } }
true
203aaff6f45f9f793cb099498c496136363b0c2b
Java
aws/aws-toolkit-eclipse
/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/AbstractDeployWizardPage.java
UTF-8
11,521
1.539063
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.eclipse.elasticbeanstalk.server.ui; import java.util.Iterator; import org.eclipse.core.databinding.AggregateValidationStatus; import org.eclipse.core.databinding.Binding; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.core.databinding.UpdateValueStrategy; import org.eclipse.core.databinding.observable.ChangeEvent; import org.eclipse.core.databinding.observable.IChangeListener; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.jface.fieldassist.FieldDecoration; import org.eclipse.jface.fieldassist.FieldDecorationRegistry; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Text; import org.eclipse.wst.server.ui.wizard.IWizardHandle; import org.eclipse.wst.server.ui.wizard.WizardFragment; import com.amazonaws.eclipse.core.ui.WebLinkListener; import com.amazonaws.eclipse.elasticbeanstalk.deploy.DeployWizardDataModel; import com.amazonaws.eclipse.elasticbeanstalk.deploy.NotEmptyValidator; /** * Abstract base class with utilities common to all deploy wizard pages. */ public abstract class AbstractDeployWizardPage extends WizardFragment { @Override public boolean hasComposite() { return true; } protected DeployWizardDataModel wizardDataModel; /** Binding context for UI controls and deploy wizard data model */ protected DataBindingContext bindingContext; /** Collective status of all validators in our binding context */ protected AggregateValidationStatus aggregateValidationStatus; protected IWizardHandle wizardHandle; /** * Generic selection listener used by radio buttons created by this class to * notify the page to update controls and re-run binding validators. */ protected final SelectionListener selectionListener = new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } @Override public void widgetSelected(SelectionEvent e) { radioButtonSelected(e.getSource()); runValidators(); } }; /** * Initializes the data validators with a fresh state. Subclasses should * call this before performing data binding to ensure they don't have stale * handlers. Because these fragments persist in the workbench and the * objects are reused, this process must be performed somewhere in the * lifecycle other than the constructor. */ protected final void initializeValidators() { bindingContext = new DataBindingContext(); aggregateValidationStatus = new AggregateValidationStatus(bindingContext, AggregateValidationStatus.MAX_SEVERITY); } protected IChangeListener changeListener; /** * Subclasses can override this callback method to be notified when the value of a radio button * changes so that any additional UI updates can be made. */ protected void radioButtonSelected(Object sourceButton) { } protected AbstractDeployWizardPage(DeployWizardDataModel wizardDataModel) { this.wizardDataModel = wizardDataModel; changeListener = new IChangeListener() { @Override public void handleChange(ChangeEvent event) { Object value = aggregateValidationStatus.getValue(); if (value instanceof IStatus == false) return; wizardHandle.setMessage(getPageDescription(), IStatus.OK); IStatus status = (IStatus)value; setComplete(status.getSeverity() == IStatus.OK); } }; } /** * Returns the page title for this fragment. */ public abstract String getPageTitle(); /** * Returns the "OK" status message for this fragment. */ public abstract String getPageDescription(); @Override public void enter() { if (wizardHandle != null) { wizardHandle.setTitle(getPageTitle()); wizardHandle.setMessage(getPageDescription(), IStatus.OK); } if (aggregateValidationStatus != null) aggregateValidationStatus.addChangeListener(changeListener); } @Override public void exit() { if (aggregateValidationStatus != null) aggregateValidationStatus.removeChangeListener(changeListener); } @Override public void performCancel(IProgressMonitor monitor) throws CoreException { setComplete(false); exit(); } @Override public void performFinish(IProgressMonitor monitor) throws CoreException { setComplete(false); exit(); } /** * Runs all the validators for the current binding context. */ protected void runValidators() { Iterator<?> iterator = bindingContext.getBindings().iterator(); while (iterator.hasNext()) { Binding binding = (Binding)iterator.next(); binding.updateTargetToModel(); } } /* * Widget Helper Methods */ public static ControlDecoration newControlDecoration(Control control, String message) { ControlDecoration decoration = new ControlDecoration(control, SWT.LEFT | SWT.TOP); decoration.setDescriptionText(message); FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault() .getFieldDecoration(FieldDecorationRegistry.DEC_ERROR); decoration.setImage(fieldDecoration.getImage()); return decoration; } public static Group newGroup(Composite parent, String text) { return newGroup(parent, text, 1); } public static Group newGroup(Composite parent, String text, int colspan) { Group group = new Group(parent, SWT.NONE); group.setText(text); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); gridData.horizontalSpan = colspan; group.setLayoutData(gridData); group.setLayout(new GridLayout(1, false)); return group; } public static Text newText(Composite parent) { return newText(parent, ""); } public static Text newText(Composite parent, String value) { Text text = new Text(parent, SWT.BORDER); text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); text.setText(value); return text; } public static Label newLabel(Composite parent, String text) { return newLabel(parent, text, 1); } public static Label newFillingLabel(Composite parent, String text) { return newFillingLabel(parent, text, 1); } public static Label newFillingLabel(Composite parent, String text, int colspan) { Label label = new Label(parent, SWT.WRAP); label.setText(text); GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); gridData.horizontalSpan = colspan; gridData.widthHint = 100; label.setLayoutData(gridData); return label; } public static Label newLabel(Composite parent, String text, int colspan) { Label label = new Label(parent, SWT.WRAP); label.setText(text); GridData gridData = new GridData(SWT.LEFT, SWT.TOP, false, false); gridData.horizontalSpan = colspan; label.setLayoutData(gridData); return label; } public static Label newLabel(Composite parent, String text, int colspan, int horizontalAlignment, int verticalAlignment) { Label label = new Label(parent, SWT.WRAP); label.setText(text); GridData gridData = new GridData(horizontalAlignment, verticalAlignment, false, false); gridData.horizontalSpan = colspan; label.setLayoutData(gridData); return label; } public static Link newLink(Composite composite, String message) { Link link = new Link(composite, SWT.WRAP); WebLinkListener webLinkListener = new WebLinkListener(); link.addListener(SWT.Selection, webLinkListener); link.setText(message); return link; } public static Combo newCombo(Composite parent) { return newCombo(parent, 1); } public static Combo newCombo(Composite parent, int colspan) { Combo combo = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY); GridData gridData = new GridData(SWT.FILL, SWT.CENTER, true, false); gridData.horizontalSpan = colspan; combo.setLayoutData(gridData); return combo; } public static Button newCheckbox(Composite parent, String text, int colspan) { Button button = new Button(parent, SWT.CHECK); button.setText(text); GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false); gridData.horizontalSpan = colspan; button.setLayoutData(gridData); return button; } public static UpdateValueStrategy newUpdateValueStrategy(ControlDecoration decoration, Button button) { UpdateValueStrategy strategy = new UpdateValueStrategy(); strategy.setAfterConvertValidator(new NotEmptyValidator(decoration, button)); return strategy; } protected Button newRadioButton(Composite parent, String text, int colspan) { return newRadioButton(parent, text, colspan, false); } protected Button newRadioButton(Composite parent, String text, int colspan, boolean selected) { return newRadioButton(parent, text, colspan, selected, selectionListener); } public static Button newRadioButton(Composite parent, String text, int colspan, boolean selected, SelectionListener selectionListener) { Button radioButton = new Button(parent, SWT.RADIO); radioButton.setText(text); GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false); gridData.horizontalSpan = colspan; radioButton.setLayoutData(gridData); radioButton.addSelectionListener(selectionListener); radioButton.setSelection(selected); return radioButton; } /** * Customize the link's layout data */ public void adjustLinkLayout(Link link, int colspan) { GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false); gridData.widthHint = 200; gridData.horizontalSpan = colspan; link.setLayoutData(gridData); } }
true
5125a0a14ea24704cc9b413191a75a52d4cc636d
Java
smallgross/daomeo
/src/main/java/com/dao/daomeo/JwtTokenUtils.java
UTF-8
582
2.046875
2
[]
no_license
package com.dao.daomeo; import javax.servlet.http.HttpServletRequest; import org.springframework.security.core.Authentication; /** * 根据请求令牌获取登录认证信息 * @author luo * */ public class JwtTokenUtils { public static Authentication getAuthenticaionFromToken(HttpServletRequest request) { Authentication authentication=null; //获取请求令牌 String token= JwtTokenUtils.getToken(request); return null; } private static String getToken(HttpServletRequest request) { return null; // TODO Auto-generated method stub } }
true
4b31f0b45ec774e7b05242b997715f2e1f0664ad
Java
smartcat-labs/cassandra-diagnostics
/cassandra-diagnostics-core/src/test/java/io/smartcat/cassandra/diagnostics/DiagnosticsTest.java
UTF-8
412
1.664063
2
[ "Apache-2.0" ]
permissive
package io.smartcat.cassandra.diagnostics; import org.junit.Test; import io.smartcat.cassandra.diagnostics.config.Configuration; public class DiagnosticsTest { @Test public void test_diagnostics_reload() { Diagnostics diagnostics = new Diagnostics(); diagnostics.activate(); Configuration configuration = diagnostics.getConfiguration(); diagnostics.reload(); } }
true
2b30b0ee0c34e3a93b34860e06c351af634f70cc
Java
kainlite/Paradigmas
/Java/IntegerList/test/integerlist/IntegerListNGTest.java
UTF-8
4,521
3.34375
3
[ "MIT" ]
permissive
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package integerlist; import static org.testng.Assert.*; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * * @author kainlite */ public class IntegerListNGTest { public IntegerListNGTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @BeforeMethod public void setUpMethod() throws Exception { } @AfterMethod public void tearDownMethod() throws Exception { } /** * Test of Add method, of class IntegerList. */ @Test public void testAdd() { System.out.println("Add"); int value = 10; IntegerList instance = new IntegerList(); instance.Add(value); assertEquals(instance.GetElement(0), value); } /** * Test of Sum method, of class IntegerList. */ @Test public void testSum() { System.out.println("Sum"); IntegerList instance = new IntegerList(); instance.Add(1); instance.Add(2); instance.Add(3); int expResult = 6; int result = instance.Sum(); assertEquals(result, expResult); } /** * Test of Reverse method, of class IntegerList. */ @Test public void testReverse() { System.out.println("Reverse"); IntegerList instance = new IntegerList(); IntegerList expResult = new IntegerList(); instance.Add(1); instance.Add(2); instance.Add(3); expResult.Add(3); expResult.Add(2); expResult.Add(1); instance.Reverse(); for (int i = 0; i < expResult.size(); i++) { assertEquals(instance.GetElement(i), expResult.GetElement(i)); } } /** * Test of GetElement method, of class IntegerList. */ @Test public void testGetElement() { System.out.println("GetElement"); int position = 0; IntegerList instance = new IntegerList(); instance.Add(0); int expResult = 0; int result = instance.GetElement(position); assertEquals(result, expResult); } /** * Test of RemoveElementsWithValue method, of class IntegerList. */ @Test public void testRemoveElementsWithValue() { System.out.println("RemoveElementsWithValue"); int value = 2; IntegerList instance = new IntegerList(); instance.Add(0); instance.Add(1); instance.Add(2); instance.Add(2); IntegerList expResult = new IntegerList(); expResult.Add(0); expResult.Add(1); instance.RemoveElementsWithValue(value); IntegerList result = instance; assertEquals(expResult.size(), 2); for (int i = 0; i < instance.size(); i++) { System.out.println(instance.GetElement(i)); } for (int i = 0; i < result.size(); i++) { assertEquals(result.GetElement(i), expResult.GetElement(i)); } } /** * Test of size method, of class IntegerList. */ @Test public void testSize() { System.out.println("size"); IntegerList instance = new IntegerList(); instance.Add(0); instance.Add(1); instance.Add(2); int expResult = 3; int result = instance.size(); assertEquals(result, expResult); } /** * Test of intrinsic method, of class IntegerList. */ @Test public void testIntrinsic() { System.out.println("intrinsic"); IntegerList a = new IntegerList(); IntegerList b = new IntegerList(); IntegerList expResult = new IntegerList(); a.Add(1); a.Add(2); a.Add(3); b.Add(0); b.Add(2); b.Add(3); expResult.Add(2); expResult.Add(3); IntegerList result = IntegerList.intrinsic(a, b); for (int i = 0; i < expResult.size(); i++) { assertEquals(result.GetElement(i), expResult.GetElement(i)); } } /** * Test of main method, of class IntegerList. */ @Test public void testMain() { // Not really needed.. } }
true
8ba46bb974376c1ec1e696b077d78cced0d670d2
Java
koprinski/Java-Tasks
/Task 2/src/com/omisoft/basic_java/objects/task3/Cleaner.java
UTF-8
551
3
3
[]
no_license
package com.omisoft.basic_java.objects.task3; /** * Creates class Cleaner which extends Staff * @author bkoprinski * */ public class Cleaner extends Staff { private String region; private int week; public Cleaner(String identNumber,int count) { super(identNumber, count); // TODO Auto-generated constructor stub } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public int getWeek() { return week; } public void setWeek(int week) { this.week = week; } }
true
9e70b49fbde513b61dbc75acb2071c95fe55b1fa
Java
xiaoshuaishuai/maxwell-kafka-enjoy
/src/main/java/com/ssx/maxwell/kafka/enjoy/common/tools/DbUtils.java
UTF-8
2,223
2.546875
3
[]
no_license
package com.ssx.maxwell.kafka.enjoy.common.tools; import lombok.extern.slf4j.Slf4j; import org.springframework.lang.Nullable; import java.sql.*; /** * @author: shuaishuai.xiao * @date: 2019/6/28 14:50 * @description: jdbc工具类 */ @Slf4j public class DbUtils { public static Connection connection(String className, String url, String user, String password) throws ClassNotFoundException, SQLException { Class.forName(className); return DriverManager.getConnection(url, user, password); } public static PreparedStatement preparedStatement(Connection connection, String sql) throws SQLException { return connection.prepareStatement(sql); } public static ResultSet resultSet(ExecuteSql executeSql, PreparedStatement preparedStatement) throws SQLException { return executeSql.ps(preparedStatement); } public static void closeConnection(@Nullable Connection con) { if (con != null) { try { con.close(); } catch (SQLException var2) { log.debug("Could not close JDBC Connection", var2); } catch (Throwable var3) { log.debug("Unexpected exception on closing JDBC Connection", var3); } } } public static void closeStatement(@Nullable Statement stmt) { if (stmt != null) { try { stmt.close(); } catch (SQLException var2) { log.trace("Could not close JDBC Statement", var2); } catch (Throwable var3) { log.trace("Unexpected exception on closing JDBC Statement", var3); } } } public static void closeResultSet(@Nullable ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException var2) { log.trace("Could not close JDBC ResultSet", var2); } catch (Throwable var3) { log.trace("Unexpected exception on closing JDBC ResultSet", var3); } } } @FunctionalInterface public interface ExecuteSql { ResultSet ps(PreparedStatement preparedStatement) throws SQLException; } }
true
fd2db1de8af2a77d9646741d1b57d0775b00c3a1
Java
SidorevichMaksim/uberfire
/uberfire-metadata/uberfire-metadata-backends/uberfire-metadata-backend-lucene/src/main/java/org/uberfire/metadata/backend/lucene/LuceneIndexEngine.java
UTF-8
8,642
1.820313
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2012 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uberfire.metadata.backend.lucene; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.IndexableField; import org.uberfire.metadata.engine.MetaIndexEngine; import org.uberfire.metadata.engine.MetaModelStore; import org.uberfire.metadata.model.KObject; import org.uberfire.metadata.model.KObjectKey; import org.uberfire.metadata.model.KProperty; import org.uberfire.metadata.model.schema.MetaObject; import org.uberfire.metadata.model.schema.MetaProperty; import org.uberfire.metadata.model.schema.MetaType; import static org.uberfire.commons.validation.Preconditions.*; public class LuceneIndexEngine implements MetaIndexEngine { private final LuceneSetup lucene; private final FieldFactory fieldFactory; private final MetaModelStore metaModelStore; private int batchMode = 0; public LuceneIndexEngine( final MetaModelStore metaModelStore, final LuceneSetup lucene, final FieldFactory fieldFactory ) { this.metaModelStore = checkNotNull( "metaModelStore", metaModelStore ); this.lucene = checkNotNull( "lucene", lucene ); this.fieldFactory = checkNotNull( "fieldFactory", fieldFactory ); } @Override public boolean freshIndex() { return lucene.freshIndex(); } @Override public synchronized void startBatchMode() { if ( batchMode < 0 ) { batchMode = 1; } else { batchMode++; } } @Override public void index( final KObject object ) { updateMetaModel( object ); lucene.indexDocument( object.getId(), newDocument( object ) ); commitIfNotBatchMode(); } private Document newDocument( final KObject object ) { final Document doc = new Document(); doc.add( new StringField( "id", object.getId(), Field.Store.YES ) ); doc.add( new StringField( "type", object.getType().getName(), Field.Store.YES ) ); doc.add( new TextField( "key", object.getKey(), Field.Store.YES ) ); doc.add( new StringField( "cluster.id", object.getClusterId(), Field.Store.YES ) ); doc.add( new StringField( "segment.id", object.getSegmentId(), Field.Store.YES ) ); final StringBuilder allText = new StringBuilder( object.getKey() ).append( '\n' ); for ( final KProperty<?> property : object.getProperties() ) { final IndexableField[] fields = fieldFactory.build( property ); for ( final IndexableField field : fields ) { doc.add( field ); if ( field instanceof TextField && !( property.getValue() instanceof Boolean ) ) { allText.append( field.stringValue() ).append( '\n' ); } } } doc.add( new TextField( FULL_TEXT_FIELD, allText.toString().toLowerCase(), Field.Store.NO ) ); return doc; } @Override public void index( final KObject... objects ) { for ( final KObject object : objects ) { index( object ); } } @Override public void rename( final KObjectKey from, final KObjectKey to ) { lucene.rename( from.getId(), to.getId() ); commitIfNotBatchMode(); } @Override public void delete( final KObjectKey objectKey ) { lucene.deleteIfExists( objectKey.getId() ); } @Override public void delete( final KObjectKey... objectsKey ) { final String[] ids = new String[ objectsKey.length ]; for ( int i = 0; i < ids.length; i++ ) { ids[ i ] = objectsKey[ i ].getId(); } lucene.deleteIfExists( ids ); } private synchronized void commitIfNotBatchMode() { if ( batchMode <= 0 ) { commit(); } } @Override public synchronized void commit() { batchMode--; if ( batchMode <= 0 ) { lucene.commit(); } } @Override public void dispose() { metaModelStore.dispose(); lucene.dispose(); } private void updateMetaModel( final KObject object ) { final MetaObject metaObject = metaModelStore.getMetaObject( object.getType().getName() ); if ( metaObject == null ) { metaModelStore.add( newMetaObect( object ) ); } else { for ( final KProperty property : object.getProperties() ) { final MetaProperty metaProperty = metaObject.getProperty( property.getName() ); if ( metaProperty == null ) { metaObject.addProperty( newMetaProperty( property ) ); } else { metaProperty.addType( property.getValue().getClass() ); if ( property.isSearchable() ) { metaProperty.setAsSearchable(); } } } metaModelStore.update( metaObject ); } } private MetaObject newMetaObect( final KObject object ) { final Set<MetaProperty> properties = new HashSet<MetaProperty>(); for ( final KProperty<?> property : object.getProperties() ) { properties.add( newMetaProperty( property ) ); } return new MetaObject() { private final Map<String, MetaProperty> propertyMap = new ConcurrentHashMap<String, MetaProperty>() {{ for ( final MetaProperty property : properties ) { put( property.getName(), property ); } }}; @Override public MetaType getType() { return object.getType(); } @Override public Collection<MetaProperty> getProperties() { return propertyMap.values(); } @Override public MetaProperty getProperty( final String name ) { return propertyMap.get( name ); } @Override public void addProperty( final MetaProperty metaProperty ) { if ( !propertyMap.containsKey( metaProperty.getName() ) ) { propertyMap.put( metaProperty.getName(), metaProperty ); } } }; } private MetaProperty newMetaProperty( final KProperty<?> property ) { return new MetaProperty() { private boolean isSearchable = property.isSearchable(); private Set<Class<?>> types = new CopyOnWriteArraySet<Class<?>>() {{ add( property.getValue().getClass() ); }}; @Override public String getName() { return property.getName(); } @Override public Set<Class<?>> getTypes() { return types; } @Override public boolean isSearchable() { return isSearchable; } @Override public void setAsSearchable() { this.isSearchable = true; } @Override public void addType( final Class<?> type ) { types.add( type ); } @Override public boolean equals( final Object obj ) { if ( obj == null ) { return false; } if ( !( obj instanceof MetaProperty ) ) { return false; } return ( (MetaProperty) obj ).getName().equals( getName() ); } @Override public int hashCode() { return getName().hashCode(); } }; } }
true
e48efd5d10a62c83623862ae95ef6f5336bfbdc6
Java
starlit010/lark
/lark-role/src/test/java/com/gome/lark/role/controller/TestUserRoleController.java
UTF-8
3,912
2.03125
2
[]
no_license
package com.gome.lark.role.controller; import com.gome.lark.common.utils.R; import com.gome.lark.role.entity.SysRoleEntity; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.junit.Assert; import org.junit.runner.RunWith; import org.springframework.boot.test.TestRestTemplate; import org.springframework.http.*; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Created by liuhui-ds9 on 2017/11/28. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring-mvc.xml", "classpath:spring-jdbc.xml", "classpath:spring-redis.xml", "classpath:spring-scheduler.xml"}) public class TestUserRoleController { private RestTemplate template = new TestRestTemplate(); /** * 信息 */ public void TestInfo() { try { String url = "http://localhost:" + 8081 + "/v1/masterdata/0501080060000116"; ArrayList<String> result = template.getForObject(url, ArrayList.class); Assert.assertTrue("通过主数据的标准化编码进行查询=>测试失败", result.size() > 0); System.err.println(result); } catch (Exception e) { e.printStackTrace(); } } /** * 保存 */ public void testSave() { try { String url = "http://localhost:" + 8081 + "/v1/masterdata"; Map<String, String> tBasicMasterData = new HashMap<String, String>(); tBasicMasterData.put("category", "100"); tBasicMasterData.put("code", "100"); int forObject = template.postForObject(url, tBasicMasterData, Integer.class); Assert.assertNotNull("创建一条主数据记录失败", forObject); Assert.assertTrue("创建一条主数据记录=>测试失败", forObject > 0); System.err.println(forObject); } catch (Exception e) { e.printStackTrace(); } } /** * 修改 */ public void testUpdate() { try { String reqJsonStr = "{\"category\":200,\"code\":\"200\", \"englishname\":\"200\",\"name\":\"200\"}"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(reqJsonStr, headers); String url = "http://localhost:" + 8081 + "/v1/masterdata/100"; ResponseEntity<String> exchange = template.exchange(url, HttpMethod.PUT, entity, String.class); String body = exchange.getBody(); Assert.assertNotNull("更改一条主数据记录失败", body); Assert.assertTrue("更改一条主数据记录=>测试失败", Integer.valueOf(body) > 0); System.err.println(exchange); } catch (Exception e) { e.printStackTrace(); } } /** * 删除 */ public void testDelete() { try { String url = "http://localhost:" + 8081 + "/v1/masterdata/200"; ResponseEntity<String> exchange = template.exchange(url, HttpMethod.DELETE, null, String.class); String body = exchange.getBody(); Assert.assertNotNull("删除一条主数据记录失败", body); Assert.assertTrue("删除一条主数据记录=>测试失败", Integer.valueOf(body) > 0); System.err.println(exchange); } catch (Exception e) { e.printStackTrace(); } } }
true
f1e94a68c6650271fbd467dd48a6e079c663fd0e
Java
china-university-mooc/Java-Web-Atguigu
/08-servlet/src/com/itutry/ConfigServlet.java
UTF-8
1,000
2.28125
2
[]
no_license
package com.itutry; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author itutry * @create 2020-05-16_10:50 */ public class ConfigServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Servlet name: " + getServletConfig().getServletName()); System.out.println("Init param names: " + getServletConfig().getInitParameterNames()); System.out.println("Init param username: " + getServletConfig().getInitParameter("username")); System.out.println("Init param url: " + getServletConfig().getInitParameter("url")); System.out.println("Init param url: " + getServletConfig().getServletContext()); System.out.println("保存context key1:" + getServletContext().getAttribute("key1")); } }
true
fcc77f4fbb94e22898e6877ccb93e8ebc9ac9adc
Java
Subrahmanyam83/Selenium
/src/test/java/com/My-Project/testscripts/9/TestWOWYSuperGymStats.java
WINDOWS-1252
8,463
2.375
2
[]
no_license
package com.tbb.testscripts.getfit; import java.lang.reflect.Method; import org.testng.Reporter; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.tbb.constants.UIRepository.WOWYSuperGymStats; import com.tbb.framework.BaseTest; import com.tbb.framework.ConfigFileReader; import com.tbb.pages.DashboardPage; import com.tbb.pages.HomePage; import com.tbb.pages.SignInPage; import com.tbb.pages.getfit.GetFitPage; import com.tbb.pages.getfit.WOWYSuperGymStatsPage; import com.tbb.pages.getfit.WowySuperGymPage; /** * * This test script contains test method(s) for Wowy SuperGym Stats page under Get-Fit module * @author Gaurav */ public class TestWOWYSuperGymStats extends BaseTest { @BeforeClass public void setUp() { startSeleniumServer(); } @BeforeMethod public void setUp(Method method) { createSeleniumInstance(method); } @AfterMethod public void stopSelenium() { stopSeleniumInstance(); } @AfterClass public void tearDown() { stopSeleniumServer(); } /** * This test verifies following: * Verifies count of 'Recent Top SuperGym Users' * Verifies presence of 'Go to Member Gallery' link * Verifies count of 'Top Workout Groups' * Verifies presence of 'Find more groups' link * Verifies count of 'Team Beachbody Programs' * Verifies presence of 'See all programs' link */ @Test public void testWOWYSuperGymStatsPage() { selenium.logComment("Creating link for 'Detailed Report' in TestNG/ReportNG Logs"); Reporter.log("<a href=" + "file://" + resultHtmlFileName + ">Detailed Report</a>"); selenium.logComment("################## Scope of this test method ######################"); selenium.logComment("Verifying whether are on Home page"); selenium.logComment("Clicking on 'Sign In' Link"); selenium.logComment("Entering valid username and password"); selenium.logComment("Clicking on 'Get Fit' link"); selenium.logComment("Clicking on 'WOWY SuperGym' Link from left side menu"); selenium.logComment("Clicking on 'More statistics' Link"); selenium.logComment("Verifying count of 'Recent Top SuperGym Users'"); selenium.logComment("Verifying presence of 'Go to Member Gallery' link"); selenium.logComment("Verifying count of 'Team Beachbody Programs'"); selenium.logComment("Verifying presence of 'See all programs' link"); selenium.logComment("Executing assertEmpty method"); selenium.logComment("################## Scope of this test method ######################"); selenium.logComment("Verifying whether are on Home page"); HomePage homePage = new HomePage(selenium); selenium.logComment("Clicking on 'Sign In' Link"); DashboardPage dashboardPage; if(ConfigFileReader.getConfigItemValue("selenium.browser").equals("*iexploreproxy") || ConfigFileReader.getConfigItemValue("selenium.browser").equals("*safariproxy")) { dashboardPage = homePage.clickSignInSpecial(ConfigFileReader.getConfigItemValue("tbb.username"), ConfigFileReader.getConfigItemValue("tbb.password")); } else { SignInPage signInPage = homePage.clickSignIn(); selenium.logComment("Entering valid username and password"); dashboardPage = signInPage.loginValidUser(ConfigFileReader.getConfigItemValue("tbb.username"), ConfigFileReader.getConfigItemValue("tbb.password")); } selenium.logComment("Clicking on 'Get Fit' link"); GetFitPage getFitPage = dashboardPage.clickGetFitLink(); selenium.logComment("Clicking on 'WOWY SuperGym' Link from left side menu"); WowySuperGymPage wowySuperGymPage = getFitPage.goToWowySupergymPage(); selenium.logComment("Clicking on 'More statistics' Link"); WOWYSuperGymStatsPage wOWYSuperGymStatsPage = wowySuperGymPage.clickMoreStatistics(); if(ConfigFileReader.getConfigItemValue("application.url").equals("www.teambeachbody.com")) { selenium.logComment("Verifying count of 'Recent Top SuperGym Users'"); assertTrue("Count of Recent Top SuperGym Users should be 5", wOWYSuperGymStatsPage.getRecentTopSuperGymUsersCount() == 5, selenium); } selenium.logComment("Verifying presence of 'Go to Member Gallery' link"); assertTrue("'Go to Member Gallery' link is not displayed", selenium.isElementPresent(WOWYSuperGymStats.GO_TO_MEMBER_GALLERY_LINK), selenium); selenium.logComment("Verifying count of 'Top Workout Groups'"); assertTrue("Count of Top Workout Groups should be 6", wOWYSuperGymStatsPage.getTopWorkoutGroupsCount() == 6, selenium); selenium.logComment("Verifying presence of 'Find more groups' link"); assertTrue("'Find more groups' link is not displayed", selenium.isElementPresent(WOWYSuperGymStats.FIND_MORE_GROUPS_LINK), selenium); selenium.logComment("Verifying count of 'Team Beachbody Programs'"); assertTrue("Count of Team Beachbody Programs should be 4", wOWYSuperGymStatsPage.getTeamBeachbodyProgramsCount() == 4, selenium); selenium.logComment("Verifying presence of 'See all programs' link"); assertTrue("'See all programs' link is not displayed", selenium.isElementPresent(WOWYSuperGymStats.SEE_ALL_PROGRAMS_LINK), selenium); selenium.logComment("Executing assertEmpty method"); emptyMessageBuilder(); } /** * This test verifies that user can send buddy invite to one of the Top Users. */ @Test public void testTopUserBuddyInvite() { selenium.logComment("Creating link for 'Detailed Report' in TestNG/ReportNG Logs"); Reporter.log("<a href=" + "file://" + resultHtmlFileName + ">Detailed Report</a>"); selenium.logComment("################## Scope of this test method ######################"); selenium.logComment("Verifying whether are on Home page"); selenium.logComment("Clicking on 'Sign In' Link"); selenium.logComment("Entering valid username and password"); selenium.logComment("Clicking on 'Get Fit' link"); selenium.logComment("Clicking on 'WOWY SuperGym' Link from left side menu"); selenium.logComment("Clicking on 'More statistics' Link"); selenium.logComment("Clicking on First top user's screen name"); selenium.logComment("Verifying whether 'Add as Buddy' button exists. If yes, click on it"); selenium.logComment("Executing assertEmpty method"); selenium.logComment("################## Scope of this test method ######################"); selenium.logComment("Verifying whether are on Home page"); HomePage homePage = new HomePage(selenium); selenium.logComment("Clicking on 'Sign In' Link"); DashboardPage dashboardPage; if(ConfigFileReader.getConfigItemValue("selenium.browser").equals("*iexploreproxy") || ConfigFileReader.getConfigItemValue("selenium.browser").equals("*safariproxy")) { dashboardPage = homePage.clickSignInSpecial(ConfigFileReader.getConfigItemValue("tbb.username"), ConfigFileReader.getConfigItemValue("tbb.password")); } else { SignInPage signInPage = homePage.clickSignIn(); selenium.logComment("Entering valid username and password"); dashboardPage = signInPage.loginValidUser(ConfigFileReader.getConfigItemValue("tbb.username"), ConfigFileReader.getConfigItemValue("tbb.password")); } selenium.logComment("Clicking on 'Get Fit' link"); GetFitPage getFitPage = dashboardPage.clickGetFitLink(); selenium.logComment("Clicking on 'WOWY SuperGym' Link from left side menu"); WowySuperGymPage wowySuperGymPage = getFitPage.goToWowySupergymPage(); selenium.logComment("Clicking on 'More statistics' Link"); WOWYSuperGymStatsPage wOWYSuperGymStatsPage = wowySuperGymPage.clickMoreStatistics(); selenium.logComment("Clicking on First top user's screen name"); selenium.click(WOWYSuperGymStats.RECENT_FIRST_TOP_USER); selenium.logComment("Verifying whether 'Add as Buddy' button exists. If yes, click on it"); assertTrue("'Add as a Buddy' button not present", selenium.waitForElementPresent(WOWYSuperGymStats.RECENT_TOP_USER_PROFILE_POP_UP_ADD_AS_A_BUDDY_BUTTON), selenium ); selenium.click(WOWYSuperGymStats.RECENT_TOP_USER_PROFILE_POP_UP_ADD_AS_A_BUDDY_BUTTON); selenium.click(WOWYSuperGymStats.RECENT_TOP_USER_PROFILE_POP_UP_NO_BUTTON); /* selenium.logComment("Clicking on 'Close' link"); selenium.click("css=div.profile-table.popup div.profile-area-close");*/ selenium.logComment("Executing assertEmpty method"); emptyMessageBuilder(); } }
true
2449165c890b9d44ff1b40a1dca0d0e7aa9f719a
Java
TTFlyzebra/RtmpCamera
/RtmpCamera/src/main/java/com/flyzebra/camera/media/VideoEncoder.java
UTF-8
6,172
2.328125
2
[]
no_license
/** * FileName: VideoEncoder * Author: FlyZebra * Email:flycnzebra@gmail.com * Date: 2023/6/23 15:06 * Description: */ package com.flyzebra.camera.media; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaFormat; import com.flyzebra.utils.FlyLog; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicBoolean; public class VideoEncoder implements Runnable { private MediaCodec codec = null; private final Object codecLock = new Object(); private final AtomicBoolean is_codec_init = new AtomicBoolean(false); private Thread mOutThread = null; private VideoEncoderCB mCallBack; public VideoEncoder(VideoEncoderCB cb) { mCallBack = cb; } public boolean isCodecInit() { return is_codec_init.get(); } public void initCodec(String mimeType, int width, int height, int bitrate) { synchronized (codecLock) { try { MediaFormat format = MediaFormat.createVideoFormat(mimeType, width, height); format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar); format.setInteger(MediaFormat.KEY_BIT_RATE, bitrate); format.setInteger(MediaFormat.KEY_FRAME_RATE, 25); format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 3); format.setInteger(MediaFormat.KEY_BITRATE_MODE, MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR); codec = MediaCodec.createEncoderByType(mimeType); codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); codec.start(); is_codec_init.set(true); mOutThread = new Thread(this); mOutThread.start(); } catch (Exception e) { FlyLog.e(e.toString()); } } } public void inYuvData(byte[] data, int size, long pts) { synchronized (codecLock) { if (!is_codec_init.get() || data == null || size <= 0) return; int inIndex = codec.dequeueInputBuffer(200000); if (inIndex < 0) { FlyLog.e("VideoEncoder codec->dequeueInputBuffer inIdex=%d error!", inIndex); return; } ByteBuffer buffer = codec.getInputBuffer(inIndex); if (buffer == null) { FlyLog.e("VideoEncoder codec->getInputBuffer inIdex=%d error!", inIndex); return; } buffer.put(data, 0, size); codec.queueInputBuffer(inIndex, 0, size, pts, 0); } } public void releaseCodec() { synchronized (codecLock) { is_codec_init.set(false); try { mOutThread.join(); } catch (InterruptedException e) { FlyLog.e(e.toString()); } codec.stop(); codec.release(); codec = null; } } @Override public void run() { MediaCodec.BufferInfo mBufferInfo = new MediaCodec.BufferInfo(); while (is_codec_init.get()) { int outputIndex = codec.dequeueOutputBuffer(mBufferInfo, 200000); switch (outputIndex) { case MediaCodec.INFO_TRY_AGAIN_LATER: break; case MediaCodec.INFO_OUTPUT_FORMAT_CHANGED: try { MediaFormat format = codec.getOutputFormat(); String mini = format.getString(MediaFormat.KEY_MIME); if (MediaFormat.MIMETYPE_VIDEO_AVC.equals(mini)) { ByteBuffer spsBuffer = format.getByteBuffer("csd-0"); spsBuffer.position(0); int spsLen = spsBuffer.remaining(); byte[] sps = new byte[spsLen]; spsBuffer.get(sps, 0, spsLen); ByteBuffer ppsBuffer = format.getByteBuffer("csd-1"); ppsBuffer.position(0); int ppsLen = ppsBuffer.remaining(); byte[] pps = new byte[ppsLen]; ppsBuffer.get(pps, 0, ppsLen); mCallBack.notifySpsPps(sps, spsLen, pps, ppsLen); } else { ByteBuffer bufer = format.getByteBuffer("csd-0"); bufer.position(0); int vspLen = bufer.remaining(); byte[] vsp = new byte[vspLen]; bufer.get(vsp, 0, vspLen); mCallBack.notifyVpsSpsPps(vsp, vspLen); } } catch (Exception e) { FlyLog.e(e.toString()); } break; case MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED: break; default: if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) == 0 && mBufferInfo.size != 0) { ByteBuffer outputBuffer = codec.getOutputBuffer(outputIndex); outputBuffer.position(mBufferInfo.offset + 4); int size = outputBuffer.remaining(); byte[] data = new byte[size]; outputBuffer.get(data, 0, size); //long pts = System.nanoTime()/1000L; MediaFormat format = codec.getOutputFormat(); String mini = format.getString(MediaFormat.KEY_MIME); if (MediaFormat.MIMETYPE_VIDEO_AVC.equals(mini)) { mCallBack.notifyAvcData(data, size, mBufferInfo.presentationTimeUs); } else { mCallBack.notifyHevcData(data, size, mBufferInfo.presentationTimeUs); } } codec.releaseOutputBuffer(outputIndex, false); break; } } } }
true
5167b6cf91040e8887e8eea8cfbf22e00bde29b7
Java
IgorFranovic/FunctionPlotter
/FunctionPlotter/src/Window.java
UTF-8
9,652
2.71875
3
[]
no_license
import java.awt.Color; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import java.util.LinkedList; import java.util.Random; import javax.swing.JFrame; import javax.swing.JLabel; public class Window extends JFrame { // code for the GUI of the program public static Color[] colorArray; public static TextAreaCustom JTextAreaFunction; public static TextAreaCustom JTextAreaMinX; public static TextAreaCustom JTextAreaMaxX; public static TextAreaCustom JTextAreaMinY; public static TextAreaCustom JTextAreaMaxY; //public static JSlider zoomSlider; //public static int zoomPercentage = 0; static Random random; public static JButtonCustom JButtonDraw; public static JButtonCustom JButtonUndo; public static JButtonCustom JButtonLink; public static JButtonCustom JButtonClear; public static JButtonCustom JButtonInfo; public static JButtonCustom JButtonInfoImage; public static JButtonCustom JButtonResetZoom; public static JLabel JLabelTitle; public static JLabel JLabelValuesX; public static JLabel JLabelValuesY; public static JLabel JLabelZoom; public static JLabel JLabelAuthors; public static JLabel JLabelCodeLink; public static boolean JButtonInfoPressed = false; public static LinkedList<Function> FunctionList = new LinkedList<Function>(); public static Plotter plotter; private int plotterDimension; public static MouseInput mouseInput; public static TextAreaCustom [] textAreaArray; public static int textAreaSelected = 0; private double xMin, xMax, yMin, yMax; public Window(String windowName, int WIDTH, int HEIGHT) { random = new Random(); colorArray = new Color[6]; colorArray[0] = Color.yellow; colorArray[1] = Color.blue; colorArray[2] = Color.GRAY; colorArray[3] = Color.BLACK; colorArray[4] = Color.GREEN; colorArray[5] = Color.DARK_GRAY; this.setSize(new Dimension(WIDTH, HEIGHT)); this.setTitle(windowName); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); this.setLayout(null); this.setResizable(false); //CHANGE INIT FUNCTION HERE String initFunction = "x^2"; FunctionList.add(new Function(initFunction, Color.red)); //JTextAreaFunction JTextAreaFunction = new TextAreaCustom(initFunction, "Enter your function here! ", 5, 1.5, 10, 1); this.add(JTextAreaFunction); //JTextAreaMinX JTextAreaMinX = new TextAreaCustom("-5", "MinX", 7.5, 6, 2, 0.5); this.add(JTextAreaMinX); //JTextAreaMaxX JTextAreaMaxX = new TextAreaCustom("5", "MaxX", 10.5, 6, 2, 0.5); this.add(JTextAreaMaxX); //JTextAreaMinY JTextAreaMinY = new TextAreaCustom("-5", "MinY", 7.5, 9, 2, 0.5); this.add(JTextAreaMinY); //JTextAreaMaxY JTextAreaMaxY = new TextAreaCustom("5", "MaxY", 10.5, 9, 2, 0.5); this.add(JTextAreaMaxY); //JButtonDraw JButtonDraw = new JButtonCustom("JButtonDraw", "resources/imgDraw.png", "Draw the function!"); JButtonDraw.setBounds(140, 120, 120, 40); this.add(JButtonDraw); //JButtonUndo JButtonUndo = new JButtonCustom("JButtonUndo", "resources/imgUndo.png", "Undo last draw!"); JButtonUndo.setBounds(140, 600, 120, 40); this.add(JButtonUndo); //JButtonLink JButtonLink = new JButtonCustom("JButtonLink", "resources/imgGit.png", "Visit code location!"); JButtonLink.setBounds(150, 750, 100, 50); this.add(JButtonLink); //JButtonClear JButtonClear = new JButtonCustom("JButtonClear", "resources/imgClear.png", "Left click to clear function field. Right click to clear x and y values!"); JButtonClear.setBounds(330, 70, 20, 20); this.add(JButtonClear); //JButtonInfo JButtonInfo = new JButtonCustom("JButtonInfo", "resources/imgInfo.png", "Click here for instructions!"); JButtonInfo.setBounds(175, 405, 40, 40); this.add(JButtonInfo); //JButtonInfoImage JButtonInfoImage = new JButtonCustom("JButtonInfoImage", "resources/imgInfoFunctions.png", ""); JButtonInfoImage.setBounds(47, 265, 600, 700); JButtonInfoImage.setVisible(false); this.add(JButtonInfoImage); //JButtonResetZoom JButtonResetZoom = new JButtonCustom("JButtonResetZoom", "resources/imgResetZoom.png", "Reset the position Preset!"); JButtonResetZoom.setBounds(175, 505, 40, 40); this.add(JButtonResetZoom); // change initFunction on line 75 //JSlider //zoomSlider = new JSlider(JSlider.HORIZONTAL, 1, 10, 1); //zoomSlider.setBounds(50, 500, 300, 40); //this.add(zoomSlider); //Plotter plotterDimension = 800; this.xMin = Double.parseDouble(JTextAreaMinX.getText()); this.xMax = Double.parseDouble(JTextAreaMaxX.getText()); this.yMin = Double.parseDouble(JTextAreaMinY.getText()); this.yMax = Double.parseDouble(JTextAreaMaxY.getText()); plotter = new Plotter(initFunction, plotterDimension, plotterDimension, xMin, xMax, yMin, yMax); plotter.setBounds(400, 0, 1200, 800); plotter.setPreferredSize(new Dimension(plotterDimension, plotterDimension)); this.add(plotter); mouseInput = new MouseInput(plotter); plotter.addMouseListener(mouseInput); plotter.addMouseWheelListener(mouseInput); plotter.addMouseMotionListener(mouseInput); //JLabels JLabelTitle = new JLabel("Function Plotter"); JLabelTitle.setFont(new Font("serif", 1, 25)); JLabelTitle.setForeground(new Color(0, 132, 204)); JLabelTitle.setBounds(115, 0, 250, 50); this.add(JLabelTitle); JLabelValuesX = new JLabel("(min X, max X)"); JLabelValuesX.setFont(new Font("helvetica", 1, 12)); JLabelValuesX.setForeground(Color.BLACK); JLabelValuesX.setBounds(160, 200, 250, 50); this.add(JLabelValuesX); JLabelValuesY = new JLabel("(min Y, max Y)"); JLabelValuesY.setFont(new Font("helvetica", 1, 12)); JLabelValuesY.setForeground(Color.BLACK); JLabelValuesY.setBounds(160, 320, 250, 50); this.add(JLabelValuesY); JLabelZoom = new JLabel("Zoom"); JLabelZoom.setFont(new Font("helvetica", 1, 12)); JLabelZoom.setForeground(Color.BLACK); JLabelZoom.setBounds(180, 465, 250, 50); // this.add(JLabelZoom); JLabelAuthors = new JLabel("Created by Nikola Pižurica and Igor Franović"); JLabelAuthors.setFont(new Font("arial", 1, 10)); JLabelAuthors.setForeground(Color.GRAY); JLabelAuthors.setBounds(80, 715, 250, 50); this.add(JLabelAuthors); textAreaArray = new TextAreaCustom[5]; textAreaArray[0] = JTextAreaFunction; textAreaArray[1] = JTextAreaMinX; textAreaArray[2] = JTextAreaMaxX; textAreaArray[3] = JTextAreaMinY; textAreaArray[4] = JTextAreaMaxY; setIcon("resources/applicationIcon.png"); this.setVisible(true); } public static class ButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent event) { String actionCommand = event.getActionCommand(); switch(actionCommand) { case "JButtonDraw" : { String function = JTextAreaFunction.getText(); //Don't draw the same function twice in a row if(FunctionList.size() > 0 && function.equalsIgnoreCase(FunctionList.get(FunctionList.size()-1).function)) break; Color col = Color.red; if(FunctionList.size() > 0) col = colorArray[(FunctionList.size() - 1) % colorArray.length]; FunctionList.add(new Function(function, col)); double xmin = Double.parseDouble(JTextAreaMinX.getText()); double xmax = Double.parseDouble(JTextAreaMaxX.getText()); double ymin = Double.parseDouble(JTextAreaMinY.getText()); double ymax = Double.parseDouble(JTextAreaMaxY.getText()); mouseInput.setAll(xmin, xmax + 0.1, ymin, ymax + 0.1); plotter.reset(function, xmin, xmax + 0.1, ymin, ymax + 0.1); //plotter.repaint(); mouseInput.zoomOut(xmin, ymin); mouseInput.zoomIn(xmin, ymin); } break; case "JButtonUndo" : { if(FunctionList.size() > 0) { FunctionList.removeLast(); plotter.repaint(); } } break; case "JButtonLink" : { openWebpage("https://github.com/IgorFranovic/FunctionPlotter"); } break; case "JButtonClear" : { JTextAreaFunction.setText(""); JTextAreaFunction.grabFocus(); } break; case "JButtonInfo" : { JButtonInfoImage.setVisible(!JButtonInfoImage.isVisible()); } break; case "JButtonResetZoom" : { double xmin = -5; double xmax = 5.1; double ymin = -5; double ymax = 5.1; Window.textAreaArray[1].setText("-5"); Window.textAreaArray[2].setText("5"); Window.textAreaArray[3].setText("-5"); Window.textAreaArray[4].setText("5"); plotter.reset(plotter.getFunction(), xmin, xmax, ymin, ymax); plotter.repaint(); mouseInput.setAll(xmin, xmax, ymin, ymax); plotter.reset(plotter.getFunction(), xmin, xmax, ymin, ymax); //plotter.repaint(); mouseInput.zoomOut(xmin, ymin); mouseInput.zoomIn(xmin, ymin); } break; } } public static void openWebpage(String urlString) { try { Desktop.getDesktop().browse(new URL(urlString).toURI()); } catch (Exception e) { e.printStackTrace(); } } } public void setIcon(String icon) { setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource(icon))); } }
true
b1b2927c9291972ef232e75f223ec99b6c48aec2
Java
AlexiSkyline/Example-Spring-and-Hibernate
/src/main/java/com/springsimplepasos/universidad/universidadbackend/repositorios/PersonaRepository.java
UTF-8
866
2.234375
2
[]
no_license
package com.springsimplepasos.universidad.universidadbackend.repositorios; import com.springsimplepasos.universidad.universidadbackend.modelo.entidades.Persona; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.NoRepositoryBean; import java.util.Optional; @NoRepositoryBean public interface PersonaRepository extends CrudRepository<Persona, Integer> { @Query( "select p from Persona p where p.nombre = ?1 and p.apellido = ?2" ) Optional<Persona> buscarPorNombreYApellido( String nombre, String apellido ); @Query( "select p from Persona p where p.dni = ?1" ) Optional<Persona> buscarPorDni( String dni ); @Query( "select p from Persona p where p.apellido like %?1%" ) Iterable<Persona> buscarPersonaPorApellido( String apellido ); }
true
a42bb0e9d24fb767388f05d1db9c70d6040db893
Java
TechieFrogs-Warriors/JavaBasics
/ANSWINI/src/Wipro_AdvancedPrograms2/SmallestPositiveNumber.java
UTF-8
1,821
4.03125
4
[]
no_license
package Wipro_AdvancedPrograms2; import java.util.Scanner; //To find smallest positive number from an array of elements public class SmallestPositiveNumber { public static void main(String[] args) { //Reading input from user Scanner sc = new Scanner(System.in); //take an array System.out.println("Enter the size of the array"); int[] inpArray = new int[sc.nextInt()]; //Enter elements into array for(int i=0;i<inpArray.length;i++) { inpArray[i] = sc.nextInt(); } //calling method that perform logic to find positive missing number System.out.println("Missing positive number is: "+missingNumber(inpArray)); sc.close(); } //Logic method that finds positive missing number public static int missingNumber(int[] inpArray) { //length of input array int len = inpArray.length; for (int i=0;i<len;i++) { //when the i'th element is not i while (inpArray[i] != i + 1) { //no need to swap when ith element is out of range [0,len](below 0 and above length of array) if (inpArray[i] <= 0 || inpArray[i] >= len) { break; } //checking for duplicate elements if(inpArray[i]==inpArray[inpArray[i]-1]) { break; } //swapping the elements int temp = inpArray[i]; inpArray[i] = inpArray[temp - 1]; inpArray[temp - 1] = temp; } } //printing loop for (int i=0;i<len;i++) { if (inpArray[i] != (i + 1)) { return (i + 1); } } return (len + 1); } }
true
03a83f7cc58004082301580689f9de43cdf0f1a4
Java
daijiangping/SHOP1.0
/src/com/bigJD/others/dao/impl/KeyWordDao.java
UTF-8
2,152
2.53125
3
[]
no_license
package com.bigJD.others.dao.impl;/** * Created by Administrator on 2016/12/16. */ import com.bigJD.others.dao.IKeyWordDao; import com.bigJD.others.entity.KeyWord; import com.bigJD.product.entity.Product; import org.hibernate.SessionFactory; import java.util.List; public class KeyWordDao implements IKeyWordDao { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } /** * 保存关键字 * @param keyWord * @return */ @Override public Integer saveKeyWord(KeyWord keyWord) { sessionFactory.getCurrentSession().save(keyWord); return 0; } /** * 查询关键字是否存在s * @param keyWord * @return */ @Override public KeyWord queryKeyWord(KeyWord keyWord) { return (KeyWord) sessionFactory.getCurrentSession().createQuery("from KeyWord k where k.name=?") .setParameter(0,keyWord.getName()).uniqueResult(); } /** * 更新关键字(点击量) * @param keyWord * @return */ @Override public Integer updataKeyWord(KeyWord keyWord) { sessionFactory.getCurrentSession().update(keyWord); return 0; } /** * 按照关键字名查找 * @param name * @return */ @Override public KeyWord queryKeyWordByName(String name) { return (KeyWord) sessionFactory.getCurrentSession().createQuery("from KeyWord k where k.name=?") .setParameter(0,name).uniqueResult(); } /** * 模糊查询关键字 * @param name * @return */ @Override public List<Product> fuzzyQuery(String name) { String hql = "select id,name from Product as key where key.name like '%"+name+"%'"; return sessionFactory.getCurrentSession().createQuery(hql).list(); } @Override public List<Product> keywordFindProducts(String name) { String hql = "from Product as p where p.name like '%"+name+"%'"; return sessionFactory.getCurrentSession().createQuery(hql).list(); } }
true
ec3188ff0a9124351b38dd54eafe18d2e37e83bf
Java
tnunes2002/LavoroTPS
/Lavori javaFX/platform game/com/karzal/javafxgame/menu/Colors.java
UTF-8
631
2.265625
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 com.karzal.javafxgame.menu; import javafx.scene.paint.Color; public class Colors { public static final Color MENU_BG = Color.rgb(0,0,0); public static final Color TEXT_COLOR = Color.rgb(255, 255, 255); public static final Color SELECTED_TEXT_COLOR = Color.rgb(0, 0, 0); public static final Color SELECTED_BG_COLOR = Color.rgb(255, 255, 255); public static final Color PRESSED_TEXT_COLOR = Color.rgb (200, 10, 10); }
true
e598993733ce861bb485e6c61c9dc79d952af8a4
Java
MHTabak/spring5-recipe-app
/src/main/java/guru/springframework/services/RecipeService.java
UTF-8
505
2.15625
2
[]
no_license
package guru.springframework.services; // Lecture 108 Initial version // Lecture 200 - Add findById() // Lecture 204 - Add saveRecipeCommand() // Lecture 206 - Add findCommandById() import guru.springframework.commands.RecipeCommand; import guru.springframework.domain.Recipe; import java.util.Set; public interface RecipeService { Set<Recipe> getRecipes(); Recipe findById(Long l); RecipeCommand findCommandById(Long l); RecipeCommand saveRecipeCommand(RecipeCommand command); }
true
8642909e83845886479511e9daea6375fa654b3b
Java
MasterJoyHunan/DesiginPattren
/src/strategy/Test.java
UTF-8
352
2.5
2
[]
no_license
package strategy; import java.util.List; public class Test { public static void main(String[] args) { String people = "father"; MusicListContext mc = new MusicListContext(people); List<String> musicList = mc.getMusicList(); for (String music: musicList) { System.out.println(music); } } }
true
f326e9f70ff8b41f36ab9f22ad62d31660e1ef64
Java
hechuan73/LeetCode
/src/items/IncreasingOrderSearchTree_897.java
UTF-8
1,623
3.96875
4
[]
no_license
package items; /** * @author hechuan */ public class IncreasingOrderSearchTree_897 { /** * Relink the input tree without extra space * * @param root the root node of the tree. * @return the root node of increasing tree */ public TreeNode increasingBST1(TreeNode root) { return increasingBST(root, null); } private TreeNode increasingBST(TreeNode root, TreeNode prev) { // if this null node was a left child, tail is its parent // if this null node was a right child, tail is its parent's parent if (root == null) { return prev; } // recursive call, traversing left while passing in the current node as tail TreeNode res = increasingBST(root.left, root); // set left child to null root.left = null; // we set the current node's right child to be tail // what is tail? this part is important // if the current node is a left child, tail will be its parent // else if the current node is a right child, tail will be its parent's parent root.right = increasingBST(root.right, prev); // throughout the whole algorithm, res is the leaf of the leftmost path in the original tree // its the smallest node and thus will be the root of the modified tree return res; } /** * Rebuild the increasing tree with inorder traversal and storing nodes in list. * * @param root the root node of the tree. * @return the root node of increasing tree */ public TreeNode increasingBST2(TreeNode root) { return root; } }
true
de51ce68922d56e57fbb6a44b2884460498d2198
Java
BBoldt/ModularArmour
/src/main/java/chbachman/armour/register/Module.java
UTF-8
661
2.15625
2
[]
no_license
package chbachman.armour.register; public interface Module { /** * Called during preinit. See {@link cpw.mods.fml.common.event.FMLPreInitializationEvent} */ public void preInit(); /** * Called during init. See {@link cpw.mods.fml.common.event.FMLInitializationEvent} */ public void init(); /** * Called during postInit. See {@link cpw.mods.fml.common.event.FMLPostInitializationEvent} */ public void postInit(); /** * Called when you should create and register your upgrades. */ public void registerUpgrades(); /** * Called when you should register your recipes for your upgrades. */ public void registerUpgradeRecipes(); }
true
916d5c35c84bc24a4cb5c714a39753521cd569a7
Java
liufengking/demo_study
/demo_java/src/main/java/com/roby/demo/log/Slf4j.java
UTF-8
747
2.484375
2
[]
no_license
package com.roby.demo.log; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Slf4j { static Logger logger = LoggerFactory.getLogger(Slf4j.class); /** * @param args */ public static void main(String[] args) { if(logger.isTraceEnabled()){ logger.trace("---This is Slf4j trace message---"); } if(logger.isDebugEnabled()){ logger.debug("This is Slf4j debug message"); } if(logger.isInfoEnabled()){ logger.info("This is Slf4j info message"); } if(logger.isWarnEnabled()){ logger.warn("This is Slf4j warn message"); } if(logger.isErrorEnabled()){ logger.error("This is Slf4j error message"); } } }
true
8b2fa857cc856a8b60c40c05b1e7b3b1c15f437c
Java
kabulov/code
/history/code/solutions/acmp_ru/solutions/_375_manual.java
UTF-8
1,438
3.34375
3
[]
no_license
import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) throws IOException { out = new PrintWriter("output.txt"); in = new Scanner(new File("input.txt")); BigInteger from = in.nextBigInteger(); BigInteger to = in.nextBigInteger(); String number = in.next(); BigInteger ten = BigInteger.ZERO; int len = number.length(); for (int i = 0; i < len; i++) { ten = ten.multiply(from).add(c2d(number.charAt(i))); } Stack<Character> stack = new Stack<Character>(); BigInteger zero = BigInteger.ZERO; if (ten.compareTo(zero) == 0) stack.push('0'); else while (ten.compareTo(zero) > 0) { stack.push(d2c(ten.mod(to))); ten = ten.divide(to); } while (!stack.isEmpty()) { out.print(stack.pop()); } out.close(); } static BigInteger c2d(final char c) { if ('0' <= c && c <= '9') return new BigInteger(new Integer(c - 48).toString()); else return new BigInteger(new Integer(c - 55).toString()); } static Character d2c(final BigInteger n) { int d = Integer.parseInt(n.toString()); if (0 <= d && d <= 9) return new Character((char)(d + 48)); else return new Character((char)(d + 55)); } static PrintWriter out; static Scanner in; }
true
969763b195bcfd2863c2537e9f528c084defad40
Java
LFMyGitHub/MyProject
/commonlibrary/src/main/java/com/example/commonlibrary/http/InterceptorUtil.java
UTF-8
4,958
2.609375
3
[]
no_license
package com.example.commonlibrary.http; import android.util.Log; import com.example.commonlibrary.config.AppConstant; import java.io.IOException; import java.util.List; import java.util.Locale; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; /** * 拦截器 */ public class InterceptorUtil { private static String TAG = "InterceptorUtil"; /** * 日志拦截器 * @return */ public static Interceptor LogInterceptor() { return new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Log.e(TAG, "request:" + request.toString()); long t1 = System.nanoTime(); okhttp3.Response response = chain.proceed(chain.request()); long t2 = System.nanoTime(); Log.e(TAG, String.format(Locale.getDefault(), "Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers())); okhttp3.MediaType mediaType = response.body().contentType(); String content = response.body().string(); Log.e(TAG, "response body:" + content); return response.newBuilder() .body(okhttp3.ResponseBody.create(mediaType, content)) .build(); } }; } /** * 请求拦截器根据API配置header类型动态设置baseurl * * @return */ public static Interceptor HeaderInterceptor() { return new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { //获取请求request Request mRequest = chain.request(); //获取请求request的创建者builder实例 Request.Builder builder = mRequest.newBuilder(); //从request中获取headers List<String> headerValues = mRequest.headers("api"); String host = ""; if (headerValues != null && headerValues.size() > 0) { //如果有这个header,先将配置的header删除 builder.removeHeader("api"); //匹配获得新的BaseUrl String headerValue = headerValues.get(0); switch (headerValue) { case "news": host = AppConstant.BASE_API; break; } String scheme; int len = host.length(); if (host.startsWith("https://")) { int pos = host.indexOf("https://") + "https://".length(); host = host.substring(pos, len); } else { int pos = host.indexOf("http://") + "http://".length(); host = host.substring(pos, len); } scheme = "https"; //从request中获取原有的HttpUrl实例oldHttpUrl HttpUrl oldHttpUrl = mRequest.url(); //重建新的HttpUrl,修改需要修改的url部分 HttpUrl newFullUrl = oldHttpUrl .newBuilder() .addQueryParameter("key", AppConstant.APP_JOKE_KEY)//笑话api接口都需要添加appkey .scheme(scheme) .host(host) .build(); //然后返回一个response至此结束修改 return chain.proceed(builder.url(newFullUrl).build()); } else { return chain.proceed(mRequest); } } }; } /** * 请求拦截器 * 添加公共请求头 * * @return */ public static Interceptor RequestInterceptor() { return new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { //获取请求request Request request = chain.request(); Request.Builder builder = request.newBuilder(); builder.header("content-type", "application/json;charset=utf-8"); return chain.proceed(builder.build()); } }; } /** * 响应拦截器 * * @return */ public static Interceptor ResponseInterceptor() { return new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { //获取请求request Request request = chain.request(); return chain.proceed(request); } }; } }
true
bb8d487fc2fdda6c8611ccb12ceaa4017bfe0c79
Java
kopwei/kthsedshomework
/DAIIAHW3_Q4/src/agents/AIDMessageContent.java
UTF-8
861
2.40625
2
[]
no_license
package agents; import jade.core.AID; import jade.util.leap.Serializable; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.util.HashSet; /** * * @author Ricky */ public class AIDMessageContent implements Serializable{ private HashSet<AID> aidCollection = null; private AID aid = null; private int bestPrice = 0; public void setAIDCollection(HashSet<AID> aidCol) { aidCollection = aidCol; } public HashSet<AID> getAIDCollection() { return aidCollection; } public void setTheAID(AID aid) { this.aid = aid; } public AID getTheAID() { return aid; } public void setBestPrice(int price) { bestPrice = price; } public int getBestPrice() { return bestPrice; } }
true
d23bd431cf24d85ca3f58c6854b61dbc6412c24f
Java
jonasgreen/Onofflist
/src/com/jg/onofflist/server/repository/ListItemRepository.java
UTF-8
669
2.1875
2
[]
no_license
package com.jg.onofflist.server.repository; import com.jg.core.server.dao.Dao; import com.jg.core.server.repository.Repository; import com.jg.onofflist.client.model.OnOffListItem; import com.jg.onofflist.server.jdo.OnOffListItemJDO; /** * */ public class ListItemRepository extends Repository<OnOffListItemJDO, OnOffListItem, CreateListItem> { public ListItemRepository(){ this(new Dao(OnOffListItemJDO.class), new ListItemConverter()); } public ListItemRepository(Dao dao, ListItemConverter con) { super(dao, con); } @Override public Class<OnOffListItem> getRepositoryType() { return OnOffListItem.class; } }
true
2c1f2ea10bb4f583878ce8cb23fe05fdd168f824
Java
ThunderKeg/leetcode
/test/main/java/n17/TestProblem17.java
UTF-8
234
1.75
2
[]
no_license
package n17; import org.junit.Test; import java.util.Arrays; public class TestProblem17 { @Test public void test17() { Solution s17 = new Solution(); System.err.println(s17.letterCombinations("")); } }
true
0ef62ce39bcf4429d66607c5a48179af075a01da
Java
mijibox/openfin-java-adapter
/src/main/java/com/mijibox/openfin/bean/ChannelConnectionOptions.java
UTF-8
674
2.140625
2
[ "Apache-2.0" ]
permissive
package com.mijibox.openfin.bean; import javax.json.JsonValue; public class ChannelConnectionOptions extends FinJsonBean { private JsonValue payload; private Boolean wait; public ChannelConnectionOptions() { } public ChannelConnectionOptions(boolean wait, JsonValue payload) { this.wait = wait; this.payload = payload; } public JsonValue getPayload() { return payload; } public void setPayload(JsonValue payload) { this.payload = payload; } public Boolean getWait() { return wait; } public void setWait(Boolean wait) { this.wait = wait; } public boolean isWait() { return this.wait == null ? true : this.wait.booleanValue(); } }
true
5c98152475e11b4f385446b43ed2475b5a6036ac
Java
bianxiaobin/XCloudBizLogic
/src/com/xc/bl/car/service/impl/CarHelpDocServiceImpl.java
UTF-8
634
1.992188
2
[]
no_license
package com.xc.bl.car.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.xc.bl.car.dao.ICarHelpDocDao; import com.xc.bl.car.service.ICarHelpDocService; import com.xc.bl.entities.CarHelpDoc; @Service("carHelpDocService") public class CarHelpDocServiceImpl implements ICarHelpDocService { @Autowired private ICarHelpDocDao dao; @Override public CarHelpDoc getCarHelpDocById(int carGradeId) { return dao.getCarHelpDocById(carGradeId); } @Override public List<CarHelpDoc> getDocAll() { return dao.getDocAll(); } }
true
4bd8d3dcae607bf97a884439b370bac0ef50528a
Java
Appdynamics/aws-ec2-monitoring-extension
/src/main/java/com/appdynamics/extensions/aws/ec2/EC2MetricsProcessor.java
UTF-8
6,550
1.734375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2018. AppDynamics LLC and its affiliates. * All Rights Reserved. * This is unpublished proprietary source code of AppDynamics LLC and its affiliates. * The copyright notice above does not evidence any actual or intended publication of such source code. * */ package com.appdynamics.extensions.aws.ec2; import static com.appdynamics.extensions.aws.Constants.METRIC_PATH_SEPARATOR; import com.amazonaws.services.cloudwatch.AmazonCloudWatch; import com.amazonaws.services.cloudwatch.model.DimensionFilter; import com.amazonaws.services.cloudwatch.model.Metric; import com.appdynamics.extensions.aws.config.IncludeMetric; import com.appdynamics.extensions.aws.dto.AWSMetric; import com.appdynamics.extensions.aws.ec2.providers.EC2InstanceNameProvider; import com.appdynamics.extensions.aws.metric.AccountMetricStatistics; import com.appdynamics.extensions.aws.metric.MetricStatistic; import com.appdynamics.extensions.aws.metric.NamespaceMetricStatistics; import com.appdynamics.extensions.aws.metric.RegionMetricStatistics; import com.appdynamics.extensions.aws.metric.StatisticType; import com.appdynamics.extensions.aws.metric.processors.MetricsProcessor; import com.appdynamics.extensions.aws.metric.processors.MetricsProcessorHelper; import com.appdynamics.extensions.logging.ExtensionsLoggerFactory; import com.google.common.base.Strings; import org.slf4j.Logger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.LongAdder; /** * @author Florencio Sarmiento */ public class EC2MetricsProcessor implements MetricsProcessor { private static final Logger LOGGER = ExtensionsLoggerFactory.getLogger(EC2MetricsProcessor.class); private static final String NAMESPACE = "AWS/EC2"; private static final String DIMENSIONS = "InstanceId"; private static final String INSTANCE = "Instance"; private List<IncludeMetric> includeMetrics; private String ec2Instance; public EC2MetricsProcessor(List<IncludeMetric> includeMetrics, String ec2Instance) { this.includeMetrics = includeMetrics; this.ec2Instance = ec2Instance; } public List<AWSMetric> getMetrics(AmazonCloudWatch awsCloudWatch, String accountName, LongAdder awsRequestsCounter) { List<DimensionFilter> dimensions = new ArrayList<DimensionFilter>(); DimensionFilter dimensionFilter = new DimensionFilter(); dimensionFilter.withName(DIMENSIONS); if (!Strings.isNullOrEmpty(ec2Instance)) { dimensionFilter.withValue(ec2Instance); } dimensions.add(dimensionFilter); EC2MetricPredicate metricFilter = new EC2MetricPredicate(accountName); return MetricsProcessorHelper.getFilteredMetrics(awsCloudWatch, awsRequestsCounter, NAMESPACE, includeMetrics, dimensions, metricFilter); } public StatisticType getStatisticType(AWSMetric metric) { return MetricsProcessorHelper.getStatisticType(metric.getIncludeMetric(), includeMetrics); } public List<com.appdynamics.extensions.metrics.Metric> createMetricStatsMapForUpload(NamespaceMetricStatistics namespaceMetricStats) { EC2InstanceNameProvider ec2InstanceNameProvider = EC2InstanceNameProvider.getInstance(); List<com.appdynamics.extensions.metrics.Metric> stats = new ArrayList<>(); if (namespaceMetricStats != null) { for (AccountMetricStatistics accountStats : namespaceMetricStats.getAccountMetricStatisticsList()) { for (RegionMetricStatistics regionStats : accountStats.getRegionMetricStatisticsList()) { for (MetricStatistic metricStat : regionStats.getMetricStatisticsList()) { String metricPath = createMetricPath(accountStats.getAccountName(), regionStats.getRegion(), metricStat, ec2InstanceNameProvider); if (metricStat.getValue() != null) { Map<String, Object> metricProperties = new HashMap<>(); AWSMetric awsMetric = metricStat.getMetric(); IncludeMetric includeMetric = awsMetric.getIncludeMetric(); metricProperties.put("alias", includeMetric.getAlias()); metricProperties.put("multiplier", includeMetric.getMultiplier()); metricProperties.put("aggregationType", includeMetric.getAggregationType()); metricProperties.put("timeRollUpType", includeMetric.getTimeRollUpType()); metricProperties.put("clusterRollUpType", includeMetric.getClusterRollUpType()); metricProperties.put("delta", includeMetric.isDelta()); com.appdynamics.extensions.metrics.Metric metric = new com.appdynamics.extensions.metrics.Metric(includeMetric.getName(), Double.toString(metricStat.getValue()), metricStat.getMetricPrefix() + metricPath, metricProperties); stats.add(metric); } else { LOGGER.debug(String.format("Ignoring metric [ %s ] which has value null", metricPath)); } } } } } return stats; } public String getNamespace() { return NAMESPACE; } private String createMetricPath(String accountName, String region, MetricStatistic metricStatistic, EC2InstanceNameProvider ec2InstanceNameProvider) { AWSMetric awsMetric = metricStatistic.getMetric(); IncludeMetric includeMetric = awsMetric.getIncludeMetric(); Metric metric = awsMetric.getMetric(); String instanceId = metric.getDimensions().get(0).getValue(); String instanceName = ec2InstanceNameProvider.getInstanceName(accountName, region, instanceId); StringBuilder metricPath = new StringBuilder(accountName) .append(METRIC_PATH_SEPARATOR) .append(region) .append(METRIC_PATH_SEPARATOR) .append(INSTANCE) .append(METRIC_PATH_SEPARATOR) .append(instanceName) .append(METRIC_PATH_SEPARATOR) .append(includeMetric.getName()); return metricPath.toString(); } }
true
cc9495cceb434415e1e0956c971a100bcb014c1e
Java
sonbyungjun/bitcamp-java-2018-12
/java-spring-webmvc/src/main/java/bitcamp/app1/Controller04_5.java
UTF-8
1,400
2.28125
2
[]
no_license
package bitcamp.app1; import java.io.PrintWriter; import java.util.Date; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/c04_5") public class Controller04_5 { // http://localhost:8080/java-spring-webmvc/app1/c04_5/h1?model=sonata&capacity=5&auto=true&createdDate=2019-4-19 @GetMapping("h1") @ResponseBody public void handler1( PrintWriter out, String model, int capacity, boolean auto, Date createdDate) { out.printf("model=%s\n", model); out.printf("capacity=%s\n", capacity); out.printf("auto=%s\n", auto); out.printf("createdDate=%s\n", createdDate); } // http://localhost:8080/java-spring-webmvc/app1/c04_5/h2?car=sonata,5,true,2019-4-19 @GetMapping("h2") @ResponseBody public void handler2( PrintWriter out, @RequestParam("car") Car car) { out.println(car); } // http://localhost:8080/java-spring-webmvc/app1/c04_5/h3?engine=bitengine,3500,16 @GetMapping("h3") @ResponseBody public void handler3( PrintWriter out, @RequestParam("engine") Engine engine) { out.println(engine); } }
true
8ab5a993b969d727cb0139e8ba4d1039566dfddf
Java
ouniali/bpel-g
/bpel-g/org.activebpel.rt.bpel/src/main/java/org/activebpel/rt/bpel/def/validation/expr/functions/AeGetLinkStatusFunctionValidator.java
UTF-8
3,031
1.84375
2
[]
no_license
//$Header: /Development/AEDevelopment/projects/org.activebpel.rt.bpel/src/org/activebpel/rt/bpel/def/validation/expr/functions/AeGetLinkStatusFunctionValidator.java,v 1.2 2008/01/25 21:01:16 dvilaverde Exp $ ///////////////////////////////////////////////////////////////////////////// //PROPRIETARY RIGHTS STATEMENT //The contents of this file represent confidential information that is the //proprietary property of Active Endpoints, Inc. Viewing or use of //this information is prohibited without the express written consent of //Active Endpoints, Inc. Removal of this PROPRIETARY RIGHTS STATEMENT //is strictly forbidden. Copyright (c) 2002-2007 All rights reserved. ///////////////////////////////////////////////////////////////////////////// package org.activebpel.rt.bpel.def.validation.expr.functions; import org.activebpel.rt.bpel.AeMessages; import org.activebpel.rt.bpel.def.AeActivityDef; import org.activebpel.rt.bpel.def.util.AeDefUtil; import org.activebpel.rt.expr.def.AeScriptFuncDef; import org.activebpel.rt.expr.validation.AeExpressionValidationResult; import org.activebpel.rt.expr.validation.IAeExpressionValidationContext; /** * Validates the bpws standard getLinkStatus function */ public class AeGetLinkStatusFunctionValidator extends AeAbstractFunctionValidator { /** * @see org.activebpel.rt.expr.validation.functions.IAeFunctionValidator#validate(org.activebpel.rt.expr.def.AeScriptFuncDef, org.activebpel.rt.expr.validation.AeExpressionValidationResult, org.activebpel.rt.expr.validation.IAeExpressionValidationContext) */ public void validate(AeScriptFuncDef aScriptFunction, AeExpressionValidationResult aResult, IAeExpressionValidationContext aContext) { int numArgs = aScriptFunction.getArgs().size(); if (numArgs != 1) { addError(aResult, AeMessages.getString("AeAbstractFunctionValidator.ERROR_INCORRECT_ARGS_NUMBER"), //$NON-NLS-1$ new Object[]{aScriptFunction.getName(), 1, numArgs, aResult.getParseResult().getExpression()}); } else if (!(aScriptFunction.getArgument(0) instanceof String)) { addError(aResult, AeMessages.getString("AeAbstractFunctionValidator.ERROR_INCORRECT_ARG_TYPE"), //$NON-NLS-1$ new Object[]{aScriptFunction.getName(), "", "String", aResult.getParseResult().getExpression()});//$NON-NLS-1$//$NON-NLS-2$ } else { AeActivityDef def = AeDefUtil.getActivityDef(aContext.getBaseDef()); String linkName = aScriptFunction.getStringArgument(0); if (!def.getTargetLinkNames().contains(linkName)) { addError(aResult, AeMessages.getString("AeGetLinkStatusFunctionValidator.LINK_DOES_NOT_EXIST_ERROR"), //$NON-NLS-1$ new Object[]{linkName, aResult.getParseResult().getExpression()}); } } } }
true
4961ab601b31dbc4029f475592cce08b21126b75
Java
huanghua119/Tasker
/src/com/chuanshida/tasker/ui/MainActivity.java
UTF-8
7,383
2.0625
2
[]
no_license
package com.chuanshida.tasker.ui; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnFocusChangeListener; import android.widget.Button; import com.chuanshida.tasker.CustomApplcation; import com.chuanshida.tasker.R; import com.chuanshida.tasker.fragment.FindFragment; import com.chuanshida.tasker.fragment.FriendsFragment; import com.chuanshida.tasker.fragment.MeFragment; import com.chuanshida.tasker.fragment.NewTaskFragment; import com.chuanshida.tasker.fragment.OutBoxFragment; import com.chuanshida.tasker.fragment.TaskFragment; import com.chuanshida.tasker.util.SharePreferenceUtil; public class MainActivity extends BaseActivity implements OnFocusChangeListener { private Button[] mTabs; private Fragment[] fragments; private int mIndex; private int mCurrentTabIndex; private TaskFragment mCalendarFrament; private FriendsFragment mFriendsFrament; private FindFragment mFindFrament; private MeFragment mMeFragment; private NewTaskFragment mNewTaskFragment; private OutBoxFragment mOutBoxFragment; private SharePreferenceUtil mSp = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initTab(); if (mSp == null) { mSp = CustomApplcation.getInstance().getSpUtil(); } } private void initView() { mTabs = new Button[4]; mTabs[0] = (Button) findViewById(R.id.btn_calendar); mTabs[1] = (Button) findViewById(R.id.btn_friends); mTabs[2] = (Button) findViewById(R.id.btn_find); mTabs[3] = (Button) findViewById(R.id.btn_me); } private void initTab() { mCalendarFrament = new TaskFragment(); mFriendsFrament = new FriendsFragment(); mFindFrament = new FindFragment(); mMeFragment = new MeFragment(); mNewTaskFragment = new NewTaskFragment(); mOutBoxFragment = new OutBoxFragment(); fragments = new Fragment[] { mCalendarFrament, mFriendsFrament, mFindFrament, mMeFragment, mNewTaskFragment, mOutBoxFragment }; FragmentTransaction trx = getFragmentManager().beginTransaction(); trx.add(R.id.fragment_container, mCalendarFrament); trx.commit(); getFragmentManager().beginTransaction().show(mCalendarFrament).commit(); mTabs[0].setSelected(true); mCurrentTabIndex = 0; } /** * button点击事件 * * @param view */ public void onTabSelect(View view) { switch (view.getId()) { case R.id.btn_calendar: mIndex = 0; break; case R.id.btn_friends: mIndex = 1; break; case R.id.btn_find: mIndex = 2; break; case R.id.btn_me: mIndex = 3; break; } if (mCurrentTabIndex != mIndex) { FragmentTransaction trx = getFragmentManager().beginTransaction(); /* * if (mCurrentTabIndex == 4 && mIndex == 0 ) { * trx.setCustomAnimations(R.anim.fragment_left_out, * R.anim.fragment_left_in); } */ trx.hide(fragments[mCurrentTabIndex]); if (mCurrentTabIndex >= 4) { trx.remove(fragments[mCurrentTabIndex]); } if (!fragments[mIndex].isAdded()) { trx.add(R.id.fragment_container, fragments[mIndex]); } trx.show(fragments[mIndex]).commit(); } if (mCurrentTabIndex == 4 || mCurrentTabIndex == 5) { mCurrentTabIndex = 0; } if (mCurrentTabIndex < 4) { mTabs[mCurrentTabIndex].setSelected(false); mTabs[mIndex].setSelected(true); } mCurrentTabIndex = mIndex; } @Override protected void onResume() { super.onResume(); } @Override public void finish() { mRunFinishAnim = false; super.finish(); } private static long firstTime; /** * 连续按两次返回键就退出 */ @Override public void onBackPressed() { if (firstTime + 2000 > System.currentTimeMillis()) { super.onBackPressed(); } else { ShowToastOld(R.string.pass_exit); } firstTime = System.currentTimeMillis(); } @Override protected void onDestroy() { super.onDestroy(); } public void onLogout(View v) { userManager.logout(); startActivity(new Intent(this, LoginChooseActivity.class)); overridePendingTransition(R.anim.left_in, R.anim.left_out); finish(); } @Override public void onFocusChange(View v, boolean hasFocus) { } public void toNewTaskFragment() { FragmentTransaction trx = getFragmentManager().beginTransaction(); /* * trx.setCustomAnimations(R.anim.fragment_left_in, * R.anim.fragment_left_out); */ mIndex = 4; trx.hide(fragments[mCurrentTabIndex]); mNewTaskFragment.setArguments(null); if (!fragments[mIndex].isAdded()) { trx.add(R.id.fragment_container, fragments[mIndex]); } trx.show(fragments[mIndex]).commit(); if (mCurrentTabIndex < 4) { mTabs[mCurrentTabIndex].setSelected(false); mTabs[0].setSelected(true); } mCurrentTabIndex = mIndex; } public void toNewTaskFragment(Bundle bundle) { FragmentTransaction trx = getFragmentManager().beginTransaction(); mIndex = 4; trx.hide(fragments[mCurrentTabIndex]); mNewTaskFragment.setArguments(bundle); if (!fragments[mIndex].isAdded()) { trx.add(R.id.fragment_container, fragments[mIndex]); } trx.show(fragments[mIndex]).commit(); if (mCurrentTabIndex < 4) { mTabs[mCurrentTabIndex].setSelected(false); mTabs[0].setSelected(true); } mCurrentTabIndex = mIndex; } public void exitFragment() { FragmentTransaction trx = getFragmentManager().beginTransaction(); /* * trx.setCustomAnimations(R.anim.fragment_left_out, * R.anim.fragment_left_in); } */ mIndex = 0; trx.hide(fragments[mCurrentTabIndex]); trx.remove(fragments[mCurrentTabIndex]); if (!fragments[mIndex].isAdded()) { trx.add(R.id.fragment_container, fragments[mIndex]); } trx.show(fragments[mIndex]).commit(); mCurrentTabIndex = mIndex; } public void toOutBoxFragment() { FragmentTransaction trx = getFragmentManager().beginTransaction(); mIndex = 5; trx.hide(fragments[mCurrentTabIndex]); if (!fragments[mIndex].isAdded()) { trx.add(R.id.fragment_container, fragments[mIndex]); } trx.show(fragments[mIndex]).commit(); if (mCurrentTabIndex < 4) { mTabs[mCurrentTabIndex].setSelected(false); mTabs[0].setSelected(true); } mCurrentTabIndex = mIndex; } public void onCellClick(View v) { } }
true
3f42a40674a3e419daf07ee64a54ab0a2336f63f
Java
hepx/proDs
/src/android/apk/utils/IconUtil.java
UTF-8
2,832
2.640625
3
[]
no_license
package android.apk.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import android.apk.parser.APK; import android.apk.parser.APKParser; import com.web4j.util.FileUtil; /** * 根据APK路径获取APK的ICON * * @author hztom * */ public class IconUtil { public static void main(String[] args) { try{ String apkPath = "C:/Users/xixi/Desktop/newsreader-wyyy_news.apk"; File file=new File(apkPath); APK apk=APKParser.getApk(file); FileUtil.writeFile(file, apk.getFilename(), "D:/apache-tomcat-6.0.33/webapps/attachments/market/apps/"+apk.getPackageName()); String path = IconUtil.getIcon(file, "icon.png", "D:/apache-tomcat-6.0.33/webapps/attachments/market/apps/com.netease.newsreader.activity/icon_72.png"); System.out.println(path); }catch(Exception e){ e.printStackTrace(); } } /** * * @param apkFile * @param iconName * @param exportIconPath * @return */ public static String getIcon(File apkFile, String iconName, String exportIconPath) { FileInputStream in = null; FileOutputStream out = null; ZipInputStream zipin = null; String apkImg = ""; try { in = new FileInputStream(apkFile); zipin = new ZipInputStream(in); ZipEntry entry = null; while ((entry = zipin.getNextEntry()) != null) { String name = entry.getName().toLowerCase(); if (name.endsWith("/" + iconName) && name.contains("drawable") && name.contains("res")) { apkImg = exportIconPath; out = new FileOutputStream(new File(exportIconPath)); byte[] buff = new byte[1024]; int n = 0; while ((n = zipin.read(buff, 0, buff.length)) != -1) { out.write(buff, 0, n); } break; } else if (name.endsWith("/app_" + iconName) && name.contains("drawable") && name.contains("res")) { apkImg = exportIconPath; out = new FileOutputStream(new File(exportIconPath)); byte[] buff = new byte[1024]; int n = 0; while ((n = zipin.read(buff, 0, buff.length)) != -1) { out.write(buff, 0, n); } break; } } out = null; zipin.closeEntry(); entry = null; } catch (Exception e) { e.printStackTrace(); } finally { try { if (zipin != null) { zipin.close(); } if (in != null) { in.close(); } } catch (Exception e) { e.printStackTrace(); } } return apkImg; } /** * 根据APK路径获取APK的ICON * * @param srcApkPath * @param iconName * @param exportIconPath * apk图标输出的地址 * @return */ public static String getIcon(String srcApkPath, String iconName, String exportIconPath) { File apkFile = new File(srcApkPath); return getIcon(apkFile, iconName, exportIconPath); } }
true
3a41988db5b8b0237846dd1f0d97501494b73666
Java
cozos/emrfs-hadoop
/com/amazon/ws/emr/hadoop/fs/shaded/com/google/common/collect/ForwardingMap$StandardValues.java
UTF-8
532
1.632813
2
[]
no_license
package com.amazon.ws.emr.hadoop.fs.shaded.com.google.common.collect; import com.amazon.ws.emr.hadoop.fs.shaded.com.google.common.annotations.Beta; @Beta public class ForwardingMap$StandardValues extends Maps.Values<K, V> { public ForwardingMap$StandardValues(ForwardingMap paramForwardingMap) { super(paramForwardingMap); } } /* Location: * Qualified Name: com.amazon.ws.emr.hadoop.fs.shaded.com.google.common.collect.ForwardingMap.StandardValues * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
9724f7dc9e4f10d820f1ca4b9eff10a1f9ba438f
Java
langjiangit/mmorpg_server
/mmorpg_server_legend/src/main/java/com/qworldr/mmorpg/logic/skill/manager/SkillManager.java
UTF-8
1,462
2.109375
2
[]
no_license
package com.qworldr.mmorpg.logic.skill.manager; import com.qworldr.mmorpg.logic.player.Player; import com.qworldr.mmorpg.logic.player.enu.RoleType; import com.qworldr.mmorpg.logic.player.resource.PlayerInitializationResource; import com.qworldr.mmorpg.logic.skill.entity.SkillEntity; import com.qworldr.mmorpg.logic.skill.resource.SkillResource; import com.qworldr.mmorpg.provider.EntityProvider; import com.qworldr.mmorpg.provider.ResourceProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @author wujiazhen */ @Component public class SkillManager { @Autowired private EntityProvider<SkillEntity,Long> skillEntityProvider; @Autowired private ResourceProvider<PlayerInitializationResource, RoleType> playerInitializationResourceProvider; @Autowired private ResourceProvider<SkillResource,Integer> skillResourceProvider; public SkillEntity getSkillEntity(Player player) { return skillEntityProvider.loadAndCreate(player.getId(),id->{ SkillEntity skillEntity = new SkillEntity(); skillEntity.setId(id); //设置初始技能 PlayerInitializationResource playerInitializationResource = playerInitializationResourceProvider.get(player.getPlayerEntity().getRole()); skillEntity.setSkillIds(playerInitializationResource.getSkillIds()); return skillEntity; }); } }
true
d17df5adbb0212ce18a220752568b64b855866c9
Java
adrianwenger/ALDA-Aufgaben
/Aufgabe2/src/graph/GraphTraversion.java
UTF-8
3,323
3.359375
3
[]
no_license
package graph; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * * @author philippschultheiss * @param <V> */ public final class GraphTraversion<V> { private GraphTraversion() { } /** * @param <V> Vertex Type * @param g graph * @param s start Vertex * @return LinkedList besucht */ public static <V> List<V> depthFirstSearch(final Graph<V> g, final V s) { List<V> besucht = new LinkedList<>(); return depthFirstSearchR(s, g, besucht); } private static <V> List<V> depthFirstSearchR(final V s, final Graph<V> g, List<V> besucht) { if (besucht.size() == g.getNumberOfVertexes()) { return besucht; } besucht.add(s); for (V vertex : g.getAdjacentVertexList(s)) { if (!besucht.contains(vertex)) { besucht = depthFirstSearchR(vertex, g, besucht); } } return besucht; } /** * * @param <V> Vertex Type * @param g graph * @param s vertex value * @return linkedList */ public static <V> List<V> breadthFirstSearch(final Graph<V> g, final V s) { List<V> besucht = new LinkedList<>(); return breadthFirstSearch(s, g, besucht); } /** * * @param <V> * @param s * @param g * @param besucht * @return */ private static <V> List<V> breadthFirstSearch(V s, final Graph<V> g, final List<V> besucht) { Queue<V> schlange = new LinkedList<>(); schlange.add(s); while (!schlange.isEmpty()) { s = schlange.remove(); if (besucht.contains(s)) { continue; } besucht.add(s); for (V vertex : g.getAdjacentVertexList(s)) { if (!besucht.contains(vertex)) { schlange.add(vertex); } } } return besucht; } /** * @param <V> Vertex type * @param g graph * @return LinkedList */ public static <V> List<V> topologicalSort(final DirectedGraph<V> g) { List<V> ts = new LinkedList<>(); int inDegree[] = new int[g.getNumberOfVertexes()]; Queue<V> q = new LinkedList<>(); int i = 0; // for every vertex... for (V vertex : g.getVertexList()) { inDegree[i] = g.getPredecessorVertexList(vertex).size(); if (inDegree[i] == 0) { q.add(vertex); } i++; } V v; int j = 0; while (!q.isEmpty()) { v = q.remove(); ts.add(v); for (V vertex : g.getSuccessorVertexList(v)) { j = 0; for (V vertex2 : g.getVertexList()) { if (vertex2 == vertex) { break; } j++; } if (--inDegree[j] == 0) { q.add(vertex); } } } if (ts.size() != g.getNumberOfVertexes()) { // Graph with cycle throw new IllegalStateException("Zyklus gefunden!"); } else { return ts; } } }
true
41f96c6c7d68e1db7666cce22dd1e3c5347f329d
Java
FridaErik/MCNetwork
/MCNetwork/src/com/TDDD27/MCNetwork/client/MessageForm.java
ISO-8859-1
8,575
2.140625
2
[]
no_license
package com.TDDD27.MCNetwork.client; import com.TDDD27.MCNetwork.shared.MCUser; import com.TDDD27.MCNetwork.shared.Message; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException; import com.google.gwt.user.client.rpc.InvocationException; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.VerticalPanel; /** * Klass fr att skriva och skicka meddelande * Anvnds av andra klasser och fristende. * @author Frida * */ public class MessageForm extends FormPanel implements ValueChangeHandler { private static TestServiceAsync testService = GWT.create(TestService.class); private MCNetwork parent; private MCUser loggedInUser=null; private Grid grid = new Grid(5, 2); private TextArea textAreaMeddelande = new TextArea(); private HTML textHTMLMeddelande = new HTML("<p>Meddelande</p>", true); private HTML errorMeddelande = new HTML("", true); private HTML goToReciever; private MCUser mySender=null; private MCUser myResiver=null; private Boolean myPrivate; private HTML confirmation = new HTML("", true); private VerticalPanel frame = new VerticalPanel(); private String prevMsg; /** * Skapar ett message form med mottagare, sndare och om meddelande r privat eller ej. * Den har ven koppling till MCNetwork fr att kunna pverka vad anvndaren ser p ett enkelt stt. * @param sender anvndaren som skickar meddelande * @param resiever anvndare som tar emot meddelande * @param theparent MCnetwork (huvudklassen) * @param priv Om meddelande ska vara privat eller inte */ public MessageForm(final MCUser sender, final MCUser resiever, MCNetwork theparent, final Boolean priv, String prevMsg){ this.mySender=sender; this.myResiver=resiever; this.myPrivate=priv; parent=theparent; this.prevMsg=prevMsg; Boolean large=true; setUpGUI(large); //HISTORY History.addValueChangeHandler(this); String initToken = History.getToken(); if(initToken.length()==0){ History.newItem("messageform"); System.out.println("HistoryToken = 0"); } History.newItem("messageform"); History.fireCurrentHistoryState(); //HISTORY } /** * Skapar ett message form med mottagare, sndare och om meddelande r privat eller ej. * Den har ven koppling till MCNetwork fr att kunna pverka vad anvndaren ser p ett enkelt stt. * @param senderid id fr anvndaren som skickar meddelande * @param resieverid id fr anvndare som tar emot meddelande * @param theparent MCnetwork (huvudklassen) * @param priv Om meddelande ska vara privat eller inte */ public MessageForm(final long senderid, final Long resiverid, MCNetwork theparent, final Boolean priv, String prevMsg){ getResiver(resiverid); getSender(senderid);//Fixar det grafiska this.myPrivate=priv; parent=theparent; this.prevMsg=prevMsg; } /** * Stter anvndaren som ska ta emot meddelandet * om man bara hade tillgng till id * @param resiverid */ private void getResiver(Long resiverid) { Boolean isResiver=true; getUser(resiverid, isResiver); } /** * Stter anvndaren som ska skicka meddelandet * om man bara hade tillgng till id * @param senderid */ private void getSender(long senderid) { Boolean isResiver=false; getUser(senderid, isResiver); } /** * Hmtar en anvndare och stter den till antingen anvndare eller mottagare * @param id * @param isResiver om anvndaren r mottagare av meddelandet * s stts isResiver till true. */ private void getUser(Long id, final Boolean isResiver) { final Long userid = id; AsyncCallback<MCUser> callback = new AsyncCallback<MCUser>() { @Override public void onFailure(Throwable caught) { System.out.println("failure in getUser"); try { throw caught; } catch (IncompatibleRemoteServiceException e) { // this client is not compatible with the server; cleanup and refresh the // browser } catch (InvocationException e) { // the call didn't complete cleanly } catch (Throwable e) { // last resort -- a very unexpected exception } } @Override public void onSuccess(MCUser result) { if(isResiver){ myResiver=result; System.out.println("Resiver satt"); } else{ mySender=result; System.out.println("Sender satt"); } if(mySender!=null && myResiver!=null){ System.out.println("Redo fr GUI"); Boolean large=false; setUpGUI(large); } } }; testService.getUser(id, callback); } /** * Skapar det grafiska som krvs fr att ta in den data som behvs fr att skicka meddelande * @param large Om det ska vara en stor eller liten message form, beror p var den anvnds. * Om true s fr den en storlek lmplig fr att anvndas ensam och false skapar en som * r lagom stor fr att anvndas p en sida med andra GUI:s */ private void setUpGUI(Boolean large) { HTML title=null; if(myPrivate==true && large){ title = new HTML("<H1>Skicka privat meddelande till "+myResiver.getFirstName()+"</H1>", true); frame.add(title); }else if(large){ title = new HTML("<H1>Skriv n&arintg;t p&aring;"+myResiver.getFirstName()+" v&auml;gg</H1>", true); frame.add(title); } goToReciever=setUpReciverLink(myResiver); if(large){ textAreaMeddelande.setSize("500px", "200px"); }else{ textAreaMeddelande.setSize("350px", "125px"); } confirmation.setVisible(false); grid.setWidget(0, 0, confirmation); grid.setWidget(1, 1, errorMeddelande); grid.setWidget(1, 0, textAreaMeddelande); Button sendBtn = new Button("Skicka"); grid.setWidget(2, 0, sendBtn); grid.setWidget(2, 1, goToReciever); if(prevMsg!=null){ textAreaMeddelande.setText("\n \n"+'"'+prevMsg+'"'); } frame.add(grid); this.add(frame); sendBtn.addClickHandler(new ClickHandler(){ @Override public void onClick(ClickEvent event){ String msgString = textAreaMeddelande.getText(); System.out.println(msgString); if (testService == null) { testService = GWT.create(TestService.class); } // Set up the callback object. AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() { @Override public void onFailure(Throwable caught) { System.out.println("failure nr person ska skapa meddelande...(Userview)"); } @Override public void onSuccess(Boolean result) { textAreaMeddelande.setText(""); confirmation.setHTML("Meddelandet har skickats till "+myResiver.getFirstName()); confirmation.setStyleName("confirmation"); confirmation.setVisible(true); } }; Message msg= new Message(mySender.getId(), myResiver.getId(), msgString, myPrivate); testService.storeMsg(msg, callback); } }); } /** * Skapar en lnk till anvndarens som man ska skicka till. * @param resiver anvndaren som ska lnkas till * @return Returnerar en HTML som funkar som en lnk */ private HTML setUpReciverLink(final MCUser resiver) { HTML toReturn = new HTML("", true); toReturn.setHTML(" G&aring; till "+ resiver.getFirstName()+":s sida >>"); toReturn.setStyleName("Clickable"); ClickHandler resieverClickHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { SendToUserPage(resiver); } private void SendToUserPage(MCUser resiver) { UserView centerwidget = new UserView(resiver, parent); parent.centerPanel.clear(); parent.centerPanel.add(centerwidget); } }; toReturn.addClickHandler(resieverClickHandler); return toReturn; } @Override public void onValueChange(ValueChangeEvent event) { if (event.getValue().equals("messageform")){ parent.centerPanel.clear(); parent.centerPanel.add(this); } } }
true
8fd6799cb065dab05cd1a4440c8ab1963789086a
Java
depCloser/bld-applets
/src/main/java/com/bld/applets/domain/AppletsFeedback.java
UTF-8
1,374
2.265625
2
[]
no_license
package com.bld.applets.domain; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * 反馈对象 applets_feedback * * @author tyx * @date 2021-03-10 */ public class AppletsFeedback extends BaseEntity { private static final long serialVersionUID = 1L; /** $column.columnComment */ private Long id; /** 内容 */ private String content; /** 用户id */ private Long userId; public AppletsFeedback setId(Long id) { this.id = id; return this; } public Long getId() { return id; } public AppletsFeedback setContent(String content) { this.content = content; return this; } public String getContent() { return content; } public AppletsFeedback setUserId(Long userId) { this.userId = userId; return this; } public Long getUserId() { return userId; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("id", getId()) .append("content", getContent()) .append("userId", getUserId()) .append("updateTime", getUpdateTime()) .append("createTime", getCreateTime()) .toString(); } }
true
2bab0128e0e553616876498b9969f9a92150adbb
Java
vchamp/android-guides
/Single/bestpractui/src/main/java/com/vm/guides/bestpractui/adapters/PaletteColorsAdapter.java
UTF-8
2,338
2.4375
2
[]
no_license
package com.vm.guides.bestpractui.adapters; import android.graphics.Color; import android.support.v7.graphics.Palette; import android.support.v7.widget.RecyclerView; import android.util.Pair; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.vm.guides.bestpractui.R; import com.vm.guides.common.util.ViewUtil; import java.util.List; public class PaletteColorsAdapter extends RecyclerView.Adapter<PaletteColorsAdapter.ViewHolder> { private List<Pair<String, Palette.Swatch>> swatches; static class ViewHolder extends RecyclerView.ViewHolder { public ViewGroup itemView; public TextView titleTextView; public TextView bodyTextView; public View colorView; public ViewHolder(ViewGroup v) { super(v); itemView = v; titleTextView = (TextView) v.findViewById(R.id.titleTextView); bodyTextView = (TextView) v.findViewById(R.id.bodyTextView); colorView = v.findViewById(R.id.colorView); } } public PaletteColorsAdapter(List<Pair<String, Palette.Swatch>> swatches) { super(); this.swatches = swatches; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder((ViewGroup) ViewUtil.inflateListItemView(parent, R.layout.list_item_palette_color)); } @Override public void onBindViewHolder(ViewHolder holder, int position) { Pair<String, Palette.Swatch> swatchItem = swatches.get(position); holder.titleTextView.setText(swatchItem.first); Palette.Swatch swatch = swatchItem.second; if (swatch != null) { holder.itemView.setBackgroundColor(swatch.getRgb()); holder.titleTextView.setTextColor(swatch.getTitleTextColor()); holder.bodyTextView.setText(swatch.toString()); holder.bodyTextView.setTextColor(swatch.getBodyTextColor()); } else { holder.itemView.setBackgroundColor(Color.BLACK); holder.titleTextView.setTextColor(Color.WHITE); holder.bodyTextView.setText("Not available"); holder.bodyTextView.setTextColor(Color.WHITE); } } @Override public int getItemCount() { return swatches.size(); } }
true
f76dbff54a41910408f0e7f3fcdc86f9a83d211a
Java
ondrejvelisek/events-shop
/events-shop-persistence/src/main/java/cz/muni/fi/eventsshop/repository/impl/EventServiceRepositoryImpl.java
UTF-8
1,250
2.28125
2
[]
no_license
package cz.muni.fi.eventsshop.repository.impl; import cz.muni.fi.eventsshop.model.EventService; import cz.muni.fi.eventsshop.repository.EventServiceRepository; import javax.enterprise.context.ApplicationScoped; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; /** * Created by patrik.cyprian on 26.5.2017. */ @ApplicationScoped public class EventServiceRepositoryImpl implements EventServiceRepository { @PersistenceContext private EntityManager manager; @Override public EventService create(EventService eventService) { manager.persist(eventService); return eventService; } @Override public EventService update(EventService eventService) { manager.merge(eventService); return eventService; } @Override public EventService find(Long eventServiceId) { return manager.find(EventService.class, eventServiceId); } @Override public List<EventService> findAll() { return manager.createQuery("from " + EventService.class.getName(), EventService.class).getResultList(); } @Override public void delete(EventService eventService) { manager.remove(eventService); } }
true
24f6cc3981bb481ee21384d888917ab17e992f05
Java
Crafter-IT/Alexey.Shevtsov
/Doc.java
UTF-8
230
2.21875
2
[]
no_license
package ru.geekbrains.java1.lesson1; public class Doc extends Animals { public Doc (){ super(500, 10,0.5f); } public Doc(int MAXrun, int MAXswiming, int MAXjump) { super(MAXrun, MAXswiming, MAXjump); } }
true
44f5bd695a80b75f7ffc003ad36902ccb3e56434
Java
FamousMrChair/apcs-1
/14_overload/defcon/Greet.java
UTF-8
934
3.546875
4
[]
no_license
//Triple J: Jeffery Tang (Mathias), Jefford Shau (Dylan), Jun Hong Wang (Bob) //APCS //HW14 -- BigSib Overload //2021-10-7 //DISCO: //It is possible to have multiple contructors in a class in order for multiple tasks to be performed when called. //QCC: //Would the constructor that takes String x not run if the BigSib object is an int or anything //that is not a string? public class Greet { public static void main( String[] args ){ String greeting; BigSib richard = new BigSib(); BigSib grizz = new BigSib(); BigSib dotCom = new BigSib(); BigSib tracy = new BigSib(); greeting = richard.greet("freshman"); System.out.println(greeting); greeting = tracy.greet("Dr. Spaceman"); System.out.println(greeting); greeting = grizz.greet("Kong Fooey"); System.out.println(greeting); greeting = dotCom.greet("mom"); System.out.println(greeting); } }
true
27f8f28dbc266d899e2e4a84d749f43ca4fcf08d
Java
sirenigell/ZimboNews
/app/src/main/java/com/example/sbondai/zimbonews/Data/Model/WPArticle.java
UTF-8
993
1.945313
2
[]
no_license
package com.example.sbondai.zimbonews.Data.Model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class WPArticle { @SerializedName("featured_image_urls") @Expose private FeaturedImageUrls featuredImageUrls; private Integer id; private Title title; private Excerpt excerpt; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Title getTitle() { return title; } public void setTitle(Title title) { this.title = title; } public Excerpt getExcerpt() { return excerpt; } public void setExcerpt(Excerpt excerpt) { this.excerpt = excerpt; } public FeaturedImageUrls getFeaturedImageUrls() { return featuredImageUrls; } public void setFeaturedImageUrls(FeaturedImageUrls featuredImageUrls) { this.featuredImageUrls = featuredImageUrls; } }
true
6fde55f1d8485ae3f787c5e587f455bb45a3b92e
Java
soulcure/airplay
/iot-channel-app/sdk/iot-channel/iot-channel-sdk/sdk/src/main/java/swaiotos/channel/iot/ss/controller/DeviceState.java
UTF-8
4,379
2.34375
2
[]
no_license
package swaiotos.channel.iot.ss.controller; import android.os.Parcel; import android.os.Parcelable; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import java.util.Set; import swaiotos.channel.iot.ss.session.Session; import swaiotos.channel.iot.utils.JSON; /** * @ClassName: DeviceState * @Author: lu * @CreateDate: 2020/4/22 5:44 PM * @Description: */ public class DeviceState implements Parcelable { private String mLsid; private Map<String, String> mConnectiveInfo; private Map<String, String> mClientInfo; public Session toSession() { Session session = new Session(); session.setId(mLsid); Set<String> keys = mConnectiveInfo.keySet(); for (String key : keys) { session.putExtra(key, mConnectiveInfo.get(key)); } return session; } public DeviceState() { } public static DeviceState parse(String in) { // return com.alibaba.fastjson.JSONObject.parseObject(in, DeviceState.class); try { JSONObject object = new JSONObject(in); String lsid = object.getString("lsid"); Map<String, String> connectiveInfo = JSON.parse(in, "connective"); Map<String, String> clientInfo = JSON.parse(in, "client"); return new DeviceState(lsid, connectiveInfo, clientInfo); } catch (JSONException e) { e.printStackTrace(); } return null; } public DeviceState(String lsid) { this(lsid, new HashMap<String, String>(), new HashMap<String, String>()); } DeviceState(String lsid, Map<String, String> connectiveInfo, Map<String, String> clientInfo) { mLsid = lsid; mConnectiveInfo = new HashMap<>(connectiveInfo); mClientInfo = new HashMap<>(clientInfo); } DeviceState(Parcel source) { this.mLsid = source.readString(); this.mConnectiveInfo = source.readHashMap(Map.class.getClassLoader()); this.mClientInfo = source.readHashMap(Map.class.getClassLoader()); } public void setLsid(String lsid) { this.mLsid = lsid; } public String getLsid() { return mLsid; } public final boolean putConnectiveInfo(String key, String value) { synchronized (mConnectiveInfo) { mConnectiveInfo.put(key, value); return true; } } public final Set<String> getConnectivies() { synchronized (mConnectiveInfo) { return mConnectiveInfo.keySet(); } } public final boolean putClientInfo(String key, String value) { synchronized (mClientInfo) { boolean r = false; String v = mClientInfo.get(key); if (v == null || !v.equals(value)) { r = true; mClientInfo.put(key, value); } return r; } } public final boolean removeClientInfo(String key) { synchronized (mClientInfo) { if (mClientInfo.containsKey(key)) { mClientInfo.remove(key); return true; } return false; } } public final Set<String> getClients() { synchronized (mClientInfo) { return mClientInfo.keySet(); } } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(mLsid); dest.writeMap(mConnectiveInfo); dest.writeMap(mClientInfo); } public String encode() { // return JSONObject.toJSONString(this); JSONObject object = new JSONObject(); try { object.put("lsid", mLsid); object.put("connective", new JSONObject(mConnectiveInfo)); object.put("client", new JSONObject(mClientInfo)); } catch (JSONException e) { e.printStackTrace(); } return object.toString(); } public static final Creator<DeviceState> CREATOR = new Creator<DeviceState>() { @Override public DeviceState createFromParcel(Parcel source) { return new DeviceState(source); } @Override public DeviceState[] newArray(int size) { return new DeviceState[size]; } }; }
true
632f9050fe1b293d2e1d57630a564db193a4dbb0
Java
tranhoavn97/PrEcomic
/app/src/main/java/com/example/developer/precomic/ChapterActivity.java
UTF-8
3,163
1.976563
2
[]
no_license
package com.example.developer.precomic; import android.content.Intent; import android.graphics.drawable.Drawable; import android.support.v4.content.res.ResourcesCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.Adapter; import android.widget.TextView; import android.widget.Toast; import com.example.developer.precomic.Adapter.AdapterChapter; import com.example.developer.precomic.Common.Common; import com.example.developer.precomic.Model.Chapter.ModelChapter; import com.example.developer.precomic.Object.Chapter; import java.util.List; public class ChapterActivity extends AppCompatActivity { Toolbar toolbar; TextView txtChapter,txtMangaName; RecyclerView rvChapter; // int MangaID; // String MangaName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chapter); toolbar=findViewById(R.id.mToolbar); txtChapter=findViewById(R.id.txtChapter); txtMangaName=findViewById(R.id.txtMangaName); setUpToolbar(); // Intent intent=getIntent(); // MangaName=intent.getStringExtra("EcomicName"); // MangaID=intent.getIntExtra("EcomicID",0); txtMangaName.setText(Common.select_ecomic.getName()); rvChapter=findViewById(R.id.rvChapter); rvChapter.setHasFixedSize(true); rvChapter.setLayoutManager(new LinearLayoutManager(this)); fetchChapter(); } private void fetchChapter() { List<Chapter> list =new ModelChapter().LoadChapter(Common.select_ecomic.getID()); Common.chapterList=list;//lưu list chapter lại để back và next txtChapter.setText("CHAPTER ("+list.size()+")"); AdapterChapter adapterChapter=new AdapterChapter(ChapterActivity.this,list); rvChapter.setAdapter(adapterChapter); adapterChapter.notifyDataSetChanged(); } private void setUpToolbar() { setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); if(getSupportActionBar() !=null) { Drawable drawable= ResourcesCompat.getDrawable(this.getResources(), R.drawable.ic_arrow_back_white_24dp, null); //custom color //drawable.setColorFilter(ResourcesCompat.getColor(this.getResources(), R.color.colorwhite, null), PorterDuff.Mode.SRC_IN); ActionBar actionBar = getSupportActionBar(); actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(drawable); } } // trở về trang chủ @Override public boolean onOptionsItemSelected(MenuItem item) { int id=item.getItemId(); if(id==android.R.id.home) { finish(); } return super.onOptionsItemSelected(item); } }
true
0d2a4ceff61419558b74a17edbac554f77ad0c61
Java
proliuxz/Lintcode
/src/S601TO800/S768.java
UTF-8
661
3
3
[]
no_license
package S601TO800; import java.util.ArrayList; import java.util.List; public class S768 { public List<List<Integer>> calcYangHuisTriangle(int n) { // write your code here List<List<Integer> > res = new ArrayList<>(); int i, j; if (n == 0) return res; for (i = 0; i < n; ++i) { List<Integer> t = new ArrayList<>(); t.add(1); for (j = 1; j < i; ++j) { t.add(res.get(i - 1).get(j - 1) + res.get(i - 1).get(j)); } if (i > 0) { t.add(1); } res.add(t); } return res; } }
true
80e501ffb6792ca5c8904044883a847f21a2c94c
Java
wanggn/LinkedData-QA-Dashboard
/old-gxt-version/src/main/java/org/aksw/linkedqa/shared/MyChart.java
UTF-8
876
2.109375
2
[]
no_license
package org.aksw.linkedqa.shared; import com.extjs.gxt.ui.client.data.BaseModelData; public class MyChart extends BaseModelData { public MyChart() { } public MyChart(String type, String data) { super(); setType(type); setData(data); } public String getType() { return get("type"); } public void setType(String type) { set("type", type); } public String getData() { return get("data"); } public void setData(String data) { set("data", data); } /* private String type; private String data; public MyChart() { } public MyChart(String type, String data) { super(); this.type = type; this.data = data; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getData() { return data; } public void setData(String data) { this.data = data; } */ }
true
4cda11e681d0b20e278e8993f1515e9d40df5df4
Java
Gorbatenko/qa_guru_4_home_24
/src/test/java/team/dataart/tests/TestData.java
UTF-8
425
1.851563
2
[]
no_license
package team.dataart.tests; import team.dataart.config.TestDataConfig; import org.aeonbits.owner.ConfigFactory; public class TestData { private static TestDataConfig getTestData() { return ConfigFactory.create(TestDataConfig.class); } public static String getWebUrl() { return getTestData().webUrl(); } public static String getApiUrl() { return getTestData().apiUrl(); } }
true
abf428b05fe114a346a4b6a960c5816c323b4fcd
Java
25267/Assignment-5
/src/main/java/org/example/event/handler/SalaryChangeEventHandler.java
UTF-8
570
2.4375
2
[]
no_license
package org.example.event.handler; import org.example.event.SalaryChangeEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; @Component public class SalaryChangeEventHandler implements ApplicationListener<SalaryChangeEvent> { @Override public void onApplicationEvent(SalaryChangeEvent salaryChangeEvent) { System.out.println("SalaryChangeEventHandler.onApplicationEvent"); System.out.println("salary changed on: " + salaryChangeEvent.getEmployee().getType()); } }
true
e96f8d663664c0ff0bcc40e7ae7cb6c4db5028b5
Java
mohsaied/lynx
/lynx/vcmapping/VcDesignation.java
UTF-8
7,730
2.46875
2
[]
no_license
package lynx.vcmapping; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.logging.Logger; import lynx.data.Bundle; import lynx.data.Design; import lynx.data.Noc; import lynx.data.MyEnums.Direction; import lynx.data.NocBundle; import lynx.main.ReportData; import lynx.nocmapping.Mapping; /** * This class contains the methods to assign a VC and combine-data status to * each bundle * * @author Mohamed * */ public class VcDesignation { private static final Logger log = Logger.getLogger(VcDesignation.class.getName()); public static VcMap createVcMap(Design design, Noc noc, Mapping mapping) { long startTime = System.nanoTime(); ReportData.getInstance().writeToRpt("Started VC designation..."); VcMap vcMap = assignVcs(design, noc, mapping); log.info(vcMap.toString()); long endTime = System.nanoTime(); DecimalFormat secondsFormat = new DecimalFormat("#.00"); log.info("Elapsed Time = " + secondsFormat.format((endTime - startTime) / 1e9) + " seconds"); ReportData.getInstance().writeToRpt( "Finished VC designation -- took " + secondsFormat.format((endTime - startTime) / 1e9) + " seconds"); ReportData.getInstance().writeToRpt("map_time = " + secondsFormat.format((endTime - startTime) / 1e9)); ReportData.getInstance().closeRpt(); return vcMap; } private static VcMap assignVcs(Design design, Noc noc, Mapping mapping) { VcMap vcMap = new VcMap(); // loop over all routers, and figure out which routers need combine-data // to be enabled, the criteria for combine data are. // 1) That more than one input bundle share a router output. // In this case, each of those bundles should take its own VC and it's // own nocbundle that will become associated with that VC // loop over all routers in this mapping for (int i = 0; i < noc.getNumRouters(); i++) { HashSet<Bundle> bunSet = mapping.getBundlesAtRouters().get(i); int numInBuns = 0; // loop over all bundles at each router for (Bundle bun : bunSet) { // How many input bundles do we have? if (bun.getDirection() == Direction.INPUT) { numInBuns++; } } // "combine data" is equal to the number of additional streams we // merge onto this router input. // So it is 0 for normal mode or if we have no bundles. // And it is 1 if we have 2 bundles, or n-1 for n bundles int combineData = numInBuns == 0 ? 0 : (numInBuns - 1); // 1) assign the routers to this combine_data value. // 2) associate bundles at this router with the combine_data value. // 3) associate bundles at this router with a VC // 4) associate source bundles of the same connections with that VC // 5) store all that info in a VcMap that can be used later // how do we choose the VC? randomly is fine for now. // But later (TODO), we should also look at path overlap in the // whole NoC and choose the VC such that it minimizes HOL blocking // when two connection paths overlap. This will have to be done in // mapping because here we are bound to whatever part of the port // that mapping gave us. // Actually, we can just swap the bundles here as well if we need to // change VCs // go over the bunset. For each input bundle, find the source bundle // then assign each bundle a VC if (combineData != 0) { // FIXME This hack is to ensure that cd works with a bundle // that uses one NoCbundle in a 4-VC NoC // TODO ideally, we would want a more general method of // assigning bundles to nocbundles in any combination of // combine-data mode // currently, the one thing that is not supported in lynx, but // is supported in SW fabricport, is cd=1 with 4 VCs -- but it // works if we switch it over to cd=2 if (combineData == 1 && noc.getNumVcs() > 2) combineData = 2; // here we need to make sure that each bundle is assigned its // correct VC // The VCs start from 0 at the most significant bit, then // increases with each nocbundle towards least-significant for (Bundle dstBun : bunSet) { if (dstBun.getDirection() == Direction.INPUT) { List<Bundle> srcBuns = dstBun.getConnections(); assert mapping.getBundleMap().get(dstBun).size() == 1 : "The number of NocBundles per Bundle involved in combine data should be exactly 1 but was " + mapping.getBundleMap().get(dstBun).size(); int currVc = mapping.getBundleMap().get(dstBun).get(0).getIndex(); vcMap.addVcDesignation(dstBun, srcBuns, i, currVc, combineData); } } } else { // for modules that don't share a port, we'll make sure they are // connected to the more-significant nocbundle(s) because this // is where data always arrives // TODO assign VCs to the non-combine-data modules too to // optimize paths and what not for (Bundle dstBun : bunSet) { if (dstBun.getDirection() == Direction.INPUT) { // there is only one dstbun // fetch its list of nocbuns and make sure they are at // the msbs List<NocBundle> nocbuns = mapping.getBundleMap().get(dstBun); int router = mapping.getRouter(dstBun); int numNocBuns = nocbuns.size(); int currNocBunIdx = noc.getNocOutBundles(router).size() - 1; List<NocBundle> newNocBuns = new ArrayList<NocBundle>(); for (int j = 0; j < numNocBuns; j++) { newNocBuns.add(noc.getNocOutBundles(router).get(currNocBunIdx--)); } mapping.getBundleMap().put(dstBun, newNocBuns); } } } // TODO at the very end, go over all bundles; if they weren't // already added then we'll add them with defaults (optional) // right now I just assume that unspecified bundles are assigned // default values (VC0 and combine_data 0) } // last thing is to edit the combine_data parameter in the NoC editNocCombineDataParameter(noc, vcMap); return vcMap; } private static void editNocCombineDataParameter(Noc noc, VcMap vcMap) { String combineDataStr = "'{"; for (int i = 0; i < noc.getNumRouters(); i++) { combineDataStr += vcMap.getRouterToCombineData().containsKey(i) ? vcMap.getRouterToCombineData().get(i) + "," : "0,"; } combineDataStr = combineDataStr.substring(0, combineDataStr.length() - 1) + "}"; noc.editParameter("COMBINE_DATA", combineDataStr); } }
true
3b0b453b9274d09f78c396b3e5abccde5d7eb3d3
Java
apurvparekh30/data-structures
/greedy/MinimumPlatforms.java
UTF-8
1,580
3.34375
3
[]
no_license
import java.util.*; class Solution { static Scanner fs = new Scanner(System.in); static int n; static int []arrival,departure; static class Interval implements Comparable<Interval> { int u,v; Interval(int u,int v){ this.u = u; this.v = v; } @Override public int compareTo(Interval o) { if(this.v == o.v) return Integer.compare(this.u,o.u); return Integer.compare(this.v,o.v); } } public static void main(String[] args) { int tc = fs.nextInt(); while(tc-- > 0){ n = fs.nextInt(); arrival = new int[n]; departure = new int[n]; for(int i=0;i<n;i++){ arrival[i] = fs.nextInt(); } for(int i=0;i<n;i++){ departure[i] = fs.nextInt(); } Interval [] it = new Interval[n]; for(int i=0;i<n;i++){ it[i] = new Interval(arrival[i], departure[i]); } Arrays.sort(it); int count = 1; int needed = 1; int i = 1; int j = 0; while(i < n && j < n){ if(it[i].u <= it[j].v){ count++; i++; if(needed < count) needed = count; } else { count--; j++; } } System.out.println(needed); } } }
true
bbca453f699e63cd883c715b1f578077c243cd88
Java
bigGreenPeople/UiautoApiTest
/app/src/main/java/com/shark/tools/ScreenShot.java
UTF-8
4,029
2.5625
3
[]
no_license
package com.shark.tools; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Rect; import android.util.Log; import android.view.View; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class ScreenShot { public final static String TAG = "SharkChilli"; // 获取指定Activity的截屏,保存到png文件 private static Bitmap takeScreenShot(View view) { // View是你需要截图的View view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap b1 = view.getDrawingCache(); // 获取屏幕长和高 int width = view.getWidth(); int height = view.getHeight(); Bitmap b = Bitmap.createBitmap(b1, 0, 0, width, height); view.destroyDrawingCache(); return b; } // 获取指定Activity的截屏,保存到png文件 private static Bitmap takeScreenShot(Activity activity) { // View是你需要截图的View View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap b1 = view.getDrawingCache(); // 获取状态栏高度 Rect frame = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; // Log.i(TAG, "" + statusBarHeight); // 获取屏幕长和高 int width = activity.getWindowManager().getDefaultDisplay().getWidth(); int height = activity.getWindowManager().getDefaultDisplay() .getHeight(); // 去掉标题栏 // Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455); Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight); view.destroyDrawingCache(); return b; } // 保存到sdcard private static void savePic(Bitmap b, String strFileName) { FileOutputStream fos = null; try { fos = new FileOutputStream(strFileName); if (null != fos) { b.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.flush(); fos.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 获取截屏的byte数组 * * @param activity * @return */ public static byte[] getActivityScreenBytes(Activity activity) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Bitmap bitmap = ScreenShot.takeScreenShot(activity); bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] bytes = byteArrayOutputStream.toByteArray(); return bytes; } /** * 获取截屏的byte数组 * * @param view * @return */ public static byte[] getViewScreenBytes(View view) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Bitmap bitmap = ScreenShot.takeScreenShot(view); bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] bytes = byteArrayOutputStream.toByteArray(); return bytes; } // 程序入口 public static void shoot(Activity a) { ScreenShot.savePic(ScreenShot.takeScreenShot(a), "sdcard/YoupinSeckillSuccess.png"); } // 程序入口 public static void shoot(View a) { ScreenShot.savePic(ScreenShot.takeScreenShot(a), "sdcard/YoupinSeckillSuccess.png"); } // 程序入口 public static void shoot(View a, String savePath) { ScreenShot.savePic(ScreenShot.takeScreenShot(a), savePath); } // 程序入口 public static void shoot(Activity a, String savePath) { ScreenShot.savePic(ScreenShot.takeScreenShot(a), savePath); } }
true
55545d70eb051dde7b1ccd9c4f3050c85711e7f7
Java
luis-sousa/GC-v1.1b
/src/dao/FraccaoDAO.java
UTF-8
8,004
2.796875
3
[ "MIT" ]
permissive
package dao; /* * ESTGF - Escola Superior de Tecnologia e Gestão de Felgueiras */ /* IPP - Instituto Politécnico do Porto */ /* LEI - Licenciatura em Engenharia Informática*/ /* Projeto Final 2013/2014 /* */ import connection.DB; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import model.Fraccao; /** * Esta classe permite efectuar operações na BD relativamente a uma Fraccão. * * @author Luís Sousa - 8090228 */ public class FraccaoDAO { private final Connection connection; private PreparedStatement stmt; /** * Construtor da classe Fraccao DAO aqui é feita a ligação com a BD. * */ public FraccaoDAO() { DB db = new DB(); this.connection = db.getConnection(); } /** * Método que permite adicionar dados de uma Fraccao na BD * * @param fraccao objecto com os dados de uma fracção * @return se a operação foi bem sucedida */ public boolean adicionarFraccao(Fraccao fraccao) { boolean result = false; try { String sql = "INSERT INTO Fraccao (codFracao,nome, morada, codPostal, localidade, " + "telefone, telemovel, email, contribuinte,permilagem,tipo)" + "VALUES (?,?,?,?,?,?,?,?,?,?,?)"; this.stmt = this.connection.prepareStatement(sql); this.stmt.setString(1, fraccao.getCod()); this.stmt.setString(2, fraccao.getNome()); this.stmt.setString(3, fraccao.getMorada()); this.stmt.setString(4, fraccao.getCodPostal()); this.stmt.setString(5, fraccao.getLocalidade()); this.stmt.setInt(6, fraccao.getTelefone()); this.stmt.setInt(7, fraccao.getTelemovel()); this.stmt.setString(8, fraccao.getMail()); this.stmt.setInt(9, fraccao.getContribuinte()); this.stmt.setFloat(10, fraccao.getPermilagem()); this.stmt.setString(11, fraccao.getTipo()); this.stmt.execute(); result = true; this.stmt.close(); } catch (SQLException ex) { throw new RuntimeException(ex); } return result; } /** * Método que permite editar dados de uma Fraccao na BD * * @param fraccao objeto com os dados de uma fracção * @return se a operação foi bem sucedida */ public boolean editarFraccao(Fraccao fraccao) { boolean result = false; try { String sql = "update Fraccao set nome=?, morada=?, codPostal=?, localidade=?,telefone=?,telemovel=?,email=?,contribuinte=?,permilagem=?, tipo=? where codFracao=?"; this.stmt = this.connection.prepareStatement(sql); this.stmt.setString(1, fraccao.getNome()); this.stmt.setString(2, fraccao.getMorada()); this.stmt.setString(3, fraccao.getCodPostal()); this.stmt.setString(4, fraccao.getLocalidade()); this.stmt.setInt(5, fraccao.getTelefone()); this.stmt.setInt(6, fraccao.getTelemovel()); this.stmt.setString(7, fraccao.getMail()); this.stmt.setInt(8, fraccao.getContribuinte()); this.stmt.setFloat(9, fraccao.getPermilagem()); this.stmt.setString(10, fraccao.getTipo()); this.stmt.setString(11, fraccao.getCod()); this.stmt.execute(); result = true; this.stmt.close(); } catch (SQLException ex) { throw new RuntimeException(ex); } return result; } /** * Metodo que permite apagar uma fraccao da BD * * @param fraccao * @return se a operação foi bem sucedida */ public boolean removerFraccao(Fraccao fraccao) { boolean result = false; try { String sql = "delete from Fraccao where codFracao=?"; this.stmt = this.connection.prepareStatement(sql); this.stmt.setString(1, fraccao.getCod()); this.stmt.execute(); result = true; this.stmt.close(); } catch (SQLException ex) { throw new RuntimeException(ex); } return result; } /** * Método que devolve todas as fracções existente na BD * * @return lista com todas as fracções existente na BD */ public ArrayList<Fraccao> getAllFraccoes() { ArrayList<Fraccao> lista = new ArrayList<>(); try (Statement statement = this.connection.createStatement()) { ResultSet rs; statement.setQueryTimeout(30); // set timeout to 30 sec. rs = statement.executeQuery("SELECT * FROM Fraccao"); while (rs.next()) { Fraccao fraccao = new Fraccao(); fraccao.cod.set(rs.getString("codFracao")); fraccao.nome.set(rs.getString("nome")); fraccao.morada.set(rs.getString("morada")); fraccao.codPostal.set(rs.getString("codPostal")); fraccao.localidade.set(rs.getString("localidade")); fraccao.telefone.set(rs.getInt("telefone")); fraccao.telemovel.set(rs.getInt("telemovel")); fraccao.mail.set(rs.getString("email")); fraccao.contribuinte.set(rs.getInt("contribuinte")); fraccao.permilagem.set(rs.getFloat("permilagem")); fraccao.tipo.set(rs.getString("tipo")); lista.add(fraccao); } rs.close(); } catch (SQLException ex) { Logger.getLogger(FraccaoDAO.class.getName()).log(Level.SEVERE, null, ex); } return lista; } /** * Método que permite obter um email de uma Fracção * * @param codFraccao identificador de uma Fracção * @return email de um determinada fracção */ public String getMail(String codFraccao) { String email = null; try { ResultSet rs; String sql = "SELECT email FROM Fraccao WHERE codFracao=?"; this.stmt = this.connection.prepareStatement(sql); this.stmt.setString(1, codFraccao); rs = this.stmt.executeQuery(); email = rs.getString("email"); rs.close(); } catch (SQLException ex) { Logger.getLogger(FraccaoDAO.class.getName()).log(Level.SEVERE, null, ex); } return email; } /** * Método que verifica se pode remover uma fração. Só pode remover a fração * se ela não existir em nenhum Orçamento, ou seja na tabela * FraccaoOrcamento * * @param codFraccao código da fração * @return se pode remover fracao */ public boolean verifyRemove(String codFraccao) { boolean remove; FraccaoOrcamentoDAO dao = new FraccaoOrcamentoDAO(); remove = !dao.existFraccao(codFraccao); dao.close(); return remove; } /** * Método que verifica se pode editar a permilagem de uma fração. Só pode * editar a permilagem de uma fração se a fração não existir em nenhum * Orçamento, ou seja na tabela FraccaoOrcamento * * @param codFraccao identificador da fração * @return se pode editar fracao */ public boolean verifyEditPerm(String codFraccao) { boolean edit; FraccaoOrcamentoDAO dao = new FraccaoOrcamentoDAO(); edit = !dao.existFraccao(codFraccao); dao.close(); return edit; } /** * Fechar a ligação á BD */ public void close() { try { if (connection != null) { connection.close(); } } catch (SQLException e) { // connection close failed. System.err.println(e); } } }
true
38f3f48f9520b24691ba91a14993fe8a07d47209
Java
SeunghoShin93/TIL
/08_java/00_intro/src/Calc.java
UTF-8
243
3.15625
3
[]
no_license
class Math { int add(int a, int b) { return a+b; } } public class Calc { public static void main(String[] args) { // TODO Auto-generated method stub Math math = new Math() ; System.out.println("3 + 9 = " + math.add(3, 9)); } }
true
ee650d53e8c49d5e40ec97cf474b1bcb08e5fdd7
Java
Meti51/LivingRoom
/src/server/server_file/ServerFile.java
UTF-8
1,105
2.6875
3
[]
no_license
package server.server_file; /** * Created on 4/9/2017. * @author Natnael Seifu [seifu003] */ public class ServerFile { private String id; private String client_ip_addr; private String client_port; /* filename == path of directory/ + filename */ private String filename; public ServerFile(String filename, String client_ip_addr, String client_port) { this.client_ip_addr = client_ip_addr; this.client_port = client_port; this.filename = filename; this.id = IDGenerator.issueUniqueID(); } public String getId() { return id; } public String getClient_ip_addr() { return client_ip_addr; } public String getClient_port() { return client_port; } public String getFilename() { return filename; } public String toString() { return id + "," + client_ip_addr + "," + client_port + "," + filename; } @Override public boolean equals(Object obj) { if (obj instanceof ServerFile) { ServerFile of = (ServerFile) obj; if (of.getId().equals(this.getId())) { return true; } } return false; } }
true
3eff31806a6c1959b91bba3dfcc66ee496212200
Java
Gabriel-demian/farm-rest-management
/src/main/java/com/proy/rest/dto/FarmDto.java
UTF-8
1,781
2.140625
2
[]
no_license
package com.proy.rest.dto; import java.math.BigDecimal; import java.util.List; public class FarmDto { private Integer id; private String farmName; private Integer chickenBought; private Integer chickenSold; private Integer eggBought; private Integer eggSold; private BigDecimal income; private BigDecimal expenses; private List<EggDto> eggs; private List<ChickenDto> chickens; public FarmDto() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFarmName() { return farmName; } public void setFarmName(String farmName) { this.farmName = farmName; } public Integer getChickenBought() { return chickenBought; } public void setChickenBought(Integer chickenBought) { this.chickenBought = chickenBought; } public Integer getChickenSold() { return chickenSold; } public void setChickenSold(Integer chickenSold) { this.chickenSold = chickenSold; } public Integer getEggBought() { return eggBought; } public void setEggBought(Integer eggBought) { this.eggBought = eggBought; } public Integer getEggSold() { return eggSold; } public void setEggSold(Integer eggSold) { this.eggSold = eggSold; } public BigDecimal getIncome() { return income; } public void setIncome(BigDecimal income) { this.income = income; } public BigDecimal getExpenses() { return expenses; } public void setExpenses(BigDecimal expenses) { this.expenses = expenses; } public List<EggDto> getEggs() { return eggs; } public void setEggs(List<EggDto> eggs) { this.eggs = eggs; } public List<ChickenDto> getChickens() { return chickens; } public void setChickens(List<ChickenDto> chickens) { this.chickens = chickens; } }
true
c60e65d004db29865f31aa90a63eb0c1d6086004
Java
BANIP/wooklog
/src/banip/action/image/ImageLoadAction.java
UTF-8
1,669
2.421875
2
[]
no_license
package banip.action.image; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import banip.action.Action; import banip.bean.ImageBean; import banip.bean.ImageTagBean; import banip.bean.support.BeanList; import banip.dao.ImageDao; import banip.data.StatusCode; import banip.util.BoardJSON; public class ImageLoadAction extends Action{ /* * 받는값 : search_word : 검색어, #검색어 * 검색어 * LIKES로 타이틀 이미지 검색 LIKES로 태그 검색 * * #검색어 * 일반 WHERE로 이미지 검색 */ @Override protected String getProtocol() { // TODO Auto-generated method stub return "GET"; } @Override protected ArrayList<String> getRequireParam() { // TODO Auto-generated method stub ArrayList<String> list = new ArrayList<String>(); list.add("search_word"); return list; } @Override protected BoardJSON executeMain(HttpServletRequest request) { // TODO Auto-generated method stub String searchWord = super.getString(request, "search_word"); boolean isTagSearch = isTagSearch(searchWord); BoardJSON boardJSON = new BoardJSON(StatusCode.STATUS_SUCCESS); ImageDao imageDao = new ImageDao(); BeanList<ImageBean> imageList = imageDao.searchImages(searchWord, isTagSearch); boardJSON.putData("images", imageList.getJSONArray()); BeanList<ImageTagBean> tagList = imageDao.searchTags(searchWord); boardJSON.putData("tags", tagList.getJSONArray()); imageDao.close(true); return boardJSON; } private boolean isTagSearch(String word) { return word.substring(0,1).equals("#"); } }
true
a08fd60575c0494940e6b8fb47fe2c96e60ffb22
Java
prAkash-SVMX/TourGuider
/app/src/main/java/com/example/android/tourguider/ListAdapter.java
UTF-8
1,274
2.3125
2
[]
no_license
package com.example.android.tourguider; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; public class ListAdapter extends ArrayAdapter<List> { public ListAdapter(@NonNull Context context, ArrayList<List> list) { super(context, 0,list); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { if (convertView==null){ convertView= LayoutInflater.from(getContext()).inflate(R.layout.listview,parent,false); } List currentPosition=getItem(position); TextView name=(TextView) convertView.findViewById(R.id.hotel_name); name.setText(currentPosition.getText()); TextView place=(TextView) convertView.findViewById(R.id.place); place.setText(currentPosition.getText2()); ImageView img=(ImageView) convertView.findViewById(R.id.img); img.setImageResource(currentPosition.getImg()); return convertView; } }
true
ac8628943e2ee7dfe1af4e05511990eea1e130f5
Java
Pferdchen/sudoku
/Sudoku/srctest/com/demo/sudoku/test/UtilityTest.java
UTF-8
1,694
2.40625
2
[]
no_license
package com.demo.sudoku.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import com.demo.sudoku.Utility; public class UtilityTest { private final static int[][] template = { { 5, 3, 0, 0, 7, 0, 0, 0, 0 }, { 6, 0, 0, 1, 9, 5, 0, 0, 0 }, { 0, 9, 8, 0, 0, 0, 0, 6, 0 }, { 8, 0, 0, 0, 6, 0, 0, 0, 3 }, { 4, 0, 0, 8, 0, 3, 0, 0, 1 }, { 7, 0, 0, 0, 2, 0, 0, 0, 6 }, { 0, 6, 0, 0, 0, 0, 2, 8, 0 }, { 0, 0, 0, 4, 1, 9, 0, 0, 5 }, { 0, 0, 0, 0, 8, 0, 0, 7, 9 } }; private final static int[][] result = { { 5, 3, 4, 6, 7, 8, 9, 1, 2 }, { 6, 7, 2, 1, 9, 5, 3, 4, 8 }, { 1, 9, 8, 3, 4, 2, 5, 6, 7 }, { 8, 5, 9, 7, 6, 1, 4, 2, 3 }, { 4, 2, 6, 8, 5, 3, 7, 9, 1 }, { 7, 1, 3, 9, 2, 4, 8, 5, 6 }, { 9, 6, 1, 5, 3, 7, 2, 8, 4 }, { 2, 8, 7, 4, 1, 9, 6, 3, 5 }, { 3, 4, 5, 2, 8, 6, 1, 7, 9 } }; @Test public void testSum() { assertEquals(0, Utility.sum(-1)); assertEquals(0, Utility.sum(0)); assertEquals(1 + 2 + 3, Utility.sum(3)); } @Test public void testFac() { assertEquals(0, Utility.fac(-1)); assertEquals(0, Utility.fac(0)); assertEquals(1 * 2 * 3, Utility.fac(3)); } @Test public void testIsResolved() { assertFalse(Utility.isResolved(template)); assertTrue(Utility.isResolved(result)); } @Test public void testIsCorrect() { assertFalse(Utility.isCorrect(template)); assertTrue(Utility.isCorrect(result)); } @Test public void testIsCorrect2() { assertFalse(Utility.isCorrect2(template)); assertTrue(Utility.isCorrect2(result)); } @Test public void testNormalize() { } @Test public void testInitialize() { } }
true
489cf2bdfb4323e2fdfe1d4b413a1f942c96a74f
Java
novianarma/FINDYOURLECTURER
/app/src/main/java/com/example/findyourlecturer/MyService.java
UTF-8
14,265
1.851563
2
[]
no_license
package com.example.findyourlecturer; import android.app.IntentService; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.os.Handler; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import static android.content.ContentValues.TAG; public class MyService extends IntentService { TextView mainText; WifiManager mainWifi; WifiReceiver receiverWifi; List<ScanResult> wifiList; StringBuilder sb = new StringBuilder(); private final Handler handler = new Handler(); String[] wifis; FirebaseAuth fAuth; public int a; String tipeuser, tipe; user user; public MyService() { super("My_Worker_Thread"); } public void onCreate() { // Initiate wifi service manager mainWifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); // Check for wifi is disabled if (mainWifi.isWifiEnabled() == false) { // If wifi disabled then enable it Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show(); mainWifi.setWifiEnabled(true); } doInback(); Log.i(TAG, "onCreate method" + Thread.currentThread().getName() + "thread dipanggil"); super.onCreate(); //CONNECT wifiList = mainWifi.getScanResults(); wifis = new String[wifiList.size()]; for (int i = 0; i < wifiList.size(); i++) { wifis[i] = ((wifiList.get(i)).SSID); if (wifis != null) { if (wifis[i].equals("Gedung AL")) { //WIFI WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = String.format("\"%s\"", wifis[i]); wifiConfig.preSharedKey = String.format("\"%s\"", "polinema"); //PASSWORD WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); //remember id int netId = wifiManager.addNetwork(wifiConfig); wifiManager.disconnect(); wifiManager.enableNetwork(netId, true); wifiManager.reconnect(); //INPUT TO FIREBASE fAuth = FirebaseAuth.getInstance(); String user = fAuth.getCurrentUser().getUid(); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("user").child("Dosen").child(user + "/ssid"); myRef.setValue("Gedung AL Polinema"); //MENAMPILKAN DATE&TIME Calendar calendar = Calendar.getInstance(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, dd-MMM-yyyy | hh:mm a"); String dateTime = simpleDateFormat.format(calendar.getTime()); myRef = database.getReference("user").child("Dosen").child(user + "/tgljam"); myRef.setValue(dateTime); } else if (wifis[i].equals("Gedung AH")) { //WIFI WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = String.format("\"%s\"", wifis[i]); wifiConfig.preSharedKey = String.format("\"%s\"", "polinema"); //PASSWORD WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); //remember id int netId = wifiManager.addNetwork(wifiConfig); wifiManager.disconnect(); wifiManager.enableNetwork(netId, true); wifiManager.reconnect(); //INPUT TO FIREBASE fAuth = FirebaseAuth.getInstance(); String user = fAuth.getCurrentUser().getUid(); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("user").child("Dosen").child(user + "/ssid"); myRef.setValue("Gedung AH Polinema"); //MENAMPILKAN DATE&TIME Calendar calendar = Calendar.getInstance(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, dd-MMM-yyyy | hh:mm a"); String dateTime = simpleDateFormat.format(calendar.getTime()); myRef = database.getReference("user").child("Dosen").child(user + "/tgljam"); myRef.setValue(dateTime); } else if (wifis[i].equals("Gedung AI")) { //WIFI WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = String.format("\"%s\"", wifis[i]); wifiConfig.preSharedKey = String.format("\"%s\"", "polinema"); //PASSWORD WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); //remember id int netId = wifiManager.addNetwork(wifiConfig); wifiManager.disconnect(); wifiManager.enableNetwork(netId, true); wifiManager.reconnect(); //INPUT TO FIREBASE fAuth = FirebaseAuth.getInstance(); String user = fAuth.getCurrentUser().getUid(); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("user").child("Dosen").child(user + "/ssid"); myRef.setValue("Gedung AI Polinema"); //MENAMPILKAN DATE&TIME Calendar calendar = Calendar.getInstance(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, dd-MMM-yyyy | hh:mm a"); String dateTime = simpleDateFormat.format(calendar.getTime()); myRef = database.getReference("user").child("Dosen").child(user + "/tgljam"); myRef.setValue(dateTime); } else if (wifis[i].equals("Gedung AH lantai 1")) { //WIFI WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = String.format("\"%s\"", wifis[i]); wifiConfig.preSharedKey = String.format("\"%s\"", "polinema"); //PASSWORD WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); //remember id int netId = wifiManager.addNetwork(wifiConfig); wifiManager.disconnect(); wifiManager.enableNetwork(netId, true); wifiManager.reconnect(); //INPUT TO FIREBASE fAuth = FirebaseAuth.getInstance(); String user = fAuth.getCurrentUser().getUid(); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("user").child("Dosen").child(user + "/ssid"); myRef.setValue("Gedung AH lantai 1"); //MENAMPILKAN DATE&TIME Calendar calendar = Calendar.getInstance(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, dd-MMM-yyyy | hh:mm a"); String dateTime = simpleDateFormat.format(calendar.getTime()); myRef = database.getReference("user").child("Dosen").child(user + "/tgljam"); myRef.setValue(dateTime); } else if (wifis[i].equals("Gedung AH lantai 2")) { //WIFI WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.SSID = String.format("\"%s\"", wifis[i]); wifiConfig.preSharedKey = String.format("\"%s\"", "polinema"); //PASSWORD WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); //remember id int netId = wifiManager.addNetwork(wifiConfig); wifiManager.disconnect(); wifiManager.enableNetwork(netId, true); wifiManager.reconnect(); //INPUT TO FIREBASE fAuth = FirebaseAuth.getInstance(); String user = fAuth.getCurrentUser().getUid(); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("user").child("Dosen").child(user + "/ssid"); myRef.setValue("Gedung AH lantai 2"); //MENAMPILKAN DATE&TIME Calendar calendar = Calendar.getInstance(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, dd-MMM-yyyy | hh:mm a"); String dateTime = simpleDateFormat.format(calendar.getTime()); myRef = database.getReference("user").child("Dosen").child(user + "/tgljam"); myRef.setValue(dateTime); } } } } public void doInback() { handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub mainWifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (receiverWifi == null) receiverWifi = new WifiReceiver(); registerReceiver(receiverWifi, new IntentFilter( WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); mainWifi.startScan(); doInback(); } }, 1000); // Toast.makeText(MyService.this, "Starting Scan...", Toast.LENGTH_SHORT).show(); } /* @Override public int onStartCommand(@Nullable Intent intent, int flags, int startId) { Toast.makeText(this,"Service Started...",Toast.LENGTH_LONG).show(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this,"Service Stopped...",Toast.LENGTH_LONG).show(); } */ @Override protected void onHandleIntent(@Nullable Intent intent) { /* synchronized (this){ int count = 0; while (count<10){ try{ wait(1500); count++; } catch (InterruptedException e){ e.printStackTrace(); } } } doInback(); */ Log.i(TAG, "onHandleIntent method" + Thread.currentThread().getName() + "thread dipanggil"); int sleepTime = intent.getIntExtra("sleepTime", 1); int kontrol = 1; while (kontrol <= sleepTime) { try { Thread.sleep(1000); Intent intent1 = new Intent("my action"); intent1.putExtra("data", kontrol); sendBroadcast(intent1); } catch (InterruptedException e) { e.printStackTrace(); } kontrol++; } doInback(); } /* public void doInback() { handler.postDelayed(new Runnable() { @Override public void run() { */ /* Intent intent = new Intent(MyService.this,WifiReceiver.class); intent.putExtra("kirim", "kirim"); startService(intent); *//* // TODO Auto-generated method stub mainWifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (receiverWifi == null) receiverWifi = new WifiReceiver(); registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); mainWifi.startScan(); // Toast.makeText(MyService.this, "Starting Scan..." + receiverWifi.getResultData(), Toast.LENGTH_SHORT).show(); doInback(); } }, 1500); // Toast.makeText(this, "coba scan wifi....", Toast.LENGTH_SHORT).show(); } */ // Broadcast receiver class called its receive method // when number of wifi connections changed /* class WifiReceiver extends BroadcastReceiver { // This method call when number of wifi connections changed public void onReceive(Context c, Intent intent) { sb = new StringBuilder(); wifiList = mainWifi.getScanResults(); sb.append("\n Number Of Wifi connections :"+wifiList.size()+"\n\n"); for(int i = 0; i < wifiList.size(); i++){ sb.append(new Integer(i+1).toString() + ". "); sb.append((wifiList.get(i)).toString()); sb.append("\n\n"); } mainText.setText(sb); } } */ }
true
628aa64f39d37712752d6173ca192dad7542e443
Java
tk4218/GroceryListR
/app/src/main/java/com/tk4218/grocerylistr/adapters/GroceryListAdapter.java
UTF-8
8,510
2.171875
2
[]
no_license
package com.tk4218.grocerylistr.adapters; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.graphics.Paint; import android.os.AsyncTask; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import com.tk4218.grocerylistr.model.GroceryList; import com.tk4218.grocerylistr.model.GroceryListItem; import com.tk4218.grocerylistr.R; import java.util.List; public class GroceryListAdapter extends BaseExpandableListAdapter { private Context mContext; private List<String> mIngredientTypes; private GroceryList mGroceryList; public GroceryListAdapter(Context context, List<String> ingredientTypes, GroceryList groceryList){ mContext = context; mIngredientTypes = ingredientTypes; mGroceryList = groceryList; } @Override public int getGroupCount() { return mIngredientTypes.size(); } @Override public int getChildrenCount(int groupPosition) { return mGroceryList.getGroceryListItems(mIngredientTypes.get(groupPosition)).size(); } @Override public String getGroup(int groupPosition) { return mIngredientTypes.get(groupPosition); } @Override public GroceryListItem getChild(int groupPosition, int childPosition) { return mGroceryList.getGroceryListItems(mIngredientTypes.get(groupPosition)).get(childPosition); } @Override public long getGroupId(int groupPosition) { return 0; } @Override public long getChildId(int groupPosition, int childPosition) { return 0; } @Override public boolean hasStableIds() { return false; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if(convertView == null){ final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.expandlist_grocerylist_header, parent, false); } //Each expandable group is the ingredient type of the items within the group. TextView ingredientType = convertView.findViewById(R.id.header_ingredient_type); ingredientType.setText(getGroup(groupPosition)); return convertView; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if(convertView == null){ final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.expandlist_grocerylist_item, parent, false); } final CheckBox groceryListItem = convertView.findViewById(R.id.item_grocerylist_item); final TextView groceryListItemAmount = convertView.findViewById(R.id.grocerylist_item_amount); groceryListItem.setTag(getChild(groupPosition, childPosition)); /*------------------------------------------------------ * Set Grocery List Item Display *------------------------------------------------------*/ groceryListItem.setChecked(((GroceryListItem)groceryListItem.getTag()).getAddedToCart()); if(groceryListItem.isChecked()){ groceryListItem.setTextColor(Color.LTGRAY); groceryListItem.setPaintFlags(groceryListItem.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); groceryListItemAmount.setPaintFlags(groceryListItemAmount.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); }else { groceryListItem.setTextColor(Color.BLACK); groceryListItem.setPaintFlags(groceryListItem.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); groceryListItemAmount.setPaintFlags(groceryListItemAmount.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); } GroceryListItem item = (GroceryListItem)groceryListItem.getTag(); String groceryListItemAmountText = item.getFormattedIngredientAmount() + " " + item.getIngredientUnit(); groceryListItem.setText(item.getIngredient().getIngredientName()); groceryListItemAmount.setText(groceryListItemAmountText); /*----------------------------------------------------- * Grocery List Item Event Handlers *-----------------------------------------------------*/ groceryListItem.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { new UpdateAddedToCart().execute(((GroceryListItem)buttonView.getTag()).getGroceryListItemKey(), isChecked); ((GroceryListItem)buttonView.getTag()).setAddedToCart(isChecked); if(isChecked){ groceryListItem.setTextColor(Color.LTGRAY); groceryListItem.setPaintFlags(groceryListItem.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); groceryListItemAmount.setPaintFlags(groceryListItemAmount.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); }else { groceryListItem.setTextColor(Color.BLACK); groceryListItem.setPaintFlags(groceryListItem.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); groceryListItemAmount.setPaintFlags(groceryListItemAmount.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); } } }); groceryListItem.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(final View v) { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle("Remove Item") .setMessage("Remove " + ((GroceryListItem)v.getTag()).getIngredient().getIngredientName() + " from list?") .setPositiveButton("Remove", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new RemoveGroceryListItem().execute(((GroceryListItem)v.getTag()).getGroceryListItemKey()); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog dialog = builder.create(); dialog.show(); return true; } }); return convertView; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return false; } private class UpdateAddedToCart extends AsyncTask<Object, Void, Void> { //private QueryBuilder mQb = new QueryBuilder(); @Override protected Void doInBackground(Object... params) { if(mGroceryList.getGroceryListItemsRemaining() == 0) { mGroceryList.setGroceryListCompleted(true); //mQb.updateGroceryListCompleted(mGroceryList.getGroceryListKey(), true); } else { if(mGroceryList.getGroceryListCompleted()) { mGroceryList.setGroceryListCompleted(false); //mQb.updateGroceryListCompleted(mGroceryList.getGroceryListKey(), false); } } //mQb.updateAddedToCart((int)params[0], (boolean)params[1]); return null; } } private class RemoveGroceryListItem extends AsyncTask<String, Void, Void> { //private QueryBuilder mQb = new QueryBuilder(); @Override protected Void doInBackground(String... params) { //boolean success = mQb.removeGroceryListItem(params[0]); //if(success){ // mGroceryList.removeGroceryListItem(params[0]); // mIngredientTypes = mGroceryList.getIngredientTypes(); //} return null; } @Override protected void onPostExecute(Void aVoid) { notifyDataSetChanged(); } } }
true
041c57e5aa72c26ee1b496ef4b1871b6c78d72f2
Java
adityasrivastava/bid-application
/src/main/java/com/sample/bidsystem/model/request/QueueBidMessage.java
UTF-8
1,133
2.359375
2
[]
no_license
package com.sample.bidsystem.model.request; import com.sample.bidsystem.entity.User; import com.sample.bidsystem.model.QueueMessage; import java.io.Serializable; public class QueueBidMessage implements QueueMessage, Serializable { private Long auctionId; private float price; private User buyer; public QueueBidMessage(Long auctionId, float price, User buyer) { this.auctionId = auctionId; this.price = price; this.buyer = buyer; } public Long getAuctionId() { return auctionId; } public void setAuctionId(Long auctionId) { this.auctionId = auctionId; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public User getBuyer() { return buyer; } public void setBuyer(User buyer) { this.buyer = buyer; } @Override public String toString() { return "QueueBidMessage{" + "auctionId=" + auctionId + ", price=" + price + ", buyer=" + buyer + '}'; } }
true
656d1a6fcbb57fd1828de41e53b9d82330b7181e
Java
soonsoft/Uranus
/uranus.security/src/main/java/com/soonsoft/uranus/security/authorization/voter/IVoter.java
UTF-8
607
2.25
2
[ "MIT" ]
permissive
package com.soonsoft.uranus.security.authorization.voter; import java.util.Collection; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.core.Authentication; public interface IVoter { /** * 权限投票(检查) * @param authentication 当前登录的角色信息 * @param object 访问的资源对象 * @param attributes 资源对象所对应的访问权限规则 * @return true - 有权限,false - 无权限 */ boolean vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes); }
true
d8635349f0ad912dc5bfdc5ec4994366a179c274
Java
zhoudy-github/Backup-Restore
/HighjetBI-Common/src/main/java/com/highjet/common/base/utils/ExcelUtil/DTO/TableMapperTemplateDTO.java
UTF-8
1,455
1.914063
2
[ "Apache-2.0" ]
permissive
package com.highjet.common.base.utils.ExcelUtil.DTO; import cn.afterturn.easypoi.excel.annotation.Excel; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import lombok.experimental.Accessors; import java.io.Serializable; /** * @author Email:liufei32@outlook.com github:Swagger-Ranger * @description 备份与恢复excel批量导入模板对象 * @since 2020/3/25 10:58 */ @Data @Accessors(chain = true) @ToString @NoArgsConstructor @AllArgsConstructor public class TableMapperTemplateDTO implements Serializable { private static final long serialVersionUID = 3125418717734522637L; // @ExcelCell(index = 0) @Excel(name = "源系统英文名") private String srcSys; // @ExcelCell(index = 1) @Excel(name = "源库英文名") private String srcDB; // @ExcelCell(index = 2) @Excel(name = "源表英文名") private String srcTable; // @ExcelCell(index = 3) @Excel(name = "源表中文名") private String srcTableCname; // @ExcelCell(index = 4) @Excel(name = "目标系统英文名") private String outSys; // @ExcelCell(index = 5) @Excel(name = "目标库英文名") private String outDB; // @ExcelCell(index = 6) @Excel(name = "目标表英文名") private String outTable; // @ExcelCell(index = 7) @Excel(name = "目标表中文名") private String outTableCname; }
true
09c33693a3ffaee93892c74cdde6c78ad5ffa441
Java
Saseke/LeetCode
/src/arrays/LC67_AddBinary.java
UTF-8
2,170
3.875
4
[]
no_license
package arrays; import static java.lang.Character.getNumericValue; public class LC67_AddBinary { private String addBinaryBetter(String a, String b) { StringBuilder sb = new StringBuilder(); int i = a.length() - 1, j = b.length() - 1, carry = 0, sum = 0; while (i >= 0 || j >= 0) { sum = carry; if (i >= 0) sum += a.charAt(i--) - '0'; if (j >= 0) sum += b.charAt(j--) - '0'; sb.append(sum % 2); carry = sum / 2; } if (carry != 0) { sb.append(carry); } return sb.reverse().toString(); } private String addBinary(String a, String b) { char[] aChars = a.toCharArray(); // 得到a,b对应的字符数组 char[] bChars = b.toCharArray(); StringBuilder stringBuilder = new StringBuilder(); int i = aChars.length - 1, j = bChars.length - 1, p = 0, q; // i,j指向aChars和bChars的最后一个元素,p表示进位数字,q表示每一位最后的结果 while (i >= 0 && j >= 0) { // 从最后一位开始,先处理具有相同位数的位置元素 int tmp = getNumericValue(aChars[i]) + getNumericValue(bChars[j]) + p; q = tmp % 2; p = tmp > 1 ? 1 : 0; stringBuilder.append(q); i--; j--; } while (i >= 0) { // aChars长度大于bChars int tmp = getNumericValue(aChars[i]) + p; q = tmp % 2; p = tmp > 1 ? 1 : 0; stringBuilder.append(q); i--; } while (j >= 0) { // bChars 长度大于aChars int tmp = getNumericValue(bChars[j]) + p; q = tmp % 2; p = tmp > 1 ? 1 : 0; stringBuilder.append(q); j--; } if (p != 0) { // 最后可能产生一个进位 stringBuilder.append("1"); } return stringBuilder.reverse().toString(); } public static void main(String[] args) { LC67_AddBinary lc67_addBinary = new LC67_AddBinary(); System.out.println(lc67_addBinary.addBinaryBetter("1", "111")); } }
true
fea60f3fe0f92767dd16f741e998f3f8ad341b58
Java
vikassry/devOps-run
/src/test/java/hello/HelloControllerTest.java
UTF-8
536
2.25
2
[]
no_license
package hello; import org.junit.Test; import static org.junit.Assert.assertEquals; public class HelloControllerTest { @Test public void HelloControllerReturnHelloOnIndex() { HelloController helloController = new HelloController(); assertEquals("Hello World! from spring boot", helloController.index()); } @Test public void HelloControllerReturnOKForHealthcheck() { HelloController helloController = new HelloController(); assertEquals("OK", helloController.healthcheck()); } }
true
a722a8ccf3412f149e5ce6ec412c460d9a548f1d
Java
tgrudz/intrcp
/RCP-SILP/src/zilp/rcp/objects/Day.java
UTF-8
2,470
2.5625
3
[]
no_license
package zilp.rcp.objects; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * This class represents day node * @author Jakub Pawlowski * @version 1.0 **/ public class Day implements Serializable { public Day() {} private List<Presence> presences = new ArrayList<Presence>(); // obecnosci private String absenceAmount; // wymiarNieob private String amount; // wymiar private String notes; // uwagi private String dayType; // typDnia private String entryPlan; // planWe private String presence; // obecnosc private String absenceCode; // kodNieob private String day; // dzien private String wokingTime; // czasPracy public void setAbsenceAmount(String absenceAmount) { this.absenceAmount = absenceAmount; } public String getAbsenceAmount() { return absenceAmount; } public void setAmount(String amount) { this.amount = amount; } public String getAmount() { return amount; } public void setNotes(String notes) { this.notes = notes; } public String getNotes() { return notes; } public void setEntryPlan(String entryPlan) { this.entryPlan = entryPlan; } public String getEntryPlan() { return entryPlan; } public void setPresence(String presence) { this.presence = presence; } public String getPresence() { return presence; } public void setAbsenceCode(String absenceCode) { this.absenceCode = absenceCode; } public String getAbsenceCode() { return absenceCode; } public void setDay(String day) { this.day = day; } public String getDay() { return day; } public void setWokingTime(String wokingTime) { this.wokingTime = wokingTime; } public String getWokingTime() { return wokingTime; } public void setDayType(String dayType) { this.dayType = dayType; } public String getDayType() { return dayType; } public void setPresences(List<Presence> presences) { this.presences = presences; } public List<Presence> getPresences() { return presences; } }
true
7c7a21e0509483fbf54aee8db3ba82453d1d79c5
Java
svendp1988/java2-examen
/src/main/java/be/pxl/paj/museum/api/data/CreateArtworkCommand.java
UTF-8
706
2.4375
2
[]
no_license
package be.pxl.paj.museum.api.data; import be.pxl.paj.museum.domain.ArtworkType; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; public class CreateArtworkCommand { @NotEmpty private final String title; @NotEmpty private final String artist; @NotNull private final ArtworkType artworkType; public CreateArtworkCommand(@NotEmpty String title, @NotEmpty String artist, @NotNull ArtworkType artworkType) { this.title = title; this.artist = artist; this.artworkType = artworkType; } public String getTitle() { return title; } public String getArtist() { return artist; } public ArtworkType getArtworkType() { return artworkType; } }
true
91c55c0bd1375f5082c32c1716e53a3b6c440db4
Java
redmojo7/StartSpringBoot
/src/main/java/com/strat/springboot/controller/service/thread/class1/TestMitiThread1.java
UTF-8
1,051
3.25
3
[]
no_license
package com.strat.springboot.controller.service.thread.class1; /** * Created by Administrator on 2017/5/4. */ /** * 通过实现 Runnable 接口实现多线程 */ public class TestMitiThread1 implements Runnable { public static void main(String[] args) { System.out.println(Thread.currentThread().getName() + " 线程运行开始!"); TestMitiThread1 test = new TestMitiThread1(); Thread thread1 = new Thread(test); Thread thread2 = new Thread(test); thread1.start(); thread2.start(); System.out.println(Thread.currentThread().getName() + " 线程运行结束!"); } public void run() { System.out.println(Thread.currentThread().getName() + " 线程运行开始!"); for (int i = 0; i < 10; i++) { System.out.println(i + " " + Thread.currentThread().getName()); try { Thread.sleep((int) Math.random() * 10); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " 线程运行结束!"); } }
true
b62e6e80fe16fc472466cfa21a41f1e401248e5d
Java
AlfonsoPG/gef4
/org.eclipse.gef4.swtfx/src/org/eclipse/gef4/swtfx/animation/AbstractTransition.java
UTF-8
2,436
3.03125
3
[]
no_license
package org.eclipse.gef4.swtfx.animation; import java.util.Timer; import java.util.TimerTask; public abstract class AbstractTransition { private static final int PERIOD = 30; public static final double INDEFINITE = -1; private IInterpolator interpolator = IInterpolator.LINEAR; /** * Stores the duration of one animation cycle (in millis), i.e. the time it * takes for the interpolator to switch from 0 to 1 or vice versa. */ private long cycleDurationMillis; // /** // * The number of cycles to execute, i.e. how often the interpolator should // * switch between 0 and 1. // */ // private double cycleCount; // // /** // * Specifies if alternating cycles reverse the animation's direction. For // * example, if you have a PathTransition with autoReverse set to // * <code>true</code>, then the object will move back and forth on the // path. // */ // private boolean autoReverse; // // /** // * Stores the delay (in millis) for the start of the transition. // */ // private long delayMillis; // // /** // * Stores an {@link IEventHandler} that is executed when the animation // * finishes. An animation finishes after // * <code>cycleCount * cycleDuration</code> (millis). // */ // private IEventHandler<ActionEvent> onFinished; private long startMillis; private boolean running; public AbstractTransition(long durationMillis) { this.cycleDurationMillis = durationMillis; } public abstract void doStep(double t); public abstract void doUpdate(); public long getDuration() { return cycleDurationMillis; } public IInterpolator getInterpolator() { return interpolator; } public void play() { if (running) { stop(); } running = true; step(0); Timer timer = new Timer(true); timer.schedule(new TimerTask() { @Override public void run() { long millis = System.currentTimeMillis(); if (startMillis == 0) { startMillis = millis; } long deltaMillis = millis - startMillis; double t = deltaMillis / (double) cycleDurationMillis; if (t > 1) { cancel(); stop(); } else { step(getInterpolator().curve(t)); } } }, 0, PERIOD); } public void setInterpolator(IInterpolator interpolator) { this.interpolator = interpolator; } public void step(double t) { doStep(t); doUpdate(); } public void stop() { if (!running) { return; } running = false; startMillis = 0; step(1); } }
true
ea4f28b7e322de8e4645a4f8daa63dde46798b75
Java
lvhailing/owner_project3
/app/src/main/java/com/haidehui/common/MyApplication.java
UTF-8
4,690
1.8125
2
[]
no_license
package com.haidehui.common; import android.app.Application; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.haidehui.R; import com.haidehui.network.http.APNManager; import com.haidehui.photo_preview.fresco.ImageLoader; import com.haidehui.uitls.ImageLoaderManager; import com.haidehui.uitls.NetworkUtils; import com.haidehui.uitls.PreferenceUtil; import com.haidehui.uitls.SystemInfo; import com.haidehui.uitls.CityDataHelper; import java.io.InputStream; import java.util.HashSet; import okhttp3.OkHttpClient; public class MyApplication extends Application { private static MyApplication instance; public static String mAppId; public static String mDownloadPath; private static final String TAG = "Init"; private CityDataHelper dataHelper; private BroadcastReceiver mReceiver; public String netType; IntentFilter mFilter; HashSet<NetListener> mListeners = new HashSet<NetListener>(); public static MyApplication getInstance() { return instance; } @Override public void onCreate() { super.onCreate(); instance = this; NetworkUtils.setContext(this); PreferenceUtil.initialize(this); SystemInfo.initialize(this); initNetReceiver(); //imageLoader初始化 ImageLoaderManager.initImageLoader(this); mAppId = getString(R.string.app_id); mDownloadPath = "/" + mAppId + "/download"; //fresco初始化 ImageLoader.getInstance().initImageLoader(getResources(), 1); APNManager.getInstance().checkNetworkType(this); //拷贝数据库文件 dataHelper = CityDataHelper.getInstance(this); InputStream in = this.getResources().openRawResource(R.raw.province); dataHelper.copyFile(in, CityDataHelper.DATABASE_NAME, CityDataHelper.DATABASES_DIR); //ShareSDK 初始化 // ShareSDK.initSDK(instance); //3.X版本以上含3.X版本,ShareSDK 初始化 // 通过代码注册你的AppKey和AppSecret // MobSDK.init(instance, "1ea86a798f5d6", "69d1ab82675b878c6061887a6ab49279"); //3.1.4版本 ShareSDK 初始化 // MobSDK.init(this); } public interface NetListener { void onNetWorkChange(String netType); } /** * 加入网络监听 * * @param l * @return */ public boolean addNetListener(NetListener l) { boolean rst = false; if (l != null && mListeners != null) { rst = mListeners.add(l); } return rst; } /** * 移除网络监听 * * @param l * @return */ public boolean removeNetListener(NetListener l) { return mListeners.remove(l); } /** * 初始化网络监听器 */ private void initNetReceiver() { mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info != null && info.isConnected()) { netType = info.getTypeName(); } else { netType = ""; } for (NetListener lis : mListeners) { if (lis != null) { lis.onNetWorkChange(netType); } } } } }; mFilter = new IntentFilter(); mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); } /** * 注册网络监听器 */ public void registReceiver() { try { registerReceiver(mReceiver, mFilter); } catch (Exception e) { } } /** * 注销网络监听器 */ public void unRegisterNetListener() { if (mListeners != null) { mListeners.clear(); } try { unregisterReceiver(mReceiver); } catch (Exception e) { // TODO: handle exception } } }
true
33ff5ee1a37e7e5327541e27b695ed5278d9266e
Java
gkancheva/AndroidProjects
/Projects@UdacityCourse/popular-movies/app/src/main/java/com/company/popularmovies/data/MovieDBHelper.java
UTF-8
1,378
2.59375
3
[]
no_license
package com.company.popularmovies.data; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class MovieDBHelper extends SQLiteOpenHelper { private static final String DB_NAME = "movies_db"; private static final int DB_VERSION = 1; MovieDBHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { final String SQL_CREATE_TABLE_STATEMENT = "CREATE TABLE " + MovieDBEntry.TABLE_NAME + " (" + MovieDBEntry._ID + " INTEGER PRIMARY KEY, " + MovieDBEntry.COLUMN_NAME + " TEXT NOT NULL, " + MovieDBEntry.COLUMN_THUMBNAIL + " BLOB NOT NULL, " + MovieDBEntry.COLUMN_OVERVIEW + " TEXT NOT NULL, " + MovieDBEntry.COLUMN_RATING + " DOUBLE NOT NULL, " + MovieDBEntry.COLUMN_TIMESTAMP + " TIMESTAMP NOT NULL);"; sqLiteDatabase.execSQL(SQL_CREATE_TABLE_STATEMENT); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { if(oldVersion < newVersion) { // alter table accordingly without loosing data sqLiteDatabase.execSQL("ALTER TABLE " + MovieDBEntry.TABLE_NAME); } } }
true
a059b6e0b3107a3ee5d6d3a022baa3c78ec7bfa1
Java
shekhfiroz/orm_technology
/00_poctest/src/acessmodifiers/Book.java
UTF-8
121
2.046875
2
[]
no_license
package acessmodifiers; public class Book { public void read() { System.out.println("Read Method is called.."); } }
true
ef67df3ad43d82eeddea5afde7f6b60f8597ed1f
Java
AswinBahulayan/RandomPrograms
/src/main/java/fibonacci/Fibinacci.java
UTF-8
278
3.3125
3
[]
no_license
package fibonacci; public class Fibinacci { public static void fib(int n) { int f1=0,f2=1; System.out.println(f1); System.out.println(f2); for(int i=0;i<=n;i++) { int temp=f1+f2; f1=f2; f2=temp; System.out.println(temp); } } }
true
317ecff823c54132c019893d6c7767b1a83f451c
Java
k8440009/Algorithm
/Java/BOJ/Java_17140.java
UTF-8
5,069
3.203125
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; class Unit implements Comparable<Unit>{ int num, cnt; Unit (int num, int cnt) { this.num = num; this.cnt = cnt; } @Override public int compareTo(Unit o) { if (this.cnt == o.cnt) { return Integer.compare(this.num, o.num); } else { return Integer.compare(this.cnt, o.cnt); } } } public class Java_17140 { static boolean printFlag = false; static int R; static int C; static int K; static int [][] board = new int [100][100]; static int rSize = 3; static int cSize = 3; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String [] tokens = br.readLine().split(" "); R = Integer.parseInt(tokens[0]) - 1; C = Integer.parseInt(tokens[1]) - 1; K = Integer.parseInt(tokens[2]); for (int r = 0; r < 3; r++) { tokens = br.readLine().split(" "); for (int c = 0; c < 3; c++) { board[r][c] = Integer.parseInt(tokens[c]); } } int time = 0; boolean success = false; while(time <= 100) { // 0. 보드 체크 if (board[R][C] == K) { success = true; break; } /** * 1.연산 */ if (rSize >= cSize) { rCalculate(); } else { cCalculate(); } printBoard(); time += 1; } if (success) { System.out.println(time); } else { System.out.println(-1); } } static void cCalculate() { ArrayList<Integer> next[] = new ArrayList[cSize]; ArrayList<Unit> arr[] = new ArrayList[cSize]; int maxSize = 0; for (int c = 0; c < cSize; c++) { Map<Integer, Integer> map = new HashMap<>(); arr[c] = new ArrayList<>(); next[c] = new ArrayList<>(); for (int r = 0; r < rSize; r++) { int num = board[r][c]; if (num == 0) continue; if (map.containsKey(num)) { map.put(num, map.get(num) + 1); } else { map.put(num, 1); } } // 정렬을 위해 데이터 넣기 for (Map.Entry<Integer, Integer> entry : map.entrySet()) { arr[c].add(new Unit(entry.getKey(), entry.getValue())); } Collections.sort(arr[c]); for (Unit unit : arr[c]) { next[c].add(unit.num); next[c].add(unit.cnt); } if (next[c].size() > maxSize) { maxSize = next[c].size(); } } // 초과하는 경우 if (maxSize> 100) maxSize = 100; rSize = maxSize; // System.out.println("rSize=" + rSize + " cSize=" + cSize); for (int c = 0; c < cSize; c++) { int listSize = next[c].size(); /** * 길이 조절 */ if (listSize >= maxSize) { for (int r = 0; r < maxSize; r++) { // System.out.println("test1"); // System.out.println("r=" + r + " c=" + c); board[r][c] = next[c].get(r); } } else { for (int r = 0; r < maxSize; r++) { if (r >= listSize) { // System.out.println("test2"); // System.out.println("r=" + r + " c=" + c); board[r][c] = 0; } else { // System.out.println("test3"); // System.out.println("r=" + r + " c=" + c); board[r][c] = next[c].get(r); } } } } } static void rCalculate() { ArrayList<Integer> next[] = new ArrayList[rSize]; ArrayList<Unit> arr[] = new ArrayList[rSize]; int maxSize = 0; for (int r = 0; r < rSize; r++) { Map<Integer, Integer> map = new HashMap<>(); arr[r] = new ArrayList<>(); next[r] = new ArrayList<>(); for (int c = 0; c < cSize; c++) { int num = board[r][c]; if (num == 0) continue; if (map.containsKey(num)) { map.put(num, map.get(num) + 1); } else { map.put(num, 1); } } // 정렬을 위해 데이터 넣기 for (Map.Entry<Integer, Integer> entry : map.entrySet()) { arr[r].add(new Unit(entry.getKey(), entry.getValue())); } Collections.sort(arr[r]); //System.out.println("r=" + r); for (Unit unit : arr[r]) { //System.out.println("num=" + unit.num + " cnt=" + unit.cnt); next[r].add(unit.num); next[r].add(unit.cnt); } if (next[r].size() > maxSize) { maxSize = next[r].size(); } } // 2, 1 1 2 // 1 1 2 1 3 1 // 3 3 // 초과하는 경우 if (maxSize> 100) maxSize = 100; cSize = maxSize; for (int r = 0; r < rSize; r++) { int listSize = next[r].size(); /** * 길이 조절 */ if (listSize >= maxSize) { for (int c = 0; c < maxSize; c++) { board[r][c] = next[r].get(c); } } else { for (int c = 0; c < maxSize; c++) { if (c >= listSize) { board[r][c] = 0; } else { board[r][c] = next[r].get(c); } } } } } static void printBoard() { if (!printFlag) return ; System.out.println("rSize=" + rSize + " cSize=" + cSize); for (int r = 0; r < rSize; r++) { for (int c = 0; c < cSize; c++) { System.out.print(board[r][c] + " "); } System.out.println(); } } }
true
6264c386d30b9a2581c2122898ae829b24581ef4
Java
stephdz/Roundish
/roundish/src/main/java/fr/dz/roundish/rest/RESTAuthenticationHandler.java
UTF-8
3,020
2.453125
2
[]
no_license
package fr.dz.roundish.rest; import javax.inject.Singleton; import javax.servlet.http.HttpSession; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import lombok.Getter; import lombok.extern.log4j.Log4j; import fr.dz.roundish.Application; import fr.dz.roundish.User; import fr.dz.roundish.rest.model.LoginInfo; import fr.dz.roundish.util.JsonUtils; /** * REST authentication handler */ @Log4j @Getter @Singleton @Path("auth") public class RESTAuthenticationHandler extends RESTHandler { // Constants private static final String CONNECTED_USER = "roundish.connectedUser"; /** * Constructor * * @param application */ public RESTAuthenticationHandler(final Application application) { super(application); } /* * Real definition used by Application */ @Override public User getConnectedUser() { return (User) getRequest().getSession().getAttribute(CONNECTED_USER); } /** * Return the connected user * * @param loginInfoJson * @return */ @GET @Produces(MediaType.APPLICATION_JSON) public Response connectedUser() { try { return handleEntity(getConnectedUser()); } catch (Throwable t) { return handleException(t); } } /** * Perform user login * * @param loginInfoJson * @return */ @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response login(final String loginInfoJson) { try { // Do the login LoginInfo loginInfo = JsonUtils.convertToEntity(loginInfoJson, LoginInfo.class); User loggedUser = getApplication().login(loginInfo.getLogin(), loginInfo.getPassword()); if (loggedUser != null) { log.debug("User '" + loginInfo.getLogin() + "' successfully connected"); // Enforce to create a JSESSIONID and register the connected // user HttpSession session = getRequest().getSession(); session.setAttribute(CONNECTED_USER, loggedUser); } else { log.debug("User '" + loginInfo.getLogin() + "' failed to connect"); } // Return the user return handleEntity(loggedUser); } catch (Throwable t) { return handleException(t); } } @DELETE @Produces(MediaType.APPLICATION_JSON) public Response logout() { try { // Do the logout User loggedUser = getConnectedUser(); getApplication().logout(getRequest()); if (loggedUser != null) { log.debug("User '" + loggedUser.getLogin() + "' successfully disconnected"); } // Clear the session getRequest().getSession().invalidate(); return Response.status(Response.Status.OK).build(); } catch (Throwable t) { return handleException(t); } } }
true
78d11befb2d5486574775d78c662cd8851c4a416
Java
Talentica/HungryHippos
/client-api/src/test/java/com/talentica/hungryHippos/client/domain/ValueSetTest.java
UTF-8
4,657
2.546875
3
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright 2017 Talentica Software Pvt. Ltd. * * 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.talentica.hungryHippos.client.domain; import java.util.HashMap; import java.util.Map; import org.junit.Assert; import org.junit.Test; public class ValueSetTest { @Test public void testToString() { ValueSet valueSet = new ValueSet(new int[] { 0, 1 }, new String[] { "India", "Sony" }); String actual = valueSet.toString(); Assert.assertEquals("India-Sony", actual); } @Test public void testValueSetCompare(){ MutableCharArrayString string1 = new MutableCharArrayString(1); string1.addByte((byte)'a'); MutableCharArrayString string2 = new MutableCharArrayString(1); string2.addByte((byte)'a'); MutableCharArrayString string3 = new MutableCharArrayString(1); string3.addByte((byte)3); ValueSet valueSet1 = new ValueSet(new int[] { 0, 1, 3 }, new MutableCharArrayString[] { string1, string2 , string3}); MutableCharArrayString string4 = new MutableCharArrayString(1); string4.addByte((byte)'a'); MutableCharArrayString string5 = new MutableCharArrayString(1); string5.addByte((byte)'a'); MutableCharArrayString string6 = new MutableCharArrayString(1); string6.addByte((byte)5); ValueSet valueSet2 = new ValueSet(new int[] { 0, 1, 3 }, new MutableCharArrayString[] { string4, string5,string6 }); Map<ValueSet,String> valueSetMap = new HashMap<>(); valueSetMap.put(valueSet1, "testString1"); valueSetMap.put(valueSet2, "testString2"); Assert.assertEquals("testString1", valueSetMap.get(valueSet1)); Assert.assertEquals("testString2", valueSetMap.get(valueSet2)); } @Test public void testEquals() { ValueSet valueSet1 = new ValueSet(new int[] { 0, 1 }, new String[] { "India", "Sony" }); ValueSet valueSet2 = new ValueSet(new int[] { 0, 1 }, new String[] { "India", "Sony" }); Assert.assertEquals(valueSet1, valueSet2); } @Test public void testEqualsForDifferentIndexes() { ValueSet valueSet1 = new ValueSet(new int[] { 0, 1 }, new String[] { "India", "Sony" }); ValueSet valueSet2 = new ValueSet(new int[] { 1, 0 }, new String[] { "India", "Sony" }); Assert.assertNotEquals(valueSet1, valueSet2); } @Test public void testCompareToOfNotSameLengthValueSets() { ValueSet valueSet1 = new ValueSet(new int[] { 0, 1 }, new String[] { "India", "Sony" }); ValueSet valueSet2 = new ValueSet(new int[] { 1 }, new String[] { "India" }); Assert.assertTrue(valueSet1.compareTo(valueSet2) > 0); Assert.assertTrue(valueSet2.compareTo(valueSet1) < 0); } @Test public void testCompareToOfSameValueSets() { MutableCharArrayString string1 = new MutableCharArrayString(2); ValueSet valueSet1 = new ValueSet(new int[] { 0, 1 }, new MutableCharArrayString[] { string1, string1 }); ValueSet valueSet2 = new ValueSet(new int[] { 0, 1 }, new MutableCharArrayString[] { string1, string1 }); Assert.assertTrue(valueSet1.compareTo(valueSet2) == 0); Assert.assertTrue(valueSet2.compareTo(valueSet1) == 0); } @Test public void testCompareToOfValueSetsOfSameSize() throws InvalidRowException { MutableCharArrayString country1 = new MutableCharArrayString(3); country1.addByte((byte)'I').addByte((byte)'n').addByte((byte)'d'); MutableCharArrayString device1 = new MutableCharArrayString(3); device1.addByte((byte)'S').addByte((byte)'a').addByte((byte)'m'); ValueSet valueSet1 = new ValueSet(new int[] { 0, 1 }, new MutableCharArrayString[] { country1, device1 }); MutableCharArrayString country2 = new MutableCharArrayString(3); country2.addByte((byte)'I').addByte((byte)'n').addByte((byte)'d'); MutableCharArrayString device2 = new MutableCharArrayString(3); device2.addByte((byte)'S').addByte((byte)'o').addByte((byte)'n'); ValueSet valueSet2 = new ValueSet(new int[] { 0, 1 }, new MutableCharArrayString[] { country2, device2 }); Assert.assertTrue(valueSet1.compareTo(valueSet2) < 0); Assert.assertTrue(valueSet2.compareTo(valueSet1) > 0); } }
true
41c818a8dbe26e846563c3c7f897c1b1ac201768
Java
zhslv/libraysys
/src/com/zhs/sys/service/BookInfoService.java
UTF-8
309
1.75
2
[]
no_license
package com.zhs.sys.service; import com.zhs.sys.domain.BookInfo; import com.zhs.sys.utils.PageBean; import java.util.List; public interface BookInfoService { List<BookInfo> queryBookInfoForPage(PageBean pageBean,BookInfo bookInfo); void updateBookInfoBorrowState(Integer bookid, Integer state); }
true
24e9c8bcc4ae044a1a60ffb0a33bc76c2b58fdaf
Java
motsneha/locobot
/LocoBotAppActivity/src/bot/location/locobotapp/StBusActivity.java
UTF-8
6,553
2.15625
2
[]
no_license
package bot.location.locobotapp; import java.io.BufferedReader; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.Toast; public class StBusActivity extends Activity implements OnItemSelectedListener,OnClickListener{ private String[] sources = {"Amravati"}; private String sourceItem; private String destItem; private static final String SERVICE_URL ="http://env-3776051.jelastic.servint.net/locobota/st";//"http://10.0.2.2:8080/com.locobot.busservice/st";//http://env-3776051.jelastic.servint.net/locobota/st/amravati/nagpur private String service_url_add; private ProgressDialog dialog; private String server_result; private Button searchButton; private AlertManager alert=new AlertManager(); private InternetConnection cd; Boolean isInternetPresent = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_st_bus); searchButton=(Button)findViewById(R.id.busSearch); searchButton.setOnClickListener(this); dialog=new ProgressDialog(this); cd = new InternetConnection(getApplicationContext()); isInternetPresent = cd.isConnectingToInternet(); if (!isInternetPresent) { // Internet Connection is not present alert.showAlertDialog(StBusActivity.this, "Internet Connection Error", "Please connect to working Internet connection", false); // stop executing code by return return; } Spinner sourceSpinner = (Spinner)findViewById(R.id.sourceSpinner); ArrayAdapter<String> sourceAdapt = new ArrayAdapter<String>(this,R.layout.spinner_item,sources); //sourceAdapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sourceSpinner.setAdapter(sourceAdapt); sourceSpinner.setOnItemSelectedListener(this); Spinner destinSpinner = (Spinner)findViewById(R.id.destinSpinner); ArrayAdapter<CharSequence> destAdapt = ArrayAdapter.createFromResource(this, R.array.destinations2,R.layout.spinner_item); //destAdapt.setDropDownViewResource(R.layout.spinner_item); destinSpinner.setAdapter(destAdapt); destinSpinner.setOnItemSelectedListener(this); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position,long id) { // TODO Auto-generated method stub Spinner spin = (Spinner)parent; Spinner spin2 = (Spinner)parent; if(spin.getId() == R.id.sourceSpinner) { sourceItem=(String)spin.getSelectedItem(); Log.d("StBusActivity",sourceItem); } if(spin2.getId() == R.id.destinSpinner) { destItem=(String)spin2.getSelectedItem(); Log.d("StBusActivity", destItem); } } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub Toast.makeText(this, "Select city",Toast.LENGTH_SHORT).show(); } public void SetResult(String result){ this.server_result=result; Log.d("StBusActivity",server_result); } private class LongRunningGetIO extends AsyncTask <Void, Void,String> { private String service_url; LongRunningGetIO(String url) { service_url=url; } public void onPreExecute() { searchButton.setClickable(false); dialog.setMessage("Loading results"); dialog.setCancelable(false); dialog.setCanceledOnTouchOutside(false); dialog.show(); } @Override protected String doInBackground(Void... params) { // TODO Auto-generated method stub String text = null; HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet(service_url); try { HttpResponse response = httpClient.execute(httpGet, localContext); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } text=builder.toString(); Log.d("StBusActivity",text); StBusActivity.this.SetResult(text); // return text; } catch (Exception e) { e.getLocalizedMessage(); } return text; } public void onPostExecute(String result) { if(result!=null) { Log.d("StBusActivity",result); StBusActivity.this.SetResult(result); } if (dialog.isShowing()) { dialog.dismiss(); } searchButton.setClickable(true); Intent intent =new Intent(StBusActivity.this,StBusResultActivity.class); Bundle bundle = new Bundle(); bundle.putString("src",sourceItem); bundle.putString("dest",destItem); bundle.putString("result",server_result); intent.putExtras(bundle); startActivity(intent); } } @Override public void onClick(View view) { // TODO Auto-generated method stub if(view.getId()==R.id.busSearch) { if((sourceItem!=null)&& (destItem!=null)) { service_url_add=SERVICE_URL+"/"+sourceItem+"/"+destItem; Log.d("StBusActivity",service_url_add); (new LongRunningGetIO(service_url_add)).execute(); } else { if(sourceItem==null) {Toast.makeText(this,"Select source",Toast.LENGTH_SHORT).show(); } if(destItem==null) {Toast.makeText(this,"Select destination",Toast.LENGTH_SHORT).show(); } } } } }
true
517a5cca2fcc3a87e489cb599c3f8a14d816a17f
Java
ChenJiahao0205/demo-typehandler
/src/main/java/pers/chenjiahao/typehandler/entity/User.java
UTF-8
674
1.96875
2
[]
no_license
package pers.chenjiahao.typehandler.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import pers.chenjiahao.typehandler.handler.UserInfoTypeHandler; /** * @Author ChenJiahao(五条) * @Date 2021/8/21 19:34 */ @Data @TableName(value = "user",autoResultMap = true) public class User { @TableId(type = IdType.AUTO) private Integer id; private String name; @TableField(value = "user_info",typeHandler = UserInfoTypeHandler.class) private UserInfo userInfo; }
true
99ecb380184d0241797e099ec3902d9e42be2564
Java
AdrianRomo/Teoria-Computacional
/Practica7TC/src/sources/APND.java
UTF-8
11,443
3.09375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sources; import java.util.ArrayList; import java.util.Stack; /** * * @author Adrian */ public class APND { String cadena; Stack<String> pila1 = new Stack(); Stack<String> pila2 = new Stack(); public APND() { } public APND(String cadena) { this.cadena = cadena; } public void setCadena(String cadena) { this.cadena = cadena; } public String getCadena() { return cadena; } public boolean validarEjercicio5() { ArrayList<Integer> estados = new ArrayList(); estados.add(0); pila1.push("Z"); pila2.push("Z"); for(int i=0;i<cadena.length();i++) { for(int j=0;j<estados.size();j++) { if(cadena.charAt(i)=='a') { if(estados.get(j)==0) { if(pila1.lastElement().equals("Z")) { pila1.push("A"); estados.set(j, 1); } if(pila2.lastElement().equals("Z")) { pila2.push("A"); estados.add(5); break; } else { estados.set(j,9); } } else if(estados.get(j)==1) { if(pila1.lastElement().equals("A")) { pila1.push("A"); estados.set(j, 1); } else { estados.set(j,9); } } else if (estados.get(j)==5) { if(pila2.lastElement().equals("A")) { pila2.push("A"); estados.set(j, 5); } else { estados.set(j,9); } } else { estados.set(j,9); } } else if(cadena.charAt(i)=='b') { if(estados.get(j)==1) { if(pila1.lastElement().equals("A")) { pila1.push("B"); estados.set(j,2); } else { estados.set(j,9); } } else if(estados.get(j)==2) { if(pila1.lastElement().equals("B")) { pila1.push("B"); estados.set(j,2); } else { estados.set(j,9); } } else if(estados.get(j)==5) { if(pila2.lastElement().equals("A")) { estados.set(j,6); } else { estados.set(j,9); } } else if(estados.get(j)==6) { if(pila2.lastElement().equals("A")) { pila2.pop(); estados.set(j,7); } else { estados.set(j,9); } } else if(estados.get(j)==7) { if(pila2.lastElement().equals("A")) { estados.set(j,6); } else { estados.set(j,9); } } else { estados.set(j,9); } } else if(cadena.charAt(i)=='c') { if(estados.get(j)==2) { if(pila1.lastElement().equals("B")) { pila1.pop(); estados.set(j,3); } else { estados.set(j,9); } } else if(estados.get(j)==3) { if(pila1.lastElement().equals("B")) { pila1.pop(); estados.set(j,3); } else if(pila1.lastElement().equals("A")) { pila1.pop(); estados.set(j,4); } else { estados.set(j,9); } } else if(estados.get(j)==4) { if(pila1.lastElement().equals("A")) { pila1.pop(); estados.set(j,4); } else { estados.set(j,9); } } else { estados.set(j,9); } } else { estados.set(j,9); } } } if((estados.contains(4) && pila1.lastElement().equals("Z")) || (estados.contains(7) && pila2.lastElement().equals("Z"))) { return true; } else { return false; } } public boolean validarEjercicio4() { ArrayList<Integer> estados = new ArrayList(); estados.add(0); pila1.push("Z"); pila2.push("Z"); for(int i=0;i<cadena.length();i++) { for(int j=0;j<estados.size();j++) { if(cadena.charAt(i)=='a') { if(estados.get(j)==0) { if(pila1.lastElement().equals("Z")) { pila1.push("A"); estados.set(j, 1); } if(pila2.lastElement().equals("Z")) { pila2.push("A"); estados.add(5); break; } else { estados.set(j,9); } } else if(estados.get(j)==1) { if(pila1.lastElement().equals("A")) { pila1.push("A"); estados.set(j, 1); } else { estados.set(j,9); } } else if (estados.get(j)==5) { if(pila2.lastElement().equals("A")) { estados.set(j, 6); } else { estados.set(j,9); } } else if (estados.get(j)==6) { if(pila2.lastElement().equals("A")) { pila2.push("A"); estados.set(j, 5); } else { estados.set(j,9); } } else { estados.set(j,9); } } else if(cadena.charAt(i)=='b') { if(estados.get(j)==1) { if(pila1.lastElement().equals("A")) { pila1.push("B"); estados.set(j,2); } else { estados.set(j,9); } } else if(estados.get(j)==2) { if(pila1.lastElement().equals("B")) { pila1.push("B"); estados.set(j,2); } else { estados.set(j,9); } } else if(estados.get(j)==6) { if(pila2.lastElement().equals("A")) { pila2.pop(); estados.set(j,7); } else { estados.set(j,9); } } else if(estados.get(j)==7) { if(pila2.lastElement().equals("A")) { pila2.pop(); estados.set(j,7); } else { estados.set(j,9); } } else { estados.set(j,9); } } else if(cadena.charAt(i)=='c') { if(estados.get(j)==2) { if(pila1.lastElement().equals("B")) { pila1.pop(); estados.set(j,3); } else { estados.set(j,9); } } else if(estados.get(j)==3) { if(pila1.lastElement().equals("B")) { pila1.pop(); estados.set(j,3); } else if(pila1.lastElement().equals("A")) { pila1.pop(); estados.set(j,4); } else { estados.set(j,9); } } else if(estados.get(j)==4) { if(pila1.lastElement().equals("A")) { pila1.pop(); estados.set(j,4); } else { estados.set(j,9); } } else { estados.set(j,9); } } else { estados.set(j,9); } } } if((estados.contains(4) && pila1.lastElement().equals("Z")) || (estados.contains(7) && pila2.lastElement().equals("Z"))) { return true; } else { return false; } } }
true
009eb93a7992c0862e75cc74b1a88db019cab087
Java
priyanka163/tool
/NextSWS-master/lmsclient_copy/src/main/java/com/nexteducation/swagger/nextsws/model/SubscriberRequest.java
UTF-8
4,297
2.03125
2
[]
no_license
/** * Api Documentation * Api Documentation * * OpenAPI spec version: 1.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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.nexteducation.swagger.nextsws.model; import java.util.Objects; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * SubscriberRequest */ @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2017-02-08T11:28:33.033+05:30") public class SubscriberRequest { @SerializedName("branchId") private Long branchId = null; @SerializedName("sessionId") private String sessionId = null; @SerializedName("subscriber") private Long subscriber = null; @SerializedName("userId") private Long userId = null; public SubscriberRequest branchId(Long branchId) { this.branchId = branchId; return this; } /** * Get branchId * @return branchId **/ @ApiModelProperty(example = "null", value = "") public Long getBranchId() { return branchId; } public void setBranchId(Long branchId) { this.branchId = branchId; } public SubscriberRequest sessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * Get sessionId * @return sessionId **/ @ApiModelProperty(example = "null", value = "") public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public SubscriberRequest subscriber(Long subscriber) { this.subscriber = subscriber; return this; } /** * Get subscriber * @return subscriber **/ @ApiModelProperty(example = "null", value = "") public Long getSubscriber() { return subscriber; } public void setSubscriber(Long subscriber) { this.subscriber = subscriber; } public SubscriberRequest userId(Long userId) { this.userId = userId; return this; } /** * Get userId * @return userId **/ @ApiModelProperty(example = "null", value = "") public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubscriberRequest subscriberRequest = (SubscriberRequest) o; return Objects.equals(this.branchId, subscriberRequest.branchId) && Objects.equals(this.sessionId, subscriberRequest.sessionId) && Objects.equals(this.subscriber, subscriberRequest.subscriber) && Objects.equals(this.userId, subscriberRequest.userId); } @Override public int hashCode() { return Objects.hash(branchId, sessionId, subscriber, userId); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class SubscriberRequest {\n"); sb.append(" branchId: ").append(toIndentedString(branchId)).append("\n"); sb.append(" sessionId: ").append(toIndentedString(sessionId)).append("\n"); sb.append(" subscriber: ").append(toIndentedString(subscriber)).append("\n"); sb.append(" userId: ").append(toIndentedString(userId)).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
6077848216fdcb3a40d17f19fa2facafcfbce64d
Java
bellmit/tkt-server
/cypw-tktstar/cypw-tktstar-provider/src/main/java/com/mtl/cypw/provider/mpm/endpoint/MachinePosterEndpoint.java
UTF-8
1,253
1.960938
2
[]
no_license
package com.mtl.cypw.provider.mpm.endpoint; import com.juqitech.request.IdRequest; import com.juqitech.response.ResultBuilder; import com.juqitech.response.TMultiResult; import com.mtl.cypw.api.member.endpoint.MachineApi; import com.mtl.cypw.api.mpm.endpoint.MachinePosterApi; import com.mtl.cypw.domain.mpm.dto.MachinePosterDTO; import com.mtl.cypw.mpm.model.MachinePoster; import com.mtl.cypw.mpm.service.MachinePosterService; import com.mtl.cypw.provider.mpm.converter.MachinePosterConverter; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; /** * @author tang. * @date 2020/3/16. */ @RestController @Slf4j public class MachinePosterEndpoint implements MachinePosterApi { @Resource private MachinePosterService machinePosterServiceImpl; @Resource private MachinePosterConverter machinePosterConverter; @Override public TMultiResult<MachinePosterDTO> searchMachinePoster(IdRequest request) { List<MachinePoster> machinePosters = machinePosterServiceImpl.searchMachinePoster(Integer.parseInt(request.getId())); return ResultBuilder.succTMulti(machinePosterConverter.toDto(machinePosters)); } }
true
c3fd53b263270b6587c84b3834587d0e09cedcb4
Java
SongChiyoon/codeGround
/src/Ureka.java
UTF-8
1,184
3.28125
3
[]
no_license
import java.util.Scanner; /** * Created by songchiyun on 2017. 9. 22.. */ public class Ureka { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int t=0;t<T;t++){ int N = sc.nextInt(); boolean pass = false; for(int i=1;T(i) <= N; i++){ for(int j=i; T(j) <= N; j++){ if(T(i) + T(j) >= N){ break; } for(int k=j;T(k) <= N; k++){ if(T(i) + T(j) + T(k) == N) { System.out.println("1"); pass = true; break; } if(T(i) + T(j) + T(k) > N){ break; } } if(pass) break; } if(pass) break; } if(!pass) System.out.println("0"); } } static int T(int num){ return num*(num+1)/2; } }
true
fc20ba93b3cb96e334425b4a9fa5d17aae562d93
Java
Killian-Townsend/Custom-FTC-Driver-Station-2021
/app/src/main/java/org/firstinspires/ftc/robotcore/external/tfod/TfodSkyStone.java
UTF-8
712
1.96875
2
[]
no_license
package org.firstinspires.ftc.robotcore.external.tfod; public class TfodSkyStone extends TfodBase { public static final String[] LABELS = new String[] { "Stone", "Skystone" }; public static final String LABEL_SKY_STONE = "Skystone"; public static final String LABEL_STONE = "Stone"; public static final String TFOD_MODEL_ASSET = "Skystone.tflite"; public TfodSkyStone() { super("Skystone.tflite", LABELS); } } /* Location: C:\Users\Student\Desktop\APK Decompiling\com.qualcomm.ftcdriverstation_38_apps.evozi.com\classes-dex2jar.jar!\org\firstinspires\ftc\robotcore\external\tfod\TfodSkyStone.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
true
c251fcb1ab53b7b5780920918bcfb2a532d81b0c
Java
ZLsuyan/QYKQGL
/QYKQGL/src/mypackage/NewsManage.java
GB18030
2,237
2.75
3
[]
no_license
package mypackage; public class NewsManage{ public boolean add(String newstitle,String newscontent,String newsobject,String newsaddtime){ DB db=new DB(); String sql="insert into news(news_title,news_content,news_object,news_addtime)values('"+newstitle+"','"+newscontent+"','"+newsobject+"','"+newsaddtime+"')"; boolean result = false; try { if(db.executeUpdate(sql)==1){ result = true; }else{ result = false; } }catch (Exception e) { System.err.println("Ϣ󣬴Ϣ"+e.getMessage()); } db.close(); return result; } public boolean delete(String newsid){ DB db=new DB(); boolean result = false; try { String sql="delete from news where news_id='"+newsid+"'"; if(db.executeUpdate(sql)==1){ result = true; }else{ result = false; } }catch (Exception e) { System.err.println("ɾʧܣϢ"+e.getMessage()); } db.close(); return result; } public boolean update(String newsid,String newnewstitle,String newnewscontent,String newnewsobject,String newnewsaddtime){ DB db=new DB(); boolean result = false; String sql="update news set news_title='"+newnewstitle+"',news_content='"+newnewscontent+"',news_object='"+newnewsobject+"',news_addtime='"+newnewsaddtime+"' where news_id='"+newsid+"';"; try { if(db.executeUpdate(sql)==1){ result = true; }else{ result = false; } }catch (Exception e) { System.err.println("Ϣ´󣬴Ϣ"+e.getMessage()); } db.close(); return result; } public boolean update2(String newsid,String newnewstitle,String newnewscontent,String newnewsobject){ DB db=new DB(); boolean result = false; String sql="update news set news_title='"+newnewstitle+"',news_content='"+newnewscontent+"',news_object='"+newnewsobject+"' where news_id='"+newsid+"';"; try { if(db.executeUpdate(sql)==1){ result = true; }else{ result = false; } }catch (Exception e) { System.err.println("Ϣ´󣬴Ϣ"+e.getMessage()); } db.close(); return result; } }
true
71eba49124bb95e873605d20ad9b31175be94a32
Java
mesadhan/nitrite-database
/nitrite/src/test/java/org/dizitart/no2/objects/data/ElemMatch.java
UTF-8
214
1.570313
2
[ "Apache-2.0" ]
permissive
package org.dizitart.no2.objects.data; import lombok.Data; /** * @author Anindya Chatterjee */ @Data public class ElemMatch { private long id; private String[] strArray; private ProductScore[] productScores; }
true
c1f6eb4bd00e1e4061e953bf6e8c306440c552ed
Java
Zartemius/PetroGuide
/app/src/main/java/com/example/darte/petroguide/presenter/domain/interactor/DbSynchronization.java
UTF-8
3,685
2.46875
2
[]
no_license
package com.example.darte.petroguide.presenter.domain.interactor; import android.util.Log; import com.example.darte.petroguide.presenter.domain.model.Place; import com.example.darte.petroguide.presenter.domain.repositories.AppRepository; import com.example.darte.petroguide.presenter.domain.repositories.CloudRepository; import io.reactivex.*; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Action; import io.reactivex.observers.DisposableCompletableObserver; import io.reactivex.schedulers.Schedulers; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; public class DbSynchronization { private AppRepository mAppRepository; private CloudRepository mCloudRepository; @Inject public DbSynchronization(AppRepository appRepository, CloudRepository cloudRepository){ mAppRepository = appRepository; mCloudRepository = cloudRepository; } public Completable synchronizeAppDbWithCloudDbAsync(final List<Place> places){ final List<String> placesId = new ArrayList<>(); for(Place place:places){ placesId.add(place.getUniqueId()); } return Completable.fromAction(new Action() { @Override public void run() throws Exception { deleteItemsFromAppDbThatDontExistInCLoudDbAsync(placesId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new DisposableCompletableObserver() { @Override public void onComplete() { Log.i("DATA_SOURCE", "works"); Log.i("SYNCHRONIZATION", "items_deleted"); for(Place place:places) { Log.i("LOADED_PLACE", "resultList" + place.getName()); } addPlaceToAppDBAsync(places) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new DisposableCompletableObserver() { @Override public void onComplete() { Log.i("SYNCHRONIZATION", "items_added"); } @Override public void onError(Throwable e) { Log.i("SYNCHRONIZATION", "items_added_error " + e); } }); } @Override public void onError(Throwable e) { Log.i("DATA_SOURCE", "no_works" + e); } }); } }); } private Completable addPlaceToAppDBAsync(final List<Place> places) { return Completable.fromAction(new Action() { @Override public void run() throws Exception { mAppRepository.insertPlace(places); } }); } private Completable deleteItemsFromAppDbThatDontExistInCLoudDbAsync(final List<String> places){ return Completable.fromAction(new Action() { @Override public void run() throws Exception { mAppRepository.deletePlaces(places); } }); } public Single<List<Place>> loadPlacesFromServerAsync(){ return mCloudRepository.getPlaces(); } }
true
fe7a2dd9faf61f8915d55a502a93fb3f508b0f1e
Java
solvek/AudioSpeakerTest
/doc/LesserAudioSwitch_v.2.7.2(124)_source_from_JADX/sources/p000/C0692jp.java
UTF-8
1,193
1.710938
2
[]
no_license
package p000; import android.content.Context; import android.content.Intent; import com.nordskog.LesserAudioSwitch.SoundBroadcastReceiver; /* renamed from: jp */ public final /* synthetic */ class C0692jp implements Runnable { /* renamed from: b */ public final /* synthetic */ C1274vp f2925b; /* renamed from: c */ public final /* synthetic */ boolean f2926c; public /* synthetic */ C0692jp(C1274vp vpVar, boolean z) { this.f2925b = vpVar; this.f2926c = z; } public final void run() { C1274vp vpVar = this.f2925b; boolean z = this.f2926c; C1324wp wpVar = vpVar.f4839b; if (wpVar.f4984f == z || !wpVar.f4983e) { wpVar.f4984f = z; return; } wpVar.f4984f = z; if (!z) { Context context = wpVar.f4979a; SoundBroadcastReceiver.C0339a aVar = SoundBroadcastReceiver.f1738a; Intent intent = new Intent(context, SoundBroadcastReceiver.class); intent.setAction(C0200av.m970a(-90609608381612L)); intent.putExtra(C0200av.m970a(-90815766811820L), true); context.sendBroadcast(intent); } } }
true