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
e750eed119ae7ea3bfea8dba5dbb3d24e7503cf6
Java
NicEastvillage/Uni-OOP
/src/week2/assignment/items/Juice.java
UTF-8
522
3.515625
4
[]
no_license
package week2.assignment.items; import java.util.Date; public class Juice extends Item implements Drinkable { public static final String NAME = "Juice"; public Juice(Date expiration) { super(NAME, 4, expiration); } @Override public void drink(Date when) { if (isExpired(when)) { System.out.println("You drank the juice. A bit sour. Was it expired?"); } else { System.out.println("You drank the juice and are filled with energy!"); } } }
true
8d41b59e2b57929718c24dcdd3efcd16751c28ab
Java
mustafaonurdurkal/kafe
/src/tr/edu/deu/ceng/coffie/entity/applicationform/CheckOut.java
UTF-8
1,168
2.46875
2
[]
no_license
package tr.edu.deu.ceng.coffie.entity.applicationform; import java.awt.EventQueue; import java.io.IOException; import javax.swing.JFrame; public class CheckOut { private JFrame frame,parent; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { CheckOut window = new CheckOut(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public CheckOut() { initialize(); } public CheckOut(JFrame pr) { this.parent =pr; initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(0, 0, 1280, 720); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setUndecorated(true); frame.setVisible(true); BCheckOut cout =null; try { cout=new BCheckOut("resources/background2.jpg",parent,frame); frame.getContentPane().add(cout); }catch(IOException e) { e.printStackTrace(); } cout.checkoutmethod(); } }
true
4bb2d9de8658e93146b2e13a37f490f5f14107a9
Java
Wildprogrammingape/Spring-Project
/spring-demo-one/src/myspringdemo/TrackCoach.java
UTF-8
614
2.796875
3
[]
no_license
package myspringdemo; public class TrackCoach implements Coach { private FortuneService fortuneService; public TrackCoach(FortuneService fortuneService) { this.fortuneService = fortuneService; } @Override public String getDailyWorkout() { return "Run a hard 5k"; } @Override public String getFortune() { return "Just do it :" + fortuneService.getFortune(); } // add an init method public void dostartup() { System.out.println("TrackCoach: inside method startup"); } // add a destroy method public void docleanup() { System.out.println("TrackCoach: inside method cleanup"); } }
true
2fc762a8d18c86a01820f2cae18daddc39873a7b
Java
trenellgalman/ru102j
/src/main/java/com/redislabs/university/ru102j/dao/SiteGeoDaoRedisImpl.java
UTF-8
4,706
2.25
2
[ "MIT" ]
permissive
package com.redislabs.university.ru102j.dao; import com.redislabs.university.ru102j.api.Coordinate; import com.redislabs.university.ru102j.api.GeoQuery; import com.redislabs.university.ru102j.api.Site; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import redis.clients.jedis.GeoRadiusResponse; import redis.clients.jedis.GeoUnit; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.Pipeline; import redis.clients.jedis.Response; public class SiteGeoDaoRedisImpl implements SiteGeoDao { private static final Double CAPACITY_THRESHOLD = 0.2; private final JedisPool jedisPool; public SiteGeoDaoRedisImpl(JedisPool jedisPool) { this.jedisPool = jedisPool; } @Override public Site findById(long id) { try (Jedis jedis = jedisPool.getResource()) { Map<String, String> fields = jedis.hgetAll(RedisSchema.getSiteHashKey(id)); if (fields == null || fields.isEmpty()) { return null; } return new Site(fields); } } @Override public Set<Site> findAll() { try (Jedis jedis = jedisPool.getResource()) { Set<String> keys = jedis.zrange(RedisSchema.getSiteGeoKey(), 0, -1); Pipeline pipeline = jedis.pipelined(); Set<Response<Map<String, String>>> sites = keys.stream().map(pipeline::hgetAll) .collect(Collectors.toSet()); pipeline.sync(); return sites.stream().map(Response::get).map(Site::new).collect(Collectors.toSet()); } } @Override public Set<Site> findByGeo(GeoQuery query) { if (query.onlyExcessCapacity()) { return findSitesByGeoWithCapacity(query); } else { return findSitesByGeo(query); } } // Challenge #5 // private Set<Site> findSitesByGeoWithCapacity(GeoQuery query) { // return Collections.emptySet(); // } // Comment out the above, and uncomment what's below private Set<Site> findSitesByGeoWithCapacity(GeoQuery query) { Double radius = query.getRadius(); double latitude = query.getCoordinate().getLat(); double longitude = query.getCoordinate().getLng(); GeoUnit unit = query.getRadiusUnit(); try (Jedis jedis = jedisPool.getResource()) { Pipeline pipeline = jedis.pipelined(); // START Challenge #5 // TODO: Challenge #5: Get the sites matching the geo query, store them // in List<GeoRadiusResponse> radiusResponses; // END Challenge #5 List<GeoRadiusResponse> radiusResponses = jedis.georadius(RedisSchema.getSiteGeoKey(), longitude, latitude, radius, unit); Set<Response<Map<String, String>>> siteResponses = radiusResponses.stream() .map(response -> pipeline.hgetAll(response.getMemberByString())).collect(Collectors.toSet()); pipeline.sync(); Set<Site> sites = siteResponses.stream().map(Response::get).map(Site::new).collect(Collectors.toSet()); // START Challenge #5 // TODO: Challenge #5: Add the code that populates the scores HashMap... // END Challenge #5 Map<Long, Response<Double>> scores = sites.stream() .map(site -> Map.entry(site.getId(), pipeline.zscore(RedisSchema.getCapacityRankingKey(), site.getId().toString()))) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); pipeline.sync(); return sites.stream().filter(site -> scores.get(site.getId()).get() >= CAPACITY_THRESHOLD) .collect(Collectors.toSet()); } } private Set<Site> findSitesByGeo(GeoQuery query) { Coordinate coord = query.getCoordinate(); Double radius = query.getRadius(); GeoUnit radiusUnit = query.getRadiusUnit(); try (Jedis jedis = jedisPool.getResource()) { List<GeoRadiusResponse> radiusResponses = jedis.georadius(RedisSchema.getSiteGeoKey(), coord.getLng(), coord.getLat(), radius, radiusUnit); return radiusResponses.stream().map(response -> jedis.hgetAll(response.getMemberByString())) .filter(Objects::nonNull).map(Site::new).collect(Collectors.toSet()); } } @Override public void insert(Site site) { try (Jedis jedis = jedisPool.getResource()) { String key = RedisSchema.getSiteHashKey(site.getId()); jedis.hmset(key, site.toMap()); if (site.getCoordinate() == null) { throw new IllegalArgumentException("Coordinate required for Geo " + "insert."); } double longitude = site.getCoordinate().getGeoCoordinate().getLongitude(); double latitude = site.getCoordinate().getGeoCoordinate().getLatitude(); jedis.geoadd(RedisSchema.getSiteGeoKey(), longitude, latitude, key); } } }
true
201ce38dba6a2ab41a62ba9250bc590aec4d1ee7
Java
moutainhigh/chdHRP
/src/com/chd/hrp/cost/service/analysis/AnalysisService.java
UTF-8
7,995
2.015625
2
[]
no_license
/** * @Copyright: Copyright (c) 2015-2-14 * @Company: 智慧云康(北京)数据科技有限公司 */ package com.chd.hrp.cost.service.analysis; import java.util.List; import java.util.Map; import org.springframework.dao.DataAccessException; /** * @Title. @Description. * 构成结余分析服务类<BR> * @Author: LiuYingDuo * @email: bell@s-chd.com * @Version: 1.0 */ public interface AnalysisService { public String queryAnalysisC0201(Map<String,Object> entityMap) throws DataAccessException; public String queryAnalysisC0203(Map<String,Object> entityMap) throws DataAccessException; public String queryAnalysisC0204(Map<String,Object> entityMap) throws DataAccessException; public String queryAnalysisC0205(Map<String,Object> entityMap) throws DataAccessException; public String queryAnalysisC0303(Map<String,Object> entityMap) throws DataAccessException; public String queryAnalysisC0304(Map<String,Object> entityMap) throws DataAccessException; public String queryAnalysisC0401(Map<String,Object> entityMap) throws DataAccessException; public String queryCostDeptReport_2(Map<String, Object> entityMap) throws DataAccessException; public String queryCostDeptReport_1(Map<String, Object> entityMap) throws DataAccessException; public String queryCostDeptReportThead(Map<String, Object> entityMap) throws DataAccessException; public String queryCostDeptReport(Map<String, Object> entityMap) throws DataAccessException; public String querychengbenMain(Map<String, Object> entityMap) throws DataAccessException; public String querychengbenMain2(Map<String, Object> entityMap) throws DataAccessException; public String querychengbenMain3(Map<String, Object> entityMap) throws DataAccessException; public String queryCostDeptCost(Map<String, Object> entityMap) throws DataAccessException; public String queryCostFLCost(Map<String, Object> entityMap) throws DataAccessException; public String queryCostGeneralHos(Map<String, Object> entityMap) throws DataAccessException; public String queryCostGeneralHosMed(Map<String, Object> entityMap) throws DataAccessException; public String queryCostGeneralDetailHos(Map<String, Object> entityMap) throws DataAccessException; public String queryCostGeneralDetailMedHos(Map<String, Object> entityMap) throws DataAccessException; public String queryCostVolumeProfit(Map<String, Object> entityMap) throws DataAccessException; public String queryCostVolumeProfitDetail(Map<String, Object> entityMap) throws DataAccessException; public String queryCostVolumeProfitDetailChart(Map<String, Object> entityMap) throws DataAccessException; public String queryCostBreakeven(Map<String, Object> entityMap) throws DataAccessException; public String queryCostBreakevenDetailIncome(Map<String, Object> entityMap) throws DataAccessException; public String queryCostBreakevenDetailCost(Map<String, Object> entityMap) throws DataAccessException; public String queryCostRingRatio(Map<String, Object> entityMap) throws DataAccessException; public String queryCostRingRatioDetail(Map<String, Object> entityMap) throws DataAccessException; public String queryCostRingRatioChart(Map<String, Object> entityMap) throws DataAccessException; /* * (1)医院各类科室直接成本表打印 * */ public List<Map<String, Object>> queryCostDeptReport_1print(Map<String, Object> entityMap) throws DataAccessException; /* * * (2)医院各类科室直接成本明细表打印 * */ public List<Map<String, Object>> queryCostDeptReportprint(Map<String, Object> entityMap) throws DataAccessException; /* * (3)医院临床服务类科室医疗成本分析表打印 * */ public List<Map<String, Object>> querychengbenMainprint(Map<String, Object> entityMap) throws DataAccessException; /* * (4)医院临床服务类科室医疗全成本分析表(财政)打印 * */ public List<Map<String, Object>> querychengbenMain2print(Map<String, Object> entityMap) throws DataAccessException; /* * (5)医院临床服务类科室全成本分析表打印 * */ public List<Map<String, Object>> querychengbenMain3print(Map<String, Object> entityMap) throws DataAccessException; /* * (6)医院临床服务类科室全成本分析明细表打印 * */ public List<Map<String, Object>> queryCostDeptReport_2print(Map<String, Object> entityMap) throws DataAccessException; /* * (7)医院临床服务类科室各级成本构成分析表打印 * */ public List<Map<String, Object>>queryAnalysisC0201print(Map<String, Object> entityMap) throws DataAccessException; /* * (8)临床服务类科室医疗成本构成分析明细表打印 * */ public List<Map<String, Object>> queryAnalysisC0203print(Map<String, Object> entityMap) throws DataAccessException; /* * (9)临床服务类科室医疗全成本构成分析明细表打印 * */ public List<Map<String, Object>> queryAnalysisC0204print(Map<String, Object> entityMap) throws DataAccessException; /* * (10)医院临床服务类科室全成本构成分析明细表打印 * */ public List<Map<String, Object>> queryAnalysisC0205print(Map<String, Object> entityMap) throws DataAccessException; /* * (11)医院医疗成本分类构成表打印 * */ public List<Map<String, Object>> queryAnalysisC0303print(Map<String, Object> entityMap) throws DataAccessException; /* * (12)医院医疗成本分类构成明细表打印 * */ public List<Map<String, Object>> queryAnalysisC0304print(Map<String, Object> entityMap) throws DataAccessException; /* * (13)医院科室医疗成本习性分析表打印 * */ public List<Map<String, Object>> queryAnalysisC0401print(Map<String, Object> entityMap) throws DataAccessException; /* * 科室医疗成本分摊表 * */ public List<Map<String, Object>> queryCostDeptCostprint(Map<String, Object> entityMap) throws DataAccessException; /* * 医疗成本分类分摊表 * */ public List<Map<String, Object>> queryCostFLCostprint(Map<String, Object> entityMap) throws DataAccessException; public String queryCostClinicalDeptIncomeItemColumns(Map<String, Object> entityMap) throws DataAccessException; public String queryCostClinicalDeptIncomeAnalysis(Map<String, Object> entityMap) throws DataAccessException; public List<Map<String, Object>> queryCostClinicalDeptIncomeAnalysisPrint(Map<String, Object> entityMap) throws DataAccessException; public String queryCostClinicalDeptIncomeAnalysisAppl(Map<String, Object> entityMap) throws DataAccessException; public List<Map<String, Object>> queryCostClinicalDeptIncomeAnalysisApplPrint(Map<String, Object> entityMap) throws DataAccessException; public String queryCostClinicalDeptIncomeAnalysisExec(Map<String, Object> entityMap) throws DataAccessException; public List<Map<String, Object>> queryCostClinicalDeptIncomeAnalysisExecPrint(Map<String, Object> entityMap) throws DataAccessException; public String queryCostDeptIncomeAnalysisAchievementsAppl(Map<String, Object> entityMap) throws DataAccessException; public List<Map<String, Object>> queryCostDeptIncomeAnalysisAchievementsApplPrint(Map<String, Object> entityMap) throws DataAccessException; /** * 临床科室收入分析构成表(自定义开单科室) * @param entityMap * @return * @throws DataAccessException */ public String queryCostCustomDeptIncomeAnalysisAppl(Map<String, Object> entityMap) throws DataAccessException; public List<Map<String, Object>> queryCostCustomDeptIncomeAnalysisApplPrint(Map<String, Object> entityMap) throws DataAccessException; /** * 临床科室收入分析构成表(自定义执行科室) * @param entityMap * @return * @throws DataAccessException */ public String queryCostCustomDeptIncomeAnalysisExec(Map<String, Object> entityMap) throws DataAccessException; public List<Map<String, Object>> queryCostCustomDeptIncomeAnalysisExecPrint(Map<String, Object> entityMap) throws DataAccessException; }
true
84b40dfdca661e9ddb45b0652128f9b017849d6e
Java
rachaTrabelsi/PregnancyTrackerAndroidApp
/app/src/main/java/com/esprit/pregnancytracker/main/DetailsInformationActivity.java
UTF-8
2,337
2.109375
2
[]
no_license
package com.esprit.pregnancytracker.main; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.esprit.pregnancytracker.R; import com.esprit.pregnancytracker.utils.PregnancyTrackerURLS; public class DetailsInformationActivity extends AppCompatActivity { String titreInfo,imgname,desc,categorie; TextView titre,description; Toolbar toolbar; ImageView imageview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details_information); titreInfo = getIntent().getStringExtra("titre"); imgname = getIntent().getStringExtra("image"); desc = getIntent().getStringExtra("desc"); description=(TextView)findViewById(R.id.descriptioninfo); toolbar = (Toolbar)findViewById(R.id.toolbar); titre = (TextView)findViewById(R.id.titreInfo); imageview = (ImageView)findViewById(R.id.imageDetails); titre.setText(titreInfo); categorie = getIntent().getStringExtra("categorie"); if (categorie.equals("sleep")) { Glide.with(this) .load(PregnancyTrackerURLS.URL_IMAGE_SLEEP_INFORMATIONS+imgname) .into(imageview); } if (categorie.equals("water")) { Glide.with(this) .load(PregnancyTrackerURLS.URL_IMAGE_WATERS_INFORMATIONS+imgname) .into(imageview); } if (categorie.equals("sport")){ Glide.with(this) .load(imgname) .into(imageview); } if (categorie.equals("alimentationtoeat")){ Glide.with(this) .load(PregnancyTrackerURLS.URL_IMAGES_IMAGES_TO_EAT +imgname) .into(imageview); } if (categorie.equals("alimentationnottoeat")){ Glide.with(this) .load(PregnancyTrackerURLS.URL_IMAGES_IMAGES_NOT_TO_EAT+imgname) .into(imageview); } description.setText(desc); toolbar.setTitle(titreInfo); } }
true
728f53c56035f7621df74ac7d814c32839b94df6
Java
lorrampi/better-hud
/src/main/java/jobicade/betterhud/util/ISlider.java
UTF-8
1,424
3.28125
3
[ "MIT" ]
permissive
package jobicade.betterhud.util; import net.minecraft.util.math.MathHelper; /** Interface representing a slider which maintains a minimum and maximum, * an interval between valid values and a current value */ public interface ISlider extends IGetSet<Double> { /** @return the minimum of the slider's range */ Double getMinimum(); /** @return The maximum of the slider's range */ Double getMaximum(); /** @return The string to display on the background of the slider * given its current value */ String getDisplayString(); /** @return The interval between values.<br> * Valid values are {@link #getMinimum()} {@code + k *} {@link #getInterval()} */ Double getInterval(); /** * Processes the value so that it satisfies the * following requirements: * <ul> * <li>{@code getMinimum() <= value <= getMaximum()} * <li>{@code value - getMinimum()} is a multiple of {@code getInterval()} * </ul> * * @param value The value to normalize. * @return The normalized value. */ default double normalize(double value) { double interval = getInterval(); double minimum = getMinimum(); if(interval != -1) { value -= minimum; value = Math.round(value / interval) * interval; value += minimum; } return MathHelper.clamp(value, minimum, getMaximum()); } }
true
b65fd7bb51ad425923ed9e727cc8a92e8009c49f
Java
Masoudas/Algorithms
/src/main/java/Chapter1/UnionFind_1_4/QuickUnion_3.java
UTF-8
2,006
3.828125
4
[]
no_license
package Chapter1.UnionFind_1_4; import java.util.stream.IntStream; /** * One thing that we did in the previous algorithm which was unnecessay, was that we gave all the * components the same name, and because of this, we had to iterate all over the ids. Hence, our search * is linear. * * Here's how we can change it. We know that an equivalence can always be associated to one element (for * example, in module 3, 0 is equivalent to 3, 6, ...). Now, let's assume that we have such element, which * we call a parent node. The goal is to find this parent node for two sites, and then make only one of them * the representative (thus making the other child of it) * * * The algorithm is called quick union, because making connections is very quick here. * * So, we refer to the id entry of each site as link. We refer to sites as nodes. * * In the find method, we follow each site to another site, until we reach a root, which is an element linked to itself. * * We can prove by induction that every node has a root. It's true for the first step. Then suppose we're at step (N-1), and * evey node has a root, it will then be true with the next union as well, as summarized above. Note that in this scheme, * all nodes connected nodes would have the same id as well. * * Question is: what is the cost of union? ? ? */ class QuickUnion implements UI{ int[] id; int component; QuickUnion(int N){ IntStream.range(0, N).foreach(i -> id[i] = i); component = N; } @Override public void union(int p, int q) { int id_p = find(p); int id_q = find(q); if (id_p == id_q) return; id[id_p] = id_q; component--; } @Override public boolean connected(int p, int q) { return find(p) == find(q); } @Override public int find(int p) { while(id[p] != p) p = id[p]; return p; } @Override public int count() { return component--; } }
true
ff4b8f4942e2b5a89989dcbc6904847f7b8d50e2
Java
jimgong3/SoCo
/client-android/app/src/main/java/com/soco/SoCoClient/events/service/JoinEventService.java
UTF-8
4,486
2.34375
2
[]
no_license
package com.soco.SoCoClient.events.service; import android.app.IntentService; import android.content.Intent; import android.util.Log; import com.soco.SoCoClient.common.HttpStatus; import com.soco.SoCoClient.common.http.HttpUtil; import com.soco.SoCoClient.common.http.JsonKeys; import com.soco.SoCoClient.common.http.UrlUtil; import com.soco.SoCoClient.common.util.SocoApp; import com.soco.SoCoClient.common.util.StringUtil; import com.soco.SoCoClient.events.details.JoinEventActivity; import com.soco.SoCoClient.events.model.Event; import org.json.JSONObject; @Deprecated public class JoinEventService extends IntentService { static final String tag = "JoinEventService"; static SocoApp socoApp; public JoinEventService() { super("JoinEventService"); } @Override public void onCreate() { super.onCreate(); //important socoApp = (SocoApp) getApplicationContext(); } @Override protected void onHandleIntent(Intent intent) { Log.d(tag, "join event service, handle intent:" + intent); Log.v(tag, "validate data"); if(socoApp.user_id.isEmpty() || socoApp.token.isEmpty()){ Log.e(tag, "user id or token or event is not available"); return; } // if(socoApp.newEvent == null){ // Log.e(tag, "new event is not available"); // return; // } String event_id = intent.getStringExtra(Event.EVENT_ID); String phone = intent.getStringExtra(JoinEventActivity.PHONE); String email = intent.getStringExtra(JoinEventActivity.EMAIL); String url = UrlUtil.getJoinEventUrl(); Object response = request( url, socoApp.user_id, socoApp.token, event_id, phone, email ); Log.v(tag, "set response flag as true"); socoApp.joinEventResponse = true; if (response != null) { Log.v(tag, "parse response"); parse(response); } else { Log.e(tag, "response is null, cannot parse"); } return; } public static Object request( String url, String user_id, String token, String event_id, String phone, String email ) { Log.v(tag, "join json request"); JSONObject data = new JSONObject(); try { data.put(JsonKeys.USER_ID, user_id); data.put(JsonKeys.TOKEN, token); data.put(JsonKeys.EVENT_ID, event_id); if(!StringUtil.isEmptyString(phone)) { data.put(JsonKeys.PHONE, phone); } if(!StringUtil.isEmptyString(email)) { data.put(JsonKeys.EMAIL, email); } Log.d(tag, "create event json: " + data); } catch (Exception e) { Log.e(tag, "cannot create json post data"); e.printStackTrace(); } return HttpUtil.executeHttpPost(url, data); } public static boolean parse(Object response) { Log.d(tag, "parse response: " + response.toString()); try { JSONObject json = new JSONObject(response.toString()); int status = json.getInt(JsonKeys.STATUS); if(status == HttpStatus.SUCCESS) { Log.d(tag, "join event success, retrieve event id"); // String event_id = json.getString(JsonKeys.EVENT_ID); // Log.d(tag, "create event success, " + // "event id: " + event_id // ); socoApp.joinEventResult = true; } else { String error_code = json.getString(JsonKeys.ERROR_CODE); String message = json.getString(JsonKeys.MESSAGE); String more_info = json.getString(JsonKeys.MORE_INFO); Log.d(tag, "join event fail, " + "error code: " + error_code + ", message: " + message + ", more info: " + more_info ); socoApp.error_message=message; socoApp.joinEventResult = false; } } catch (Exception e) { Log.e(tag, "cannot convert parse to json object: " + e.toString()); e.printStackTrace(); socoApp.joinEventResult = false; return false; } return true; } }
true
025e32a6677be895ef5a0ddf61acfb801bb154de
Java
NikitaKemarskiy/ds-labs
/lab2/src/com/deque/MyLinkedDeque.java
UTF-8
5,586
3.78125
4
[ "MIT" ]
permissive
package com.deque; // Мои классы import com.exception.*; // Классы Java import java.lang.Math; public class MyLinkedDeque implements MyDeque { // Private private int size = 0; private DequeItem back = null; private DequeItem front = null; // Public public MyLinkedDeque() { // Конструктор по умолчанию } public void push_back(int item) { // Вставка элемента в конец очереди if (back == null) { back = new DequeItem(item); front = back; } else { DequeItem newItem = new DequeItem(item, back, null); back.setNext(newItem); back = newItem; } size++; } public void push_front(int item) { // Вставка элемента в начало очереди if (front == null) { front = new DequeItem(item); back = front; } else { DequeItem newItem = new DequeItem(item, null, front); front.setPrev(newItem); front = newItem; } size++; } public int pop_back() throws EmptyDequeException { // Удаление элемента в конце очереди if (back == null) { throw new EmptyDequeException("Queue is already empty."); } DequeItem oldItem = back; back = back.getPrev(); if (back != null) { back.setNext(null); oldItem.setPrev(null); } else { front = null; } size--; return oldItem.getData(); } public int pop_front() throws EmptyDequeException { // Удаление элемента в начале очереди if (front == null) { throw new EmptyDequeException("Queue is already empty."); } DequeItem oldItem = front; front = front.getNext(); if (front != null) { front.setPrev(null); oldItem.setNext(null); } else { back = null; } size--; return oldItem.getData(); } public int back() throws EmptyDequeException { // Возврат конца очереди без удаления if (back == null) { throw new EmptyDequeException("Queue is already empty."); } return back.getData(); } public int front() throws EmptyDequeException { // Возврат начала очереди без удаления if (front == null) { throw new EmptyDequeException("Queue is already empty."); } return front.getData(); } public int size() { // Возврат размера очереди return size; } public void clear() { // Очистка очереди DequeItem current = front; front = null; back = null; size = 0; while (current != null) { DequeItem buffer = current; current = current.getNext(); buffer.setNext(null); if (current != null) { current.setPrev(null); } } } public boolean isEmpty() { // Проверка пуста ли очередь return size > 0 ? false : true; } public int valueOf(int index) throws InvalidIndexException { if (index >= size || index < 0) { throw new InvalidIndexException("Invalid index was passed."); } MyLinkedDeque buffer = new MyLinkedDeque(); for (int i = 0; i < index; i++) { try { buffer.push_back(this.pop_front()); } catch (EmptyDequeException err) { throw new InvalidIndexException("Invalid index was passed"); } } int val = this.front.getData(); while (!buffer.isEmpty()) { try { this.push_front(buffer.pop_back()); } catch (EmptyDequeException err) { throw new InvalidIndexException("Invalid index was passed"); } } return val; } public void randomFill(int n) { for (int i = 0; i < n; i++) { this.push_back((int)(Math.random() * 10)); } } public String toString() { // Привести очередь к строке String str = "["; // Открываем массив в строке DequeItem current = front; while (current != back) { str += current.getData() + ", "; // Добавляем помимо элемента запятую с пробелом в конце current = current.getNext(); } if (current != null) { str += current.getData(); } str += "]"; // Закрываем массив в строке return str; } } class DequeItem { // Private int data = 0; DequeItem next = null; DequeItem prev = null; // Public DequeItem() { data = 0; } DequeItem(int data) { this.data = data; } DequeItem(int data, DequeItem prev, DequeItem next) { this.data = data; this.prev = prev; this.next = next; } public void setNext(DequeItem next) { this.next = next; } public void setPrev(DequeItem prev) { this.prev = prev; } public DequeItem getNext() { return next; } public DequeItem getPrev() { return prev; } public int getData() { return data; } }
true
e33f25303a94e0f5c9279edea2991f7da25198d2
Java
mrtamb9/BKSportAnnotation
/src - Copy/main/java/org/bksport/annotation/mvc/view/StatisticMediator.java
UTF-8
1,175
2.390625
2
[]
no_license
package org.bksport.annotation.mvc.view; import java.awt.Frame; import java.util.HashMap; import org.bksport.annotation.mvc.AppFacade; import org.bksport.annotation.mvc.view.ui.StatisticDialog; import org.puremvc.java.interfaces.INotification; import org.puremvc.java.patterns.mediator.Mediator; /** * * Mediator of {@link StatisticDialog}, show information of every annotations * * @author congnh * */ public class StatisticMediator extends Mediator { public StatisticMediator() { super(StatisticMediator.class.getName(), null); } @Override public String[] listNotificationInterests() { return new String[] { AppFacade.STATISTIC_LOADED }; } @SuppressWarnings("unchecked") public void handleNotification(INotification notification) { String name = notification.getName(); if (name.equals(AppFacade.STATISTIC_LOADED)) { StatisticDialog dialog = new StatisticDialog((Frame) facade .retrieveMediator(AppFacade.CONTAINER_MED).getViewComponent(), true); dialog .setStatistic((HashMap<String, HashMap<String, Integer>>) notification .getBody()); dialog.setVisible(true); } } }
true
220f2b7191dd3721dc22503e3206a7d4936e5862
Java
mbohnearschi-endava/jiraminer
/src/main/java/org/dxworks/dxplatform/jiraminer/Main.java
UTF-8
2,846
2.3125
2
[ "Apache-2.0" ]
permissive
package org.dxworks.dxplatform.jiraminer; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.dxworks.dxplatform.jiraminer.configuration.JiraMinerConfiguration; import org.dxworks.dxplatform.jiraminer.rest.client.JiraMinerUnauthorizedException; import org.dxworks.dxplatform.jiraminer.rest.client.JiraRestClient; import org.dxworks.dxplatform.jiraminer.rest.client.JiraRestClientFactory; import org.dxworks.dxplatform.jiraminer.rest.response.JiraIssueDTO; import java.io.File; import java.io.IOException; import java.util.List; @Slf4j public class Main { public static void main(String[] args) throws Exception { // oldMain(args); log.info("Starting Jira Miner..."); JiraMinerConfiguration jiraMinerConfiguration = new JiraMinerConfiguration(); JiraRestClientFactory jiraRestClientFactory = new JiraRestClientFactory(jiraMinerConfiguration); JiraRestClient jiraRestClient = jiraRestClientFactory.createByAuthenticationType(); JiraMiner jiraMiner = new JiraMiner(jiraRestClient, jiraMinerConfiguration); List<JiraIssueDTO> issues = null; try { issues = jiraMiner.getIssues(); } catch (JiraMinerUnauthorizedException e) { log.error("Error: Unauthorized. Please revise your authentication method and try again. \n" + "If you are using cookie based authentication, please renew the cookie!"); System.exit(1); } log.info("Writing results to file..."); ensureResultsFolderExists(); writeIssuesToFile(jiraMinerConfiguration.getProjectID(), issues); log.info("Finished Jira Miner."); } private static void ensureResultsFolderExists() { File directory = new File("results"); if (!directory.exists()) { directory.mkdirs(); } } private static void writeIssuesToFile(String projectID, List<JiraIssueDTO> issues) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); try { objectMapper.writeValue(new File("results/" + projectID + "-issues.json"), issues); } catch (IOException e) { log.error("Could not write result file!", e); throw e; } } // private static void oldMain(String[] args) throws Exception { // if (args.length == 0) { // throw new IllegalArgumentException("No command specified. Use one of " + Command.names()); // } // // PropertiesClient propertiesClient = new PropertiesClient(); // JiraOAuthClient jiraOAuthClient = new JiraOAuthClient(propertiesClient); // // List<String> argumentsWithoutFirst = Arrays.asList(args).subList(1, args.length); // // new OAuthClient(propertiesClient, jiraOAuthClient).execute(Command.fromString(args[0]), argumentsWithoutFirst); // } }
true
d0d72729386a88ca88dfe64bdc4648ff49c8b942
Java
jackycaojiaqi/yaoyaoLive
/app/src/main/java/com/fubang/video/ui/RegisterActivity.java
UTF-8
14,263
1.578125
2
[]
no_license
package com.fubang.video.ui; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import com.bumptech.glide.Glide; import com.fubang.video.AppConstant; import com.fubang.video.R; import com.fubang.video.base.BaseActivity; import com.fubang.video.callback.JsonCallBack; import com.fubang.video.entity.LoginEntity; import com.fubang.video.entity.SendMsgEntity; import com.fubang.video.entity.UploadPhotoEntity; import com.fubang.video.util.FileUtils; import com.fubang.video.util.ImagUtil; import com.fubang.video.util.StringUtil; import com.fubang.video.util.SystemStatusManager; import com.fubang.video.util.ToastUtil; import com.fubang.video.widget.ClearableEditText; import com.jph.takephoto.app.TakePhotoActivity; import com.jph.takephoto.model.CropOptions; import com.jph.takephoto.model.TImage; import com.jph.takephoto.model.TResult; import com.lzy.okgo.OkGo; import com.lzy.okgo.model.Response; import com.socks.library.KLog; import com.vmloft.develop.library.tools.utils.VMLog; import com.vmloft.develop.library.tools.utils.VMSPUtil; import java.io.File; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import de.hdodenhof.circleimageview.CircleImageView; import okhttp3.Call; /** * Created by jacky on 2017/7/18. */ public class RegisterActivity extends TakePhotoActivity { @BindView(R.id.iv_back) ImageView ivBack; @BindView(R.id.tv_title) TextView tvTitle; @BindView(R.id.iv_register_pic) CircleImageView ivRegisterPic; @BindView(R.id.et_register_nickname) ClearableEditText etRegisterNickname; @BindView(R.id.cb_register_pick_male) ImageView cbRegisterPickMale; @BindView(R.id.iv_register_pick_male) ImageView ivRegisterPickMale; @BindView(R.id.ll_register_pick_male) LinearLayout llRegisterPickMale; @BindView(R.id.cb_register_pick_female) ImageView cbRegisterPickFemale; @BindView(R.id.iv_register_pick_female) ImageView ivRegisterPickFemale; @BindView(R.id.ll_register_pick_female) LinearLayout llRegisterPickFemale; @BindView(R.id.et_register_password) ClearableEditText etRegisterPassword; @BindView(R.id.btn_register_submit) Button btnRegisterSubmit; private String phone, calias, password, cphoto, photo_name; private int gender = 1; private Context context; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTranslucentStatus(); setContentView(R.layout.activity_register_info); ButterKnife.bind(this); context = this; initview(); } private void initview() { tvTitle.setText(R.string.register_phone); phone = getIntent().getStringExtra(AppConstant.USERID); } @OnClick({R.id.iv_register_pic, R.id.iv_back, R.id.ll_register_pick_male, R.id.ll_register_pick_female, R.id.btn_register_submit}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.iv_back: finish(); break; case R.id.iv_register_pic: ShowPopAction(); break; case R.id.ll_register_pick_male: gender = 1; cbRegisterPickMale.setImageResource(R.drawable.ic_checkbox_checked); ivRegisterPickMale.setImageResource(R.drawable.ic_register_male_checked); cbRegisterPickFemale.setImageResource(R.drawable.ic_checkbox_uncheked); ivRegisterPickFemale.setImageResource(R.drawable.ic_register_female_unchecked); break; case R.id.ll_register_pick_female: gender = 0; cbRegisterPickMale.setImageResource(R.drawable.ic_checkbox_uncheked); ivRegisterPickMale.setImageResource(R.drawable.ic_register_male); cbRegisterPickFemale.setImageResource(R.drawable.ic_checkbox_checked); ivRegisterPickFemale.setImageResource(R.drawable.ic_register_female_checked); break; case R.id.btn_register_submit: calias = etRegisterNickname.getText().toString().trim(); password = etRegisterPassword.getText().toString().trim(); if (StringUtil.isEmptyandnull(calias)) { ToastUtil.show(context, R.string.nick_name_not_null); return; } if (StringUtil.isEmptyandnull(password)) { ToastUtil.show(context,R.string.pwd_not_null); return; } KLog.e(photo_name); OkGo.<LoginEntity>post(AppConstant.BASE_URL + AppConstant.URL_REGISTER) .tag(this) .params("ctel", phone) .params("calias", calias) .params("password", password) .params("ngender", gender) .params("cphoto", photo_name) .execute(new JsonCallBack<LoginEntity>(LoginEntity.class) { @Override public void onSuccess(Response<LoginEntity> response) { if (response.body().getStatus().equals("success")) { //本地存数据 VMSPUtil.put(context, AppConstant.TOKEN, response.body().getInfo().getCtoken()); VMSPUtil.put(context, AppConstant.USERID, response.body().getInfo().getNuserid()); VMSPUtil.put(context, AppConstant.GENDER, String.valueOf(gender)); VMSPUtil.put(context, AppConstant.USERNAME, calias); VMSPUtil.put(context, AppConstant.USERPIC, AppConstant.BASE_IMG_URL + photo_name); VMSPUtil.put(context, AppConstant.PASSWORD, password); VMSPUtil.put(context, AppConstant.PHONE, phone); //去登录 OkGo.<LoginEntity>post(AppConstant.BASE_URL + AppConstant.URL_LOGIN) .tag(this) .params("ctel", phone) .params("password", password) .execute(new JsonCallBack<LoginEntity>(LoginEntity.class) { @Override public void onSuccess(Response<LoginEntity> response) { if (response.body().getStatus().equals("success")) { VMSPUtil.put(context, AppConstant.USERID, response.body().getInfo().getNuserid()); VMSPUtil.put(context, AppConstant.TOKEN, response.body().getInfo().getCtoken()); //环信登录 Intent intent = new Intent(context, MainActivity.class); startActivity(intent); finish(); // loginHX(); } else { ToastUtil.show(context, getString(R.string.wrong_pwd)); } } @Override public void onError(Response<LoginEntity> response) { super.onError(response); } }); } else { ToastUtil.show(context,getString(R.string.register_fail)); } } @Override public void onError(Response<LoginEntity> response) { super.onError(response); } }); break; } } /** * 处理拍照弹窗 */ private PopupWindow pop_pic; private Uri imageUri; private void ShowPopAction() { final View popupView = getLayoutInflater().inflate(R.layout.pop_user_pic, null); pop_pic = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true); pop_pic.showAtLocation(tvTitle, Gravity.CENTER_HORIZONTAL, 0, 0); pop_pic.setOutsideTouchable(false); ImageView iv_cancle = (ImageView) popupView.findViewById(R.id.tv_user_info_pic_cancle); TextView tv_album = (TextView) popupView.findViewById(R.id.tv_user_info_pic_form_album); TextView tv_camera = (TextView) popupView.findViewById(R.id.tv_user_info_pic_form_camera); iv_cancle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pop_pic.dismiss(); } }); tv_album.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { File file = new File(FileUtils.getTempFiles() + System.currentTimeMillis() + "tempalbum.jpg"); if (file.exists()) { file.delete(); } if (!file.getParentFile().exists()) file.getParentFile().mkdirs(); imageUri = Uri.fromFile(file); getTakePhoto().onPickFromGalleryWithCrop(imageUri, getCropOptions()); pop_pic.dismiss(); } }); tv_camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { File file = new File(FileUtils.getTempFiles() + System.currentTimeMillis() + "tempcamera.jpg"); if (file.exists()) { file.delete(); } if (!file.getParentFile().exists()) file.getParentFile().mkdirs(); imageUri = Uri.fromFile(file); getTakePhoto().onPickFromCaptureWithCrop(imageUri, getCropOptions()); pop_pic.dismiss(); } }); } @Override public void takeCancel() { KLog.e("takeCancel"); super.takeCancel(); } @Override public void takeFail(TResult result, String msg) { KLog.e("takeFail"); super.takeFail(result, msg); } @Override public void takeSuccess(TResult result) { KLog.e("takeSuccess"); super.takeSuccess(result); showImg(result.getImages()); } private void showImg(ArrayList<TImage> images) { KLog.e(images.size()); if (images.size() > 0) { KLog.e(images.get(0).getOriginalPath()); // Glide.with(context).load(new File(images.get(0).getOriginalPath())).fitCenter().into(ivRegisterPic); cphoto = images.get(0).getOriginalPath(); //上传图片 OkGo.<UploadPhotoEntity>post(AppConstant.BASE_URL + AppConstant.URL_UPLOAD_PHOTO) .tag(this) .params("ctoken", String.valueOf(VMSPUtil.get(context, AppConstant.TOKEN, ""))) .params("sub_name", "touxiang") .params("file", new File(cphoto)) .execute(new JsonCallBack<UploadPhotoEntity>(UploadPhotoEntity.class) { @Override public void onSuccess(Response<UploadPhotoEntity> response) { if (response.body().getStatus().equals("success")) { photo_name = response.body().getInfo().getFilename(); ImagUtil.setnoerror(context, AppConstant.BASE_IMG_URL + photo_name, ivRegisterPic); } else { ToastUtil.show(context, getString(R.string.upload_pick_fail)); } } @Override public void onError(Response<UploadPhotoEntity> response) { super.onError(response); } }); } } private CropOptions getCropOptions() { int height = Integer.parseInt("500"); int width = Integer.parseInt("600"); CropOptions.Builder builder = new CropOptions.Builder(); builder.setAspectX(width).setAspectY(height); builder.setOutputX(width).setOutputY(height); return builder.create(); } /** * 设置状态栏背景状态 */ public void setTranslucentStatus() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; winParams.flags |= bits; win.setAttributes(winParams); } SystemStatusManager tintManager = new SystemStatusManager(this); tintManager.setStatusBarTintEnabled(true); tintManager.setStatusBarTintResource(0);//状态栏无背景 } }
true
a95c32dea5a4121e4f19a74387fd19dcb60886f3
Java
andrewrstubbs/Recursive-Descent-Parser
/Slump.java
UTF-8
1,890
3.3125
3
[]
no_license
import java.util.ArrayList; /** * @author Andrew Stubbs * @version 3/22/15 * The definition of the Slump rule of the ENBF */ public class Slump { protected int nextToken; protected char lexeme; protected ArrayList<Character> chars; protected Slurpy slurpy; protected final Character D = 'D'; protected final Character E = 'E'; protected final Character F = 'F'; protected final Character G = 'G'; public Slump(int curToken, Character lxm, ArrayList<Character> charList, Slurpy x){ System.out.println("Enter <slump>"); nextToken = curToken; lexeme = lxm; chars = charList; slurpy = x; try { //Evaluates the Slump rule of the ENBF, calling the Slump class when appropriate if(lexeme == D || lexeme == E ){ System.out.println("Next token is: " + nextToken +" Next lexeme is: " + lexeme ); nextToken++; lexeme = chars.get(nextToken); while(lexeme == 'F'){ System.out.println("Next token is: " + nextToken +" Next lexeme is: " + lexeme ); nextToken++; lexeme = chars.get(nextToken); } if(lexeme == G){ System.out.println("Next token is: " + nextToken +" Next lexeme is: " + lexeme ); if(chars.size() > nextToken+1){ nextToken++; lexeme = chars.get(nextToken); } } else{ Slump slump3 = new Slump(nextToken, lexeme, chars, slurpy); lexeme = slump3.getLexeme(); nextToken = slump3.getNextToken(); } } else{ slurpy.setStatus(false); } } catch (Exception e) { slurpy.setStatus(false); } System.out.println("Exit <slump>"); } /** * * @return the next lexeme to be evaluated */ public Character getLexeme(){ return lexeme; } /** * * @return the token of the next lexeme to be evaluated */ public int getNextToken(){ return nextToken; } }
true
8773e9663c94fc0927872f4a36c857f29a07a637
Java
Quantum64/OpenModDetector
/src/main/java/co/q64/omd/spigot/SpigotOpenModDetectorPlugin.java
UTF-8
709
1.9375
2
[]
no_license
package co.q64.omd.spigot; import org.bukkit.plugin.java.JavaPlugin; import co.q64.omd.OpenModDetector; import co.q64.omd.OpenModDetectorPlugin; import co.q64.omd.base.inject.ModDetectorModule; import co.q64.omd.spigot.inject.*; public class SpigotOpenModDetectorPlugin extends JavaPlugin implements OpenModDetectorPlugin { private OpenModDetector modDetector; @Override public void onEnable() { //formatter:off this.modDetector = DaggerSpigotComponent.builder() .modDetectorModule(new ModDetectorModule()) .spigotModule(new SpigotModule(this)) .build().getOpenModDetector(); //formatter:on modDetector.enable(); } @Override public void onDisable() { modDetector.disable(); } }
true
c2b6f2ec1b5037048eef6b6b3eac7583b140994a
Java
multi-os-engine/moe-core
/moe.apple/moe.platform.ios/src/main/java/apple/foundation/NSOutputStream.java
UTF-8
7,821
1.578125
2
[ "Apache-2.0", "ICU", "W3C" ]
permissive
/* Copyright 2014-2016 Intel Corporation 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 apple.foundation; import apple.NSObject; import org.moe.natj.c.ann.FunctionPtr; import org.moe.natj.general.NatJ; import org.moe.natj.general.Pointer; import org.moe.natj.general.ann.Generated; import org.moe.natj.general.ann.Library; import org.moe.natj.general.ann.Mapped; import org.moe.natj.general.ann.NInt; import org.moe.natj.general.ann.NUInt; import org.moe.natj.general.ann.Owned; import org.moe.natj.general.ann.ReferenceInfo; import org.moe.natj.general.ann.Runtime; import org.moe.natj.general.ptr.BytePtr; import org.moe.natj.general.ptr.ConstBytePtr; import org.moe.natj.general.ptr.Ptr; import org.moe.natj.general.ptr.VoidPtr; import org.moe.natj.objc.Class; import org.moe.natj.objc.ObjCRuntime; import org.moe.natj.objc.SEL; import org.moe.natj.objc.ann.ObjCClassBinding; import org.moe.natj.objc.ann.Selector; import org.moe.natj.objc.map.ObjCObjectMapper; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * NSOutputStream is an abstract class representing the base functionality of a write stream. * Subclassers are required to implement these methods. */ @Generated @Library("Foundation") @Runtime(ObjCRuntime.class) @ObjCClassBinding public class NSOutputStream extends NSStream { static { NatJ.register(); } @Generated protected NSOutputStream(Pointer peer) { super(peer); } @Generated @Selector("accessInstanceVariablesDirectly") public static native boolean accessInstanceVariablesDirectly(); @Generated @Owned @Selector("alloc") public static native NSOutputStream alloc(); @Owned @Generated @Selector("allocWithZone:") public static native NSOutputStream allocWithZone(VoidPtr zone); @Generated @Selector("automaticallyNotifiesObserversForKey:") public static native boolean automaticallyNotifiesObserversForKey(@NotNull String key); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:") public static native void cancelPreviousPerformRequestsWithTarget( @NotNull @Mapped(ObjCObjectMapper.class) Object aTarget); @Generated @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:") public static native void cancelPreviousPerformRequestsWithTargetSelectorObject( @NotNull @Mapped(ObjCObjectMapper.class) Object aTarget, @NotNull SEL aSelector, @Nullable @Mapped(ObjCObjectMapper.class) Object anArgument); @NotNull @Generated @Selector("classFallbacksForKeyedArchiver") public static native NSArray<String> classFallbacksForKeyedArchiver(); @NotNull @Generated @Selector("classForKeyedUnarchiver") public static native Class classForKeyedUnarchiver(); @Generated @Selector("debugDescription") public static native String debugDescription_static(); @Generated @Selector("description") public static native String description_static(); @Generated @Selector("getBoundStreamsWithBufferSize:inputStream:outputStream:") public static native void getBoundStreamsWithBufferSizeInputStreamOutputStream(@NUInt long bufferSize, @Nullable @ReferenceInfo(type = NSInputStream.class) Ptr<NSInputStream> inputStream, @Nullable @ReferenceInfo(type = NSOutputStream.class) Ptr<NSOutputStream> outputStream); @Deprecated @Generated @Selector("getStreamsToHostWithName:port:inputStream:outputStream:") public static native void getStreamsToHostWithNamePortInputStreamOutputStream(@NotNull String hostname, @NInt long port, @Nullable @ReferenceInfo(type = NSInputStream.class) Ptr<NSInputStream> inputStream, @Nullable @ReferenceInfo(type = NSOutputStream.class) Ptr<NSOutputStream> outputStream); @Generated @Selector("hash") @NUInt public static native long hash_static(); @Generated @Selector("instanceMethodForSelector:") @FunctionPtr(name = "call_instanceMethodForSelector_ret") public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector); @Generated @Selector("instanceMethodSignatureForSelector:") public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector); @Generated @Selector("instancesRespondToSelector:") public static native boolean instancesRespondToSelector(SEL aSelector); @Generated @Selector("isSubclassOfClass:") public static native boolean isSubclassOfClass(Class aClass); @NotNull @Generated @Selector("keyPathsForValuesAffectingValueForKey:") public static native NSSet<String> keyPathsForValuesAffectingValueForKey(@NotNull String key); @Generated @Owned @Selector("new") public static native NSOutputStream new_objc(); @Generated @Selector("outputStreamToBuffer:capacity:") public static native NSOutputStream outputStreamToBufferCapacity(@NotNull BytePtr buffer, @NUInt long capacity); @Generated @Selector("outputStreamToFileAtPath:append:") public static native NSOutputStream outputStreamToFileAtPathAppend(@NotNull String path, boolean shouldAppend); @Generated @Selector("outputStreamToMemory") public static native NSOutputStream outputStreamToMemory(); /** * API-Since: 4.0 */ @Generated @Selector("outputStreamWithURL:append:") public static native NSOutputStream outputStreamWithURLAppend(@NotNull NSURL url, boolean shouldAppend); @Generated @Selector("resolveClassMethod:") public static native boolean resolveClassMethod(SEL sel); @Generated @Selector("resolveInstanceMethod:") public static native boolean resolveInstanceMethod(SEL sel); @Generated @Selector("setVersion:") public static native void setVersion_static(@NInt long aVersion); @Generated @Selector("superclass") public static native Class superclass_static(); @Generated @Selector("version") @NInt public static native long version_static(); /** * writes the bytes from the specified buffer to the stream up to len bytes. Returns the number of bytes actually * written. */ @Generated @Selector("hasSpaceAvailable") public native boolean hasSpaceAvailable(); @Generated @Selector("init") public native NSOutputStream init(); @Generated @Selector("initToBuffer:capacity:") public native NSOutputStream initToBufferCapacity(@NotNull BytePtr buffer, @NUInt long capacity); @Generated @Selector("initToFileAtPath:append:") public native NSOutputStream initToFileAtPathAppend(@NotNull String path, boolean shouldAppend); /** * returns YES if the stream can be written to or if it is impossible to tell without actually doing the write. */ @Generated @Selector("initToMemory") public native NSOutputStream initToMemory(); /** * API-Since: 4.0 */ @Generated @Selector("initWithURL:append:") public native NSOutputStream initWithURLAppend(@NotNull NSURL url, boolean shouldAppend); @Generated @Selector("write:maxLength:") @NInt public native long writeMaxLength(@NotNull ConstBytePtr buffer, @NUInt long len); }
true
9e780118f6c3a10fbe028dbbd2c18343ab3ace7b
Java
arpit2425/getwel
/app/src/main/java/com/example/arpit/getwel/customer.java
UTF-8
1,011
2.21875
2
[]
no_license
package com.example.arpit.getwel; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import java.util.ArrayList; public class customer { String name; String email; String phone; String address; String product; String amount; String quantity; public customer() { } public customer(String name, String phone, String address,String product,String quantity,String amount) { this.name = name; this.phone = phone; this.address = address; this.product=product; this.quantity=quantity; this.amount=amount; } public String getName() { return name; } public String getPhone() { return phone; } public String getAddress() { return address; } public String getProduct() { return product; } public String getQuantity() { return quantity; } public String getAmount() { return amount; } }
true
d2416c4622d820c7d0e9fb8fa6e156d9fa3ebb00
Java
kimnamsun/stocker
/src/board/controller/BoardCommentInsertServlet.java
UTF-8
1,628
2.34375
2
[]
no_license
package board.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import board.model.service.BoardService; import board.model.vo.BoardComment; @WebServlet("/board/boardCommentInsert") public class BoardCommentInsertServlet extends HttpServlet { private static final long serialVersionUID = 1L; public BoardCommentInsertServlet() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int boardRef = Integer.parseInt(request.getParameter("boardRef")); int boardCommentLevel = Integer.parseInt(request.getParameter("boardCommentLevel")); int boardCommentRef = Integer.parseInt(request.getParameter("boardCommentRef")); String boardCommentWriter = request.getParameter("boardCommentWriter"); String boardCommentContent = request.getParameter("boardCommentContent"); BoardComment bc = new BoardComment(0, boardCommentLevel, boardCommentWriter, boardCommentContent, boardRef, boardCommentRef, null); int result = new BoardService().insertBoardComment(bc); String msg = result > 0 ? "댓글이 등록되었습니다." : "댓글 등록 실패!"; String loc = "/board/boardView?boardNo=" + boardRef; request.setAttribute("msg", msg); request.setAttribute("loc", loc); request.getRequestDispatcher("/WEB-INF/views/common/msg.jsp").forward(request, response); } }
true
01942c71871fd8a09e54550edad79a1770c100da
Java
jvitorc/Ticket-To-Ride
/src/network/ActorNetGames.java
ISO-8859-1
2,726
2.453125
2
[]
no_license
package network; import br.ufsc.inf.leobr.cliente.Jogada; import br.ufsc.inf.leobr.cliente.OuvidorProxy; import br.ufsc.inf.leobr.cliente.Proxy; import br.ufsc.inf.leobr.cliente.exception.ArquivoMultiplayerException; import br.ufsc.inf.leobr.cliente.exception.JahConectadoException; import br.ufsc.inf.leobr.cliente.exception.NaoConectadoException; import br.ufsc.inf.leobr.cliente.exception.NaoJogandoException; import br.ufsc.inf.leobr.cliente.exception.NaoPossivelConectarException; import control.Controller; public class ActorNetGames implements OuvidorProxy { private Controller controller; private Proxy proxy; public ActorNetGames(Controller controller) { this.controller = controller; proxy = Proxy.getInstance(); proxy.addOuvinte(this); } // CASO DE USO CONECTAR public boolean connect(String server, String name) { try { proxy.conectar(server, name); return true; } catch (JahConectadoException | NaoPossivelConectarException | ArquivoMultiplayerException e) { e.printStackTrace(); return false; } } // INICIA CASO DE USO RECEBER SOLICITO DE INICIO @Override public void iniciarNovaPartida(Integer posicao) { // TODO Auto-generated method stub controller.startNewGame(posicao); } // DESCONECTAR POR ERRO @Override public void finalizarPartidaComErro(String message) { // TODO Auto-generated method stub controller.disconnectNETWORK(); } @Override public void receberMensagem(String msg) { // TODO Auto-generated method stub } // INICIA CASO DE USO RECEBER JOGADA @Override public void receberJogada(Jogada jogada) { // TODO Auto-generated method stub Action action = (Action) jogada; controller.setPlayed(action); } // DESCONECTAR POR ERRO @Override public void tratarConexaoPerdida() { // TODO Auto-generated method stub controller.disconnectNETWORK(); } // NO PRECISA @Override public void tratarPartidaNaoIniciada(String message) { } // CASO DE USO INICIAR PARTIDA public boolean startGame(int quantity) { try { proxy.iniciarPartida(quantity); return true; } catch (NaoConectadoException e) { return false; } } // CASO DE USO FINALIZAR TURNO public boolean sendAction(Jogada action) { try { proxy.enviaJogada(action); return true; } catch (NaoJogandoException e) { return false; } } // CASO DE USO DESCONECTAR public void disconnect() { try { proxy.desconectar(); } catch (NaoConectadoException e) { e.printStackTrace(); } } public String getOtherPlayerName(int position) { return proxy.obterNomeAdversario(position); } }
true
baa5c34964fc3b34e521f62cc0815d596bf608cc
Java
fabiomorais/poo-2018.1
/src/patterns/abstract_factory/FabricaSRT.java
UTF-8
494
2.515625
3
[]
no_license
package patterns.abstract_factory; public class FabricaSRT extends Fabrica { @Override public Sanduiche montarSanduche() { Sanduiche sanduiche = super.montarSanduche(); Salada s = criarSalada(); sanduiche.addSalada(s); return sanduiche; } public Salada criarSalada() { return new Salada(); } public Pao criarPao() { return new Integral(); } public Queijo criarQueijo() { return new Cheddar(); } public Presunto criarPresunto() { return new DePeru(); } }
true
15e80ced25059e3987009b45ae6f8b5ff53c06b6
Java
384401056/JavaDesignPattern
/11-模板方法模式Template Method/src/com/templatemethod/MainTest.java
UTF-8
190
2.03125
2
[]
no_license
package com.templatemethod; public class MainTest { /** * @param args */ public static void main(String[] args) { Template template = new MyClass2(); template.method(); } }
true
96d506404a35bcf5fe97505bf75b3ade63880487
Java
hasee284/Java
/src/member/MemberDao.java
UTF-8
717
2.140625
2
[]
no_license
package member; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; public class MemberDao { private static MemberDao instance; public static MemberDao getInstance() { if (instance == null) { instance = new MemberDao(); } return instance; } private MemberDao() {} private JdbcTemplate template = DBApplication.getTemplate(); public MemberVO login(MemberVO vo) { return template.queryForObject("SELECT * FROM MEMBER WHERE ID=? AND PW=?" , new BeanPropertyRowMapper<>(MemberVO.class) ,vo.getId() ,vo.getPwd()); } public int inputNoticeMenu(MemberVO vo) { return vo.getInputNoticeMenu(); } }
true
4f132c215d9116f19362149a4cc0253c5741e74b
Java
gouthampradhan/html-analyzer
/src/main/java/htmlanalyzer/parser/data/Metadata.java
UTF-8
1,357
2.640625
3
[]
no_license
package htmlanalyzer.parser.data; import java.util.Map; /** * Created by gouthamvidyapradhan on 07/10/2017. * Data response object to populate HTML Metadata information */ public class Metadata{ //Html version private String htmlVersion; //HTML title private String title; //Map of header type and count private Map<String, Long> header; //Flag indicating if the page has a login form or not private boolean login; //Map of LinkType and total count of each links private Map<LinkType, Integer> linkCount; public String getHtmlVersion() { return htmlVersion; } public void setHtmlVersion(String htmlVersion) { this.htmlVersion = htmlVersion; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Map<String, Long> getHeader() { return header; } public void setHeader(Map<String, Long> header) { this.header = header; } public boolean isLogin() { return login; } public void setLogin(boolean login) { this.login = login; } public Map<LinkType, Integer> getLinkCount() { return linkCount; } public void setLinkCount(Map<LinkType, Integer> linkCount) { this.linkCount = linkCount; } }
true
50c3649e3423553ebcb67bbf62045806ba4acdfc
Java
semaj7/ledder
/src/Picture.java
UTF-8
884
3.109375
3
[]
no_license
import java.awt.*; import java.util.ArrayList; /** * Created by james on 07/02/16. * A combination of compositions which should be active simultaneously. */ public class Picture extends ArrayList<Composition>{ Picture(Color color){ makeAll(color); } Picture(Composition comp){ makeAll(comp); } Picture(){ } Picture(int r, int g, int b){ makeAll(r, g, b); } void makeAll(Composition comp){ //TODO.. does weird stuff: first time sending: only to 14 for(int i = 0; i < Config.NUMBER_OF_BARS; i++){ add(new Composition(comp)); get(i).setAddressByte(i); //address might not be i for every config } } void makeAll(Color color){ makeAll(new Composition(color)); } void makeAll(int r, int g, int b){ makeAll(new Composition(r, g, b)); } }
true
e460b5251ff184cf03e584f4b4ce86311978732b
Java
wearablebiosensing/tex-tronics
/androidedge/SmartGloveArchives/Demo_Versions/WithGraphing_Flex_Only/SmartGloveFragments/app/src/main/java/andrewpeltier/smartglovefragments/fragments/patientfrags/FinishFragment.java
UTF-8
9,811
2.390625
2
[ "Apache-2.0" ]
permissive
package andrewpeltier.smartglovefragments.fragments.patientfrags; import android.animation.ObjectAnimator; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.CountDownTimer; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.constraint.ConstraintLayout; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.utils.ColorTemplate; import andrewpeltier.smartglovefragments.R; import andrewpeltier.smartglovefragments.main_activity.MainActivity; import andrewpeltier.smartglovefragments.tex_tronics.TexTronicsManagerService; import andrewpeltier.smartglovefragments.visualize.GenerateGraph; /** ====================================== * * FinishFragment Class * * ====================================== * * This fragment needs substantial changes as we are able to gather more information * from our server. At this point, we demo dummy data and restart the application. * * * * @author Andrew Peltier * @version 1.0 */ public class FinishFragment extends Fragment { private static final String TAG = "FinishFragment"; /** * The time it takes to transition from one set of graphs to another. At this * point, it takes one second to have a set of graphs move off of the screen and * one second to move back on */ private static final long TRAN_TICK = 1000; private static final long TRAN_FINISH = 1000; /** * The duration of a set of graphs on the screen. At this point, a set of graphs should * remain on the screen for 6 seconds. */ private static final long START_TICK = 6000; /** * This will probably have to change. The graphs will rotate between each set for 5 minutes, * at which point the application will reset. This should be plenty of time to demo */ private static final long START_FINISH = 300000; private Button returnButton; // Button that returns to home fragment private ConstraintLayout chartLayout; // Layout that contains our pie graphs private PieChart chart, chart2, chart3; // Each of the pie graphs that shows dummy data private CountDownTimer transitionTimer, startTimer; // Timer that manages the pie graphs private boolean demo = false; // Determines what set of graphs we are displaying private boolean firstTick = true; // Stops the timer from running code twice /** onCreateView() * * Called when the view is first created. We use the fragment_exercise_selection XML file to load the view and its * properties into the fragment, which is then given to the Main Activity. For the finish fragment, we just have to * set up the charts and start the timers that are used to animate them. * * @param inflater -Used to "inflate" or load the layout inside the main activity * @param container -Object containing the fragment layout (from MainActivity XML) * @param savedInstanceState -State of the application * @return The intractable exercise selection fragment view. */ @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_finish, container, false); returnButton = view.findViewById(R.id.return_button); // Sets the return button to restart the application and return to the home screen on click returnButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { restart(); } }); // Find charts chart = view.findViewById(R.id.chart); chart2 = view.findViewById(R.id.chart2); chart3 = view.findViewById(R.id.chart3); // Set up charts with original data chart = setUpChart(chart, ColorTemplate.getHoloBlue(), 50, 100, "Graph 1"); chart2 = setUpChart(chart2, ColorTemplate.JOYFUL_COLORS[0], 250, 1000, "Graph 2"); chart3 = setUpChart(chart3, ColorTemplate.JOYFUL_COLORS[1], 1320, 2000, "Graph 3"); // Start chart layout animation process chartLayout = view.findViewById(R.id.chartLayout); // Starts the graph rotation timer startTimer = new CountDownTimer(START_FINISH, START_TICK) { /** onTick() * * Because of how the Android Countdown Timer works, a tick is automatically activated * once the clock starts. Since we only want this to activate once, we have a boolean * denying the initial tick to start. * * Other than that, we set up the view animation that rotates between sets of graphs * * @param l -The time between ticks */ @Override public void onTick(long l) { if(firstTick) firstTick = false; else animateView(chartLayout); } /** onFinish() * * After 5 minutes, we restart the application */ @Override public void onFinish() { restart(); } }.start(); // Clears all pre-existing exercises from the exercise manager Log.d(TAG, "onCreateView: Started."); return view; } /** animateView() * * Called by the start timer every 6 seconds upon tick. This animates the chart layout which contains * each graph on and off of the screen * * @param view -View to be animated, namely the chart layout */ private void animateView(View view) { // Sends the view off of the page ObjectAnimator anim = ObjectAnimator.ofFloat(view, "x", 0, 3000); anim.setDuration(1000); anim.start(); // Starts transition timer transitionTimer = new CountDownTimer(TRAN_FINISH, TRAN_TICK) { @Override public void onTick(long l) { } @Override public void onFinish() { // After waiting, send the alternate graphs back on to the screen demo = !demo; changeChart(); ObjectAnimator anim = ObjectAnimator.ofFloat(chartLayout, "x", -3000, 0); anim.setDuration(1000); anim.start(); } }.start(); } /** changeChart() * * Called by animateView(). This changes the data of the three pie graphs to the alternate set when * they are off the screen. This gives the illusion that there are multiple sets of charts being animated * */ private void changeChart() { // Alternates between graph sets if(!demo) { chart = setUpChart(chart, ColorTemplate.getHoloBlue(), 50, 100, "Graph 1"); chart2 = setUpChart(chart2, ColorTemplate.JOYFUL_COLORS[0], 250, 1000, "Graph 2"); chart3 = setUpChart(chart3, ColorTemplate.JOYFUL_COLORS[1], 1320, 2000, "Graph 3"); } else { chart = setUpChart(chart, Color.MAGENTA, 25, 100, "Graph 4"); chart2 = setUpChart(chart2, Color.CYAN, 750, 1000, "Graph 5"); chart3 = setUpChart(chart3, ColorTemplate.VORDIPLOM_COLORS[1], 1900, 2000, "Graph 6"); } } /** setUpChart() * * Called by setUpChart(). This takes as parameters all the values that each graph needs and uses the * GenerateGraph class to change it * * @param chart -The graph to be changed * @param color -The color scheme of the graph * @param value -How filled the graph is * @param max -Max value that the graph can be filled to * @param graphName -Name of the graph * @return The fully constructed graph */ private PieChart setUpChart(PieChart chart, int color, int value, int max, String graphName) { // Create an entirely new chart if there is not one yet if(chart == null) chart = new PieChart(getActivity()); // Creates a new chart with our parameters chart = GenerateGraph.createPieChart(chart, value, max, graphName); // Fills the graph with the data we receive from our parameters GenerateGraph.addData(chart, color, value, max); return chart; } /** restart() * * Clears the data that we've used for our routine. We essentially restart the application from the * beginning. * */ private void restart() { // Clears the list of exercises from our exercise selection fragment ExerciseSelectionFragment.adapter.clear(); ExerciseSelectionFragment.listItems.clear(); // Disconnects from all devices and the MQTT server ((MainActivity)getActivity()).disconnect(); TexTronicsManagerService.stop(getActivity()); // Restart the main activity to clear fragment manager and launch it again Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } }
true
a9e9863202827f1225c819ee4b0bea3d58a0e0b2
Java
dgutu/java
/SearchIncite/src/com/searchincite/client/widgets/entitylabels/DocumentStatusLabel.java
UTF-8
3,081
1.828125
2
[]
no_license
package com.searchincite.client.widgets.entitylabels; import com.google.gwt.user.client.ui.ClickListener; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Hyperlink; import com.google.gwt.user.client.ui.MenuBar; import com.google.gwt.user.client.ui.Widget; import com.searchincite.client.entity.DocumentResult; import com.searchincite.client.entity.DocumentWithResult; import com.searchincite.client.widgets.dialogs.ViewResultDialog; import org.gwm.client.event.GFrameEvent; import org.gwm.client.event.GFrameListener; public class DocumentStatusLabel extends Composite implements GFrameListener { DocumentWithResult m_Document; MenuBar m_ContextMenuBar = new MenuBar(true); ViewResultDialog m_dlgViewResult = null; DocumentStatusLabel m_This = this; public DocumentStatusLabel(DocumentWithResult d) { this.m_Document = d; Hyperlink hl = new Hyperlink(); hl.setText(d.getDocumentResult().getDocumentStatus()); hl.addClickListener(new ClickListener() { public void onClick(Widget hl) { DocumentStatusLabel.this.m_dlgViewResult = new ViewResultDialog(DocumentStatusLabel.this.m_Document.getDocumentID(), DocumentStatusLabel.this.m_Document.getDocumentResult().getOntology()); DocumentStatusLabel.this.m_dlgViewResult.setDialogFrameListener(DocumentStatusLabel.this.m_This); DocumentStatusLabel.this.m_dlgViewResult.show(); } }); initWidget(hl); } public DocumentStatusLabel(int documentIdParam, String ontologyNameParam) { final int documentId = documentIdParam; final String ontologyName = ontologyNameParam; Hyperlink hl = new Hyperlink(); hl.setText("processed"); hl.addClickListener(new ClickListener() { public void onClick(Widget hl) { DocumentStatusLabel.this.m_dlgViewResult = new ViewResultDialog(documentId, ontologyName); DocumentStatusLabel.this.m_dlgViewResult.setDialogFrameListener(DocumentStatusLabel.this.m_This); DocumentStatusLabel.this.m_dlgViewResult.show(); } }); initWidget(hl); } public DocumentWithResult getDocument() { return this.m_Document; } public void setDocument(DocumentWithResult d) { this.m_Document = d; } public void frameClosed(GFrameEvent evt) { this.m_dlgViewResult = null; } public void frameGhostMoved(int top, int left, GFrameEvent event) {} public void frameGhostMoving(int top, int left, GFrameEvent event) {} public void frameIconified(GFrameEvent evt) {} public void frameMaximized(GFrameEvent evt) {} public void frameMinimized(GFrameEvent evt) {} public void frameMoved(GFrameEvent evt) {} public void frameMoving(GFrameEvent event) {} public void frameOpened(GFrameEvent evt) {} public void frameResized(GFrameEvent evt) {} public void frameRestored(GFrameEvent evt) {} public void frameSelected(GFrameEvent event) {} }
true
92460027f43db3fd4789555a582567ca2a65f7bf
Java
wkendwr/FuturesBot
/src/messenger/facebook.java
UTF-8
5,397
2.328125
2
[ "Apache-2.0" ]
permissive
package messenger; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Properties; import org.jivesoftware.smack.Chat; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.MessageListener; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.SASLAuthentication; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.packet.Message; public class facebook implements MessageListener { XMPPConnection connection; private volatile static facebook fclient; static List<String> sendlist; static String id; static String pass; private facebook(){} public static facebook getInstance(){ Properties prop = new Properties(); try { // load a properties file prop.load(new FileInputStream("C:\\Profile\\config.properties")); // get the property value and print it out id = prop.getProperty("FB"); pass = prop.getProperty("FB_PASS"); } catch (IOException ex) { ex.printStackTrace(); } if (fclient == null) { synchronized (facebook.class){ if (fclient == null) { fclient = new facebook(); } } } return fclient; } public void login(String userName, String password) throws XMPPException { SASLAuthentication.registerSASLMechanism("DIGEST-MD5", MySASLDigestMD5Mechanism.class); ConnectionConfiguration config = new ConnectionConfiguration( "chat.facebook.com", 5222, "chat.facebook.com"); config.setCompressionEnabled(true); config.setSASLAuthenticationEnabled(true); connection = new XMPPConnection(config); connection.connect(); connection.login(userName, password); } public void sendMessage(String message, String to) throws XMPPException { Chat chat = connection.getChatManager().createChat(to, this); chat.sendMessage(message); } public void displayBuddyList() { Roster roster = connection.getRoster(); roster.setSubscriptionMode(Roster.SubscriptionMode.accept_all); Collection<RosterEntry> entries = roster.getEntries(); System.out.println("\n\n" + entries.size() + " buddy(ies):"); for (RosterEntry r : entries) { System.out.println(r.getName() + ":" + r.getUser()); } } public void getBuddyList() { Roster roster = connection.getRoster(); roster.setSubscriptionMode(Roster.SubscriptionMode.accept_all); Collection<RosterEntry> entries = roster.getEntries(); sendlist = new ArrayList<String>(); for (RosterEntry r : entries) { sendlist.add(r.getUser()); } } public void addRoster(String bot, String email, String input){ facebook c = facebook.getInstance(); try { addRoster(bot,input); c.sendMessage(input, email); } catch (XMPPException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addRoster(String bot,String input){ facebook c = facebook.getInstance(); try { c.login(id, pass); Roster roster = connection.getRoster(); roster.createEntry(input, null, null); } catch (XMPPException e) { // TODO Auto-generated catch block e.printStackTrace(); } c.disconnect(); } public void disconnect() { connection.disconnect(); } public void processMessage(Chat chat, Message message) { if (message.getType() == Message.Type.chat) System.out.println(chat.getParticipant() + " says: " + message.getBody()); } public static void main(String args[]) throws XMPPException, IOException { // declare variables facebook c = facebook.getInstance(); /*BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String msg;*/ // turn on the enhanced debugger XMPPConnection.DEBUG_ENABLED = false; // provide your login information here c.login(id, pass); System.out.println("-----"); c.displayBuddyList(); System.out.println("-----"); /*while (!(msg = br.readLine()).equals("bye")) { // your buddy's gmail address goes here c.sendMessage(msg, "-517003764@chat.facebook.com"); }*/ c.disconnect(); System.exit(0); } public void alert(String bot,String email, String msg) { facebook c = facebook.getInstance(); // turn on the enhanced debugger XMPPConnection.DEBUG_ENABLED = false; // provide your login information here try { c.login(id, pass); c.sendMessage(msg, email); Thread.sleep(500); } catch (XMPPException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } c.disconnect(); } public void alert(String bot, String msg) { facebook c = facebook.getInstance(); // turn on the enhanced debugger XMPPConnection.DEBUG_ENABLED = false; // provide your login information here try { c.login(id, pass); fclient.getBuddyList(); for (String list: sendlist){ c.sendMessage(msg, list); Thread.sleep(500); } } catch (XMPPException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } c.disconnect(); } }
true
7a48f7b7cb316ee7153f67befdd6df2c5eaac8bb
Java
Tibiusc/TutorialJava
/src/test/java/AbstractizareInterfete/PersoanaStudent.java
UTF-8
753
2.828125
3
[]
no_license
package AbstractizareInterfete; public class PersoanaStudent extends Persoana implements Student { //Mostenire = extends; (O clasa se mosteneste) //Interfata = implements; (O interfata se implementeaza) // O clasa poate implementa o multime de interfete; //Cand o clasa implementeaza o clasa => clasa trebuie sa ofere implementari pnetru toate metodele interfetei; public PersoanaStudent(String nume, String prenume, int varsta, String job) { super(nume, prenume, varsta, job); } @Override public void Invata() { System.out.println("Studentul " + getNume() + getPrenume() + " invata."); } @Override public void Detaliistudent() { System.out.println(super.toString()); } }
true
9462419586d1a6f64a2edcaaf147866941096aee
Java
batfish/batfish
/projects/question/src/test/java/org/batfish/question/comparefilters/CompareFiltersAnswererTest.java
UTF-8
5,246
2.25
2
[ "Apache-2.0" ]
permissive
package org.batfish.question.comparefilters; import static com.google.common.base.Preconditions.checkArgument; import static org.batfish.datamodel.LineAction.DENY; import static org.batfish.datamodel.LineAction.PERMIT; import static org.batfish.question.comparefilters.CompareFiltersAnswerer.compareFilters; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.empty; import static org.junit.Assert.assertThat; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.annotation.Nullable; import net.sf.javabdd.BDD; import org.batfish.common.bdd.BDDPacket; import org.batfish.common.bdd.PermitAndDenyBdds; import org.batfish.datamodel.LineAction; import org.junit.Test; public final class CompareFiltersAnswererTest { private static final String HOSTNAME = "hostname"; private static final String FILTER = "filter"; private final BDDPacket _pkt = new BDDPacket(); private final BDD _zero = _pkt.getFactory().zero(); private List<FilterDifference> compare( List<LineAction> currentActions, List<BDD> currentBdds, List<LineAction> referenceActions, List<BDD> referenceBdds) { List<PermitAndDenyBdds> currentLineBdds = toPermitAndDenyBdds(currentActions, currentBdds); List<PermitAndDenyBdds> refLineBdds = toPermitAndDenyBdds(referenceActions, referenceBdds); return compare(currentLineBdds, refLineBdds); } private List<FilterDifference> compare( List<PermitAndDenyBdds> currentBdds, List<PermitAndDenyBdds> referenceBdds) { return compareFilters(HOSTNAME, FILTER, currentBdds, referenceBdds, _pkt) .collect(Collectors.toList()); } private static FilterDifference difference( @Nullable Integer currentIndex, @Nullable Integer referenceIndex) { return new FilterDifference(HOSTNAME, FILTER, currentIndex, referenceIndex); } private List<BDD> aclBdds(BDD... lineBdds) { checkArgument(lineBdds.length > 0); ImmutableList.Builder<BDD> aclBdds = ImmutableList.builder(); BDD reach = _pkt.getFactory().one(); for (BDD lineBdd : lineBdds) { aclBdds.add(reach.and(lineBdd)); reach = reach.and(lineBdd.not()); } // add the BDD for flows that match no lines in the acl. aclBdds.add(reach); return aclBdds.build(); } @Test public void testCompareFilters() { BDD dstIp0 = _pkt.getDstIp().value(0); BDD dstIp1 = _pkt.getDstIp().value(1); BDD srcIp0 = _pkt.getSrcIp().value(0); BDD dstPort0 = _pkt.getDstPort().value(0); BDD srcPort0 = _pkt.getSrcPort().value(0); List<BDD> zeroBdds = aclBdds(dstIp0, srcIp0, dstPort0, srcPort0); // Representation of an empty Acl. List<BDD> emptyAclBdds = ImmutableList.of(_pkt.getFactory().one()); List<LineAction> emptyAclActions = ImmutableList.of(); List<LineAction> pppp = ImmutableList.of(PERMIT, PERMIT, PERMIT, PERMIT); List<LineAction> dpdp = ImmutableList.of(DENY, PERMIT, DENY, PERMIT); // If nothing has changed, return no differences assertThat(compare(pppp, zeroBdds, pppp, zeroBdds), empty()); // If all lines deleted, return a difference for each permit line assertThat( compare(emptyAclActions, emptyAclBdds, pppp, zeroBdds), contains( difference(null, 0), difference(null, 1), difference(null, 2), difference(null, 3))); assertThat( compare(emptyAclActions, emptyAclBdds, dpdp, zeroBdds), contains(difference(null, 1), difference(null, 3))); // If all lines added, return a difference for each permit line assertThat( compare(pppp, zeroBdds, emptyAclActions, emptyAclBdds), contains( difference(0, null), difference(1, null), difference(2, null), difference(3, null))); assertThat( compare(dpdp, zeroBdds, emptyAclActions, emptyAclBdds), contains(difference(1, null), difference(3, null))); { List<BDD> currentAcl = zeroBdds; List<BDD> referenceAcl = aclBdds(dstIp1, srcIp0, dstPort0, srcPort0); // if we change a permit line, we get differences for that line in each direction assertThat( compare(pppp, currentAcl, pppp, referenceAcl), contains(difference(0, null), difference(null, 0))); // if we change a deny line, we affect later permit lines List<FilterDifference> compare = compare(dpdp, currentAcl, dpdp, referenceAcl); assertThat( compare, contains(difference(0, 1), difference(0, 3), difference(1, 0), difference(3, 0))); } } private List<PermitAndDenyBdds> toPermitAndDenyBdds(List<LineAction> actions, List<BDD> bdds) { // bdds should have one more element than actions, representing the default denied packets assert bdds.size() == actions.size() + 1; return IntStream.range(0, bdds.size()) .mapToObj( i -> { LineAction action = i == actions.size() ? DENY : actions.get(i); return action == PERMIT ? new PermitAndDenyBdds(bdds.get(i), _zero) : new PermitAndDenyBdds(_zero, bdds.get(i)); }) .collect(ImmutableList.toImmutableList()); } }
true
d951326ad82e0890c85fe4f7cba015976d7bd532
Java
YYdesoul/spring5-study
/spring-08-proxy/src/main/java/com/soul/staticProxy/Client.java
UTF-8
320
2.5625
3
[]
no_license
package com.soul.staticProxy; public class Client { public static void main(String[] args) { // without proxy // Host host = new Host(); // host.rent(); // 代理可以做一些被代理对象做不了的事情 Proxy proxy = new Proxy(new Host()); proxy.rent(); } }
true
3acd88493563e1eb7f4f44a1a78656df55357b2f
Java
mfkiwl/jet
/limo_apps/Dev_and_test_apps/TabExample/src/com/reconinstruments/tabexample/WidgetTestActivity.java
UTF-8
428
1.757813
2
[]
no_license
package com.reconinstruments.tabexample; import android.app.Activity; import android.os.Bundle; import android.view.View; public class WidgetTestActivity extends Activity { private View mTabView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTabView = new TestTabView(this); setContentView(mTabView); } }
true
379a18ba581ec226762e2aebd383b9ba323d1945
Java
ycfn97/IdeaWorkspace
/ArraySortProj/src/myarraysort/BinarySearch.java
UTF-8
2,523
4.21875
4
[]
no_license
package myarraysort; import java.util.Arrays; import java.util.Scanner; public class BinarySearch { public static void main(String[] args) { int arr[]=new int[10]; for (int i=0;i<10;i++){ arr[i]=(int)(Math.random()*100+1); } Arrays.sort(arr); System.out.println(Arrays.toString(arr)); System.out.println("please input number to search:"); Scanner scanner=new Scanner(System.in); int num=scanner.nextInt(); boolean result=binarySearch01(arr,0,arr.length-1,num); System.out.println(result?"find it!":"not found."); } /** * 递归法二分查找,首先判断数组是否为空,如果不为空,找到中间节点判断待查找元素与中间节点数字大小关系, * 并对开始或者结束节点进行调整进行下一次递归调用,直到中间节点等于待查找元素或者开始节点大于结束节点 * 那么就说明没有找到,返回false,查找函数用到一个boolean标记,如果找到标记就会变成true * @param arr 已排好序的待查找数组 * @param start 开始查找位置 * @param end 结束查找位置 * @param num 待查找元素 * @return 是否找到 */ public static boolean binarySearch(int[] arr,int start,int end,int num){ boolean flag=false; if (arr.length==0){ return flag; } int mid=(start+end)/2; if (start>end){ return false; } if (arr[mid]>num){ end=mid-1; flag=binarySearch(arr,start,end,num); } if (arr[mid]<num){ start=mid+1; flag=binarySearch(arr,start,end,num); } if (arr[mid]==num){ flag=true; } return flag; } /** * for循环二分查找,思路与递归法相同 * @param arr 已排好序的待查找数组 * @param start 开始查找位置 * @param end 结束查找位置 * @param num 待查找元素 * @return 是否找到 */ public static boolean binarySearch01(int[] arr,int start,int end,int num){ boolean flag=false; for (;start<=end;){ int middle=(start+end)/2; if (arr[middle]==num){ flag=true; break; }else if (num>arr[middle]){ start=middle+1; }else { end=middle-1; } } return flag; } }
true
1af990b3cf3b2e9cd45e98216b4a1f2b1097edaa
Java
Viji7789/PageObjectModel
/PageObjectModel/src/testCases/MyProfilePage.java
UTF-8
2,103
2.0625
2
[]
no_license
package testCases; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.PageFactory; import pageObjects.LoginPageObjects; //import org.openqa.selenium.interactions.Actions; import pageObjects.MyInfoPageObjects; public class MyProfilePage { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver", "C:\\chromedriver\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get("https://opensource-demo.orangehrmlive.com/"); PageFactory.initElements(driver, LoginPageObjects.class); LoginPageObjects.username.sendKeys("Admin"); LoginPageObjects.password.sendKeys("admin123"); LoginPageObjects.LoginButton.click(); Thread.sleep(1000); PageFactory.initElements(driver, MyInfoPageObjects.class); MyInfoPageObjects.MyInfo.click(); MyInfoPageObjects.EditButton.click(); MyInfoPageObjects.GenderSelect.click(); MyInfoPageObjects.SaveButton.click(); /*MyInfoPageObjects.MyInfo(driver).click(); MyInfoPageObjects.EditButton(driver).click(); MyInfoPageObjects.GenderSelect(driver).click(); MyInfoPageObjects.SaveButton(driver).click();*/ /*WebElement username=driver.findElement(By.id("txtUsername")); username.sendKeys("Admin"); WebElement password=driver.findElement(By.id("txtPassword")); password.sendKeys("admin123"); WebElement loginButton=driver.findElement(By.id("btnLogin")); loginButton.click();*/ /*WebElement MyInfo=driver.findElement(By.xpath("//*[@id=\'menu_pim_viewMyDetails\']")); MyInfo.click(); WebElement EditButton=driver.findElement(By.id("btnSave")); EditButton.click(); WebElement GenderSelect=driver.findElement(By.id("personal_optGender_2")); GenderSelect.click(); WebElement SaveButton=driver.findElement(By.id("btnSave")); SaveButton.click();*/ driver.quit(); } }
true
cd7595d339aa8f291a1b16561b954f0ca2cfa0e1
Java
nettm/exercise
/exercise-spring/src/main/java/com/nettm/exercise/spring/cat/MyCatService.java
UTF-8
228
2.15625
2
[ "Apache-2.0" ]
permissive
package com.nettm.exercise.spring.cat; import org.springframework.stereotype.Component; @Component public class MyCatService implements MyCat { @Override public void run() { System.out.println("run"); } }
true
814946ddaeddd6a2bff0f8162a898cdb37c743a9
Java
nguyentung-199/HomeInsurance
/src/kevinrogers/homeinsurance/servlet/GenerateQuote.java
UTF-8
3,060
2.390625
2
[]
no_license
package kevinrogers.homeinsurance.servlet; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.text.DecimalFormat; import java.text.ParseException; /** * Servlet implementation class GenerateQuote */ @WebServlet("/GenerateQuote") public class GenerateQuote extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public GenerateQuote() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // response.getWriter().append("Served at: ").append(request.getContextPath()); try { int quoteID = 1; HttpSession session = request.getSession(true); String sqFt = (String) session.getAttribute("SquareFeet"); int squareFeet = Integer.parseInt(sqFt); DecimalFormat df = new DecimalFormat("0.00"); double dwellingCoverage = squareFeet * 90; String dwellingCoverageHundredths = df.format(dwellingCoverage); double roundedDwellingCoverage = (Double)df.parse(dwellingCoverageHundredths); double premium = dwellingCoverage * 0.15; String premiumHundredths = df.format(premium); double roundedPremium = (Double)df.parse(premiumHundredths); double detachedStructures = dwellingCoverage * 0.1; String detachedStructuresHundredths = df.format(detachedStructures); double roundedDetachedStructures = (Double)df.parse(detachedStructuresHundredths); double personalProperty = dwellingCoverage * 0.07; String personalPropertyHundredths = df.format(personalProperty); double roundedPersonalProperty = (Double)df.parse(personalPropertyHundredths); double additionalExpenses = dwellingCoverage * 0.2; String additionalExpensesHundredths = df.format(additionalExpenses); double roundedAdditionalExpenses = (Double)df.parse(additionalExpensesHundredths); double medicalExpense = 5000.00; double deductible = 250.00; RequestDispatcher rd = request.getRequestDispatcher("/JSP/CoverageDetails.jsp"); rd.forward(request, response); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
true
2e64250565b82f30daa1d935a3065591f6dd7f58
Java
mstftikir/contactlist
/src/test/java/com/kn/contactlist/service/impl/ContactListServiceImplTests.java
UTF-8
2,194
2.234375
2
[ "Apache-2.0" ]
permissive
package com.kn.contactlist.service.impl; import com.kn.contactlist.dto.ContactDto; import com.kn.contactlist.exception.type.BusinessException; import com.kn.contactlist.model.ContactTable; import com.kn.contactlist.repository.ContactRepository; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.jupiter.api.Assertions; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import java.util.Date; import java.util.LinkedList; import java.util.List; public class ContactListServiceImplTests { @Mock private ContactRepository contactRepository; @InjectMocks private ContactListServiceImpl contactListService; private static final String name = "Test Name"; private static final String url = "Test Url"; private static final String serviceUserId = "10000"; private final List<ContactTable> contactTableList = new LinkedList<>(); @Before public void setUp() { MockitoAnnotations.initMocks(this); ContactTable contactTable = new ContactTable(); contactTable.setName(name); contactTable.setUrl(url); contactTable.setCreateTime(new Date()); contactTable.setCreateUserId(serviceUserId); contactTable.setUpdateTime(new Date()); contactTable.setUpdateUserId(serviceUserId); contactTableList.add(contactTable); } @Test public void findAllContactsExceptionTest(){ Mockito.when(contactRepository.findAll()).thenReturn(new LinkedList<>()); Assertions.assertThrows(BusinessException.class, () -> contactListService.findAllContacts()); } @Test public void findAllContactsCorrectValueTest() throws BusinessException { Mockito.when(contactRepository.findAll()).thenReturn(contactTableList); List<ContactDto> contactDtoList = contactListService.findAllContacts(); Assert.assertNotNull(contactDtoList); Assert.assertEquals(name, contactDtoList.get(0).getName()); Assert.assertEquals(url, contactDtoList.get(0).getUrl()); } }
true
196ce8278106a56954c3d5a315169f5eefe0136c
Java
thinkpi9/spring-boot
/spring-boot-async/src/main/java/com/learn/asyc/component/WebSocketComponent.java
UTF-8
1,634
2.71875
3
[]
no_license
package com.learn.asyc.component; import java.io.IOException; import java.util.Iterator; import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import org.springframework.stereotype.Component; @Component @ServerEndpoint("/test/info") public class WebSocketComponent { private Session session; private static CopyOnWriteArraySet<WebSocketComponent> webSocketSet = new CopyOnWriteArraySet<WebSocketComponent>(); @OnOpen public void onOpen(Session session) { this.session = session; webSocketSet.add(this); System.out.println("new Session be added:" + session.getId()); } @OnMessage public void onMessage(String content, Session session) { System.out.println(String.format("Session->[{%s}]:Message:[{%s}]", session.getId(), content)); } @OnError public void onError(Session session, Throwable error) { System.out.println("error"); } @OnClose public void onClose() { System.out.println("new Session be remove:" + this.session.getId()); webSocketSet.remove(this); } public Session getSession() { return session; } public static void sendMessage(String content) throws IOException { Iterator<WebSocketComponent> iterator = webSocketSet.iterator(); while (iterator.hasNext()) { WebSocketComponent component = iterator.next(); Session session = component.getSession(); session.getBasicRemote().sendText(content); } } }
true
09b5c4a9014138a24e36b804beaba10aed7620f9
Java
lsm1998/jvm
/src/main/java/com/lsm1998/jvm/clazz/constant/impl/ConstantMethodTypeInfo.java
UTF-8
577
2.234375
2
[]
no_license
package com.lsm1998.jvm.clazz.constant.impl; import com.lsm1998.jvm.clazz.ClassRead; import com.lsm1998.jvm.clazz.constant.ConstantInfo; import com.lsm1998.jvm.utils.ClassReadUtil; /** * @作者:刘时明 * @时间:2019/3/28-15:40 * @作用: */ public class ConstantMethodTypeInfo implements ConstantInfo { public int descriptorIndex; @Override public void readInfo(ClassRead classRead) { descriptorIndex= ClassReadUtil.readU2(classRead); } @Override public String toString() { return "#"+descriptorIndex; } }
true
dc19a07ce4e63f499c6390e36ec9b9123ff060db
Java
Icygocode/Project_DA_Java_EN_Come_to_the_Rescue_of_a_Java_Application
/Project02Eclipse/src/com/hemebiotech/analytics/writer/WriteException.java
UTF-8
160
1.929688
2
[]
no_license
package com.hemebiotech.analytics.writer; public class WriteException extends Exception { public WriteException(Throwable cause) { super(cause); } }
true
efb0ca7118ad4d868dda7686a96b874b85117a89
Java
akhil741990/java8-try-outs
/src/com/soul/java8/iterable/foreach/Java8ForEachInIterable.java
UTF-8
706
3.6875
4
[]
no_license
package com.soul.java8.iterable.foreach; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; public class Java8ForEachInIterable { public static void main(String args[]) { List<Integer> l = new ArrayList<>(); l.add(1); l.add(2); l.add(3); l.forEach(new Consumer<Integer>() { @Override public void accept(Integer t) { System.out.println("Consumed via annonymous class :"+ t); } }); MyListConsumer consumer = new MyListConsumer(); l.forEach(consumer); } static class MyListConsumer implements Consumer<Integer> { @Override public void accept(Integer t) { System.out.println("Consumed :"+ t); } } }
true
1ee3ac162f55fbfb8b0521a6d60aa65df80d61fa
Java
shika-sophia/sepJavaRecurrent
/javaSilver/SE11Black/Examin02.java
UTF-8
6,474
2.984375
3
[]
no_license
/** * @title javaSilver / SE11Black / Examin02 * @content * @see 志賀澄人『徹底攻略 Java SE11 Silver 問題集[1ZO-815]』(黒本),インプレス, 2019 * @author shika * @date 2021-01-18 / 07:52-10:29 (157分) * @correctRate ①73.75 % ( 〇59問 / 全80問 ) */ package javaSilver.SE11Black; import javaSilver.AnswerMaker; public class Examin02 { public static void main(String[] args) { new AnswerMaker(); }//main() }//class /* //====== 1回目 / 2021-01-18 ====== 〇 1: D 〇 2: A, B, D × 3: C => 〇: A float -> intは キャストが必要 × 4: D, E, F => 〇: C, E, F D: package-privateなので全て参照可は間違い C: CacheTrash.add()は明記されていないが、他の選択肢の間違いに気付けば、これを選べる。 〇 5: C 〇 6: C 〇 7: A 〇 8: D 〇 9: E × 10: C, E => 〇: A, E var List list = new ArrayList<>();は defaultだと <Object>になり、varもOK。 〇 11: B × 12: A, D => 〇: C, D var a = { 1.0, 2.0, 3.0, 4.0 };は、型を明記していないのでコンパイルエラー。 (double値の配列と推論できるけど、 floatかもしれない。この曖昧さがエラーにした理由かも) × 13: D => 〇: C (分ってて選択肢の入力ミスや)もったいない。気を付けよう。 〇 14: D 「super.super.method();」はコンパイルエラー。一つ上のsuperのみアクセス可。 〇 15: B 〇 16: D × 17: C, E => 〇: A, E ◆無名配列 sample(new int[]{ 1, 2, 3 }); メソッドの引数を渡すために名前を付けなくてもインスタンスできる。 int[] array; array = new int[]{ };要素数を未定義に見えるが、{ }で要素0と定義できる。 C: new Double[3]{ };初期化子を付けたら[3]要素数を記述するとコンパイルエラー。 〇 18: E × 19: D => 〇: B 「D: 22 + 22 + 2 = 46」してたわ。a=10なので 54ね。(初歩的なミス) 〇 20: B 〇 21: A 〇 22: D 〇 23: C 〇 24: A 〇 25: D 〇 26: C 〇 27: B 〇 28: B Consumer<>は戻り値を返さないので returnで値を返すとコンパイルエラー。 x -> { return x }はOK。 x -> return xはNG。 〇 29: D × 30: E => 〇: C interface { void method();} -> 暗黙で public abstract -> これ間違えやすい × 31: B => 〇: A ◆Map<key, value> keySet(): keyを取り出し Set型を戻す。 value(): valueを取り出し、Collection型をの参照を返す。 set(Collection c)を set(List<String> list)では呼び出せない。 × 32: C => 〇: B default で Overrideすることは可能。 共変戻り値: Overrideでは、同じ型かそのサブクラスの戻り値が可能。 × 33: A => 〇: C int[] -> Ocject[]は互換性がない。 int[] -> Objectで受ける。 int[] -> long[]の暗黙の型変換があるが、32bit-> 64bitの処理が必要なため、Objectのが近い型。 × 34: D => 〇: A int[][] ary = new int[2][4];と定義した配列に ary[0] = { 1, 2, 3, 4 }; ary[1] = { 1, 2 }; はOK。非対称な多次元配列。 〇 35: D 〇 36: D × 37: A => 〇: C String strは、ローカル変数。初期化はされないので、これを使うとコンパイルエラー。 fieldなら、nullで初期化と混同しないように。 〇 38: E 〇 39: D 〇 40: A 〇 41: A × 42: D => 〇: C ◆try-catch-resource文の順序 ① close()を自動的に呼び出しリソースを解放 -> close()が Overrideされてていればそちらを呼び出し ②catch ③finally × 43: B, C => 〇: C, D モジュールを実行するときは class-pathが通るので、モジュール内のディレクトリにアクセス可能。 〇 44: A × 45: B, C, D => 〇: B, D, E 抽象クラスは、具象メソッドだけでも可。 C: abstract で { }を付けるとコンパイルエラー。 A: abstractは自動付記されないので、明記する。 〇 46: C 〇 47: A 〇 48: D, E 〇 49: C 〇 50: C, D 〇 51: C 〇 52: D, G, H 〇 53: A 〇 54: A, E 〇 55: E 〇 56: B 〇 57: A 〇 58: C × 59: C => 〇: A オートアンボクシング int Integer.intValue(Integer) 〇 60: A 〇 61: B 〇 62: A ststic fieldは、インスタンス変数を利用して呼び出しても コンパイル時にクラス名へ変換される。 a.num -> Main.num 〇 63: D, E 〇 64: C 〇 65: D × 66: B => 〇: E null.nameでフィールドを呼び出したら NullPo 〇 67: B × 68: E, F => 〇: B, F 共変戻り値に型パラメタ<Object>の中身は適用しない List<Number>, ArrayList<Number>はOK。 List<Number>, List<Integer>はNG。 Overrideだけじゃなくシグニチャを変えてオーバーロードも可能。 Set<CharSequence>, Set<String>はシグニチャを変えたことにならない。完全一致でもない Set<CharSequence>, TreeSet<CharSequence>ならオーバーロード成立。 ただし、@Overrideを付記するとコンパイルエラー。 〇 69: C array.length: 配列の要素数 array[i].length(): 配列の中身である要素の String.length() 〇 70: A 〇 71: C, D 〇 72: C 〇 73: C × 74: A => 〇: C ◆2次元配列のclone(): new 新しい配列を作り、要素の参照先をコピー。(シャローコピー「浅いコピー」) ◆1次元配列のclone(): new 新しい配列を作り、要素の値をコピー(ディープコピー)。元の配列と参照先が違う。 ◆Object.equals(): defaultで同一性(参照先)で判定 array2 = array1.clone();により、 要素の参照は同じでも、別の配列 -> 配列の参照先は違う。 〇 75: C × 76: A, B ? => 〇: B, E メソッド参照は ()を付けない String::toUpperCase ならOK。 〇 77: A 〇 78: B 〇 79: A ◇74参照 1次元配列 clone()は要素のコピー。変更しても元の配列に影響しない。 Object.clone()なので全てのクラスで使える。 〇 80: A 開始時刻 07:52 終了時刻 10:29 所要時間 157 分 正答率 73.75 % ( 〇59問 / 全80問 ) */
true
8dfb10713b423255b4cceb7d32bd26476e1751a5
Java
sgholamian/log-aware-clone-detection
/NLPCCd/HBase/770_2.java
UTF-8
481
2.078125
2
[ "MIT" ]
permissive
//,temp,sample_5465.java,2,19,temp,sample_5510.java,2,19 //,3 public class xxx { public void dummy_method(){ reader = createWALReaderForPrimary(); long flushSeqId = -1; while (true) { WAL.Entry entry = reader.next(); if (entry == null) { break; } FlushDescriptor flushDesc = WALEdit.getFlushDescriptor(entry.getEdit().getCells().get(0)); if (flushDesc != null) { if (flushDesc.getAction() == FlushAction.START_FLUSH) { log.info("replaying flush start in secondary"); } } } } };
true
e82c01e38370ae76c94a88c9f5fc0903d2aa1eea
Java
hkdragon9/HashWolf2_BackEnd
/hashwolf2/src/main/java/com/HashWolf2/hashwolf2/Controllers/UserController.java
UTF-8
2,091
2.296875
2
[]
no_license
package com.HashWolf2.hashwolf2.Controllers; import com.HashWolf2.hashwolf2.Model.GroupTable; import com.HashWolf2.hashwolf2.Model.User; import com.HashWolf2.hashwolf2.Repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(value = "/user") public class UserController { @Autowired private UserRepository usersRepository; public UserController(UserRepository userRepository){ this.usersRepository = userRepository; } public UserRepository getUsersRepository() { return usersRepository; } @RequestMapping(value = "/all") public List<User> getAll(){ return usersRepository.findAll(); } @RequestMapping(value = "/clear") public List<User> clear(){ usersRepository.deleteAll(); return usersRepository.findAll(); } @RequestMapping(value = "/add", method = RequestMethod.GET) public List<User> add(@RequestBody final User user) { usersRepository.save(user); return usersRepository.findAll(); } @GetMapping("/findUserByID/{userID}") public User getUserbyId(@PathVariable("userID") final Integer uid) { return usersRepository.findByUserid(uid); } @GetMapping("/findUserGroupsByID/{userID}") public List<GroupTable> getUserGroups(@PathVariable("userID") final Integer uid) { return usersRepository.findByUserid(uid).getGroups(); } @RequestMapping(value = "/addNewUser", method = RequestMethod.GET) public List<User> insert(@RequestParam String user_name, @RequestParam String user_email) { User tempUser = new User(user_name, user_email, null); usersRepository.save(tempUser); return usersRepository.findAll(); } @RequestMapping(value = "/containsGroup") public void addGroupToUser(@RequestParam int userID, @RequestParam int groupID) { User user = usersRepository.findByUserid(userID); //GroupTable group = null; } }
true
3bd90d664f5a18fb67021dc11de1c4ee60939b71
Java
zuokai666/WorkFlow
/workflow/src/main/java/org/zk/workflow/util/TimeUtil.java
UTF-8
357
2.109375
2
[]
no_license
package org.zk.workflow.util; import java.text.SimpleDateFormat; import java.util.Date; public class TimeUtil { public static String now(){ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return dateFormat.format(new Date()); } public static String key(){ return "" + System.currentTimeMillis(); } }
true
2d19df72fdae446ddc275b667a42e7a4bff7e94d
Java
zulnerub/Java---Java-OOP
/InterfacesAndAbstraction/army/HelperClasses/Interfaces/Repair.java
UTF-8
144
2.34375
2
[]
no_license
package InterfacesAndAbstraction.army.HelperClasses.Interfaces; public interface Repair { String getName(); String getHoursWorked(); }
true
824d599effd9d747f90b0e528e529d42daf01101
Java
jrnbulu/core-java
/coreJavaApp/src/com/bss/module1/SumOfNumbersInRange.java
UTF-8
847
3.59375
4
[]
no_license
package com.bss.module1; import java.util.Scanner; public class SumOfNumbersInRange { public static void main(String[] args) { int start,end; if(args.length > 1) { start = Integer.parseInt(args[0]); end = Integer.parseInt(args[1]); System.out.println("Input from command line array: start :"+args[0]+" and end:"+args[1]); System.out.println("After adding numbers in given range:"+getSumOfNumbers(start,end)); } Scanner sc=new Scanner(System.in); start=sc.nextInt(); end=sc.nextInt(); System.out.println("Input from scanner: start :"+start+" and end:"+end); System.out.println("After adding numbers in given range:"+getSumOfNumbers(start,end)); } public static int getSumOfNumbers(int startNum,int endNum) { int i,sum=0; for(i=startNum;i<=endNum;i++) { sum +=i; } return sum; } }
true
fd1c07bf9ee6293570b93446b3cd0f0fab53a433
Java
kongra/SAN
/2013 letni/Lodz B/ALGO-Lodz-B/src/san/algo/TestPow.java
UTF-8
512
2.703125
3
[]
no_license
package san.algo; import java.math.BigInteger; import san.algo.math.Pow; public class TestPow { public static void main(String[] args) { for (int i = 0; i < 10; i++) { testFastPow(); } // System.out.println(val.toString().length()); } private static void testFastPow() { long start = System.currentTimeMillis(); String s = Pow.fast(2, 1000000).toString(); long end = System.currentTimeMillis(); System.out.println("Finished in " + (end - start) + " msecs."); } }
true
08252e05b7514dad3b70c83742fa7b28bdd5db8a
Java
jeyanthank/graph-cloner
/src/main/java/com/workspan/cloner/model/Entity.java
UTF-8
1,488
2.6875
3
[]
no_license
package com.workspan.cloner.model; import com.google.gson.annotations.SerializedName; import java.util.Optional; /** * User: jeyanthan * Date: 2019-02-27 * Add description here */ public class Entity { @SerializedName("entity_id") private Integer entityId; private String name; private String description; public Entity(Integer entityId){ this.entityId = entityId; } public Entity(Integer entityId, String name, Optional<String> description){ this.entityId = entityId; this.name = name; this.description = description.orElse(""); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + entityId.hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Entity other = (Entity) obj; if (this.entityId == null) { if (other.entityId != null) return false; } else if (!this.entityId.equals(other.entityId)) return false; return true; } public Integer getEntityId() { return entityId; } public String getName() { return name; } public String getDescription() { return description; } }
true
8a5d4dac3d74c95accd807bcbf8ddf00d327c8be
Java
suyeongs/PayQuick_GraduationProject
/Android/app/src/main/java/com/example/payquick/ScanStockActivity.java
UTF-8
4,173
2.140625
2
[]
no_license
package com.example.payquick; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.Toast; import com.google.zxing.ResultPoint; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import com.journeyapps.barcodescanner.BarcodeCallback; import com.journeyapps.barcodescanner.BarcodeResult; import com.journeyapps.barcodescanner.CaptureManager; import com.journeyapps.barcodescanner.DecoratedBarcodeView; import java.util.List; public class ScanStockActivity extends AppCompatActivity { private CaptureManager capture; private DecoratedBarcodeView barcodeScannerView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan_stock); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_light); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); barcodeScannerView = (DecoratedBarcodeView) findViewById(R.id.dbv_barcode); capture = new CaptureManager(this, barcodeScannerView); capture.initializeFromIntent(this.getIntent(), savedInstanceState); capture.decode(); //readBarcode("1342323873290"); barcodeScannerView.decodeContinuous(new BarcodeCallback() { @Override public void barcodeResult(BarcodeResult result) { readBarcode(result.toString()); } @Override public void possibleResultPoints(List<ResultPoint> resultPoints) { } }); } // 툴바 뒤로가기 @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); capture.onResume(); } @Override protected void onPause() { super.onPause(); capture.onPause(); } @Override protected void onDestroy() { super.onDestroy(); capture.onDestroy(); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); capture.onSaveInstanceState(outState); } // 바코드 읽어서 다음으로 넘김 public void readBarcode(String barcode) { Intent sendIntent = new Intent(getApplicationContext(), SearchStockActivity.class); sendIntent.putExtra("barcode_id", barcode); startActivity(sendIntent); //Toast.makeText(getApplicationContext(), barcode, Toast.LENGTH_SHORT).show(); } /* // 참고 : https://superwony.tistory.com/78 @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan_stock); IntentIntegrator intentIntegrator = new IntentIntegrator(this); intentIntegrator.setBeepEnabled(false); // 바코드 인식시 소리 intentIntegrator.initiateScan(); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (intentResult != null) { if (intentResult.getContents() == null) { Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "Scanned : " + intentResult.getContents(), Toast.LENGTH_LONG).show(); } } else { super.onActivityResult(requestCode, resultCode, data); } } */ }
true
f0e62f927f4ebfd91582c9b6e1885fcab92d5bd6
Java
Ikii-developer/ikii-backend
/ikii-back-microservices/ikii-back-payment/src/main/java/mx/ikii/payment/service/payment/IkiiPaymentServiceWrapperImpl.java
UTF-8
6,102
1.882813
2
[ "MIT" ]
permissive
package mx.ikii.payment.service.payment; import java.util.List; import java.util.Objects; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.server.ResponseStatusException; import io.conekta.PaymentSource; import lombok.extern.slf4j.Slf4j; import mx.ikii.commons.exception.handler.ConektaRepositoryException; import mx.ikii.commons.exception.handler.FeignException; import mx.ikii.commons.feignclient.service.impl.ICustomerDetailsFeignService; import mx.ikii.commons.payload.request.payment.conekta.CustomerConektaWrapperRequest; import mx.ikii.commons.payload.request.payment.conekta.CustomerConektaWrapperRequest.ConektaCardInfo; import mx.ikii.commons.persistence.collection.CustomerDetails; import mx.ikii.payment.mapper.PaymentMethodMapper; import mx.ikii.payment.methods.conekta.service.payments.IPaymentsConektaService; import mx.ikii.payment.payload.dto.PaymentMethodDTO; import mx.ikii.payment.payload.request.PaymentSourceRequest; import mx.ikii.payment.payload.response.PaymentMethodResponse; import mx.ikii.payment.service.customer.IkiiPaymentCustomerServiceWrapperImpl; import mx.ikii.payment.payload.response.CustomerConektaResponse; @Slf4j @Service public class IkiiPaymentServiceWrapperImpl implements IKiiPaymentServiceWrapper { @Autowired private IPaymentsConektaService paymentsConektaService; @Autowired private IkiiPaymentCustomerServiceWrapperImpl ikiiPaymentCustomerServiceWrapperImpl; @Autowired private ICustomerDetailsFeignService customerDetailsFeignService; @Override public List<PaymentMethodResponse> getPaymentMethod(String ikiiCustomerId) { log.info( "[IkiiPaymentServiceWrapperImpl] - INIT get payment method with customerId [{}] ", ikiiCustomerId); List<PaymentSource> paymentsSource = null; try { CustomerDetails customerDetails = customerDetailsFeignService.findByCustomerId(ikiiCustomerId); String customerConektaId = customerDetails.getCustomerConektaId(); if (Objects.isNull(customerConektaId)) { throw new ResponseStatusException(HttpStatus.CONFLICT, "Provider payment user has not been created"); } paymentsSource = paymentsConektaService.find(customerConektaId); } catch (ConektaRepositoryException e) { log.error(e.getMessage(), e); throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage(), e); } return PaymentMethodMapper.paymentSourceToPaymentMethodsResponse(paymentsSource); } @Override public PaymentMethodResponse createPaymentMethod(String ikiiCustomerId, PaymentMethodDTO paymentMethodRequest) { log.info( "[IkiiPaymentServiceWrapperImpl] - INIT create payment method with customerId [{}] and request [{}] ", ikiiCustomerId, paymentMethodRequest); try { CustomerDetails customerDetails = customerDetailsFeignService.findByCustomerId(ikiiCustomerId); String customerConektaId = customerDetails.getCustomerConektaId(); PaymentSource paymentSource = null; if (Objects.isNull(customerConektaId)) { CustomerConektaResponse customerConektaResponse = ikiiPaymentCustomerServiceWrapperImpl .createCustomerConekta(CustomerConektaWrapperRequest.builder() .conektaCardInfo(ConektaCardInfo.builder() .token(paymentMethodRequest.getToken_id()) .type(paymentMethodRequest.getType()).build()) .ikiiCustomerId(ikiiCustomerId).ikiiCustomerDetailId(customerDetails.getId()) .build()); customerConektaId = customerConektaResponse.getId(); } paymentSource = paymentsConektaService.create(customerConektaId, paymentMethodRequest); return PaymentMethodMapper.paymentSourceToPaymentMethodResponse(paymentSource); } catch (FeignException | ConektaRepositoryException e) { log.error(e.getMessage(), e); throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage(), e); } catch (Exception e) { log.error(e.getMessage(), e); throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage(), e); } } @Override public void updatePaymentMethod(String ikiiCustomerId, PaymentSourceRequest paymentSourceRequest) { log.info( "[IkiiPaymentServiceWrapperImpl] - INIT update payment method with customerId [{}] and request [{}] ", ikiiCustomerId, paymentSourceRequest); try { CustomerDetails customerDetails = customerDetailsFeignService.findByCustomerId(ikiiCustomerId); String customerConektaId = customerDetails.getCustomerConektaId(); if (Objects.isNull(customerConektaId)) { throw new ResponseStatusException(HttpStatus.CONFLICT, "Provider payment user has not been created"); } paymentsConektaService.update(customerConektaId, paymentSourceRequest); } catch (ConektaRepositoryException e) { log.error(e.getMessage(), e); throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage(), e); } } @Override public void deletePaymentMethod(String ikiiCustomerId, String paymentMethodId) { try { log.info( "[IkiiPaymentServiceWrapperImpl] - INIT delete payment method with customerId [{}] and paymentSourceId [{}] ", ikiiCustomerId, paymentMethodId); CustomerDetails customerDetails = customerDetailsFeignService.findByCustomerId(ikiiCustomerId); String customerConektaId = customerDetails.getCustomerConektaId(); if (Objects.isNull(customerConektaId)) { throw new ResponseStatusException(HttpStatus.CONFLICT, "Provider payment user has not been created"); } paymentsConektaService.delete(customerConektaId, paymentMethodId); } catch (ConektaRepositoryException e) { log.error(e.getMessage(), e); throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage(), e); } } }
true
d804264ca144f0285f58750196ce5bd05cd76729
Java
war10ckIT/javaRogueLike
/src/main/java/com/fxgl/games/roguelike/control/BombControl.java
UTF-8
988
2.5
2
[ "MIT" ]
permissive
package com.fxgl.games.roguelike.control; import com.almasb.fxgl.app.FXGL; import com.almasb.fxgl.entity.component.Component; import com.almasb.fxgl.entity.components.BoundingBoxComponent; import com.fxgl.games.roguelike.GameApp; import com.fxgl.games.roguelike.GameTypes; public class BombControl extends Component { private int radius; public BombControl(int radius) { this.radius = radius; } @Override public void onUpdate(double tpf) { } public void explode() { BoundingBoxComponent bbox = getEntity().getBoundingBoxComponent(); FXGL.getApp() .getGameWorld() .getEntitiesInRange(bbox.range(radius, radius)) .stream() .filter(e -> e.isType(GameTypes.BRICK)) .forEach(e -> { FXGL.<GameApp>getAppCast().onWallDestroyed(e); e.removeFromWorld(); }); getEntity().removeFromWorld(); } }
true
11ed9f0ee1a22668d8d8e318689cfc40243de9b7
Java
nikhilthota7/RestApiExtentReport
/CucumberReportingApi2/src/test/java/com/cts/StepDefinition/DeleteRequest.java
UTF-8
1,317
2.25
2
[]
no_license
package com.cts.StepDefinition; import cucumber.api.Scenario; import cucumber.api.java.Before; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import io.restassured.response.Response; import io.restassured.response.ValidatableResponse; import io.restassured.specification.RequestSpecification; import static io.restassured.RestAssured.given; public class DeleteRequest { String baseUri="https://reqres.in/"; RequestSpecification _REQS_SPEC; Response _RESP; ValidatableResponse _VALIDATABLE_RESP; Scenario scn; @Before public void BeforeHook(Scenario s) { this.scn = s; } @Given("I have end point API URI") public void i_have_end_point_API_URI() { _REQS_SPEC =given().baseUri(baseUri); scn.write("Base uri is" + baseUri); } @When("I enter uri and submit") public void i_enter_uri_and_submit() { _RESP=_REQS_SPEC.delete("/api/users/2"); scn.write("Uri entered is"+_RESP.asString()); } @Then("I should get {int} as response code") public void i_should_get_as_response_code(Integer int1) { _VALIDATABLE_RESP=_RESP.then().log().all(); _VALIDATABLE_RESP.assertThat().statusCode(int1); scn.write("Status code from response is "+_RESP.getStatusCode()); } }
true
31c7d11ac582c4aaf8c31ef2979401d39f1e13a8
Java
ryan4fun/kmmk
/kmmk/src/com/gps/Message.java
UTF-8
114
1.898438
2
[]
no_license
package com.gps; public class Message extends Exception { public Message(String msg){ super(msg); } }
true
5f57e74ecc13f16153b45212ac14c1de84d6d855
Java
ZinKoWinn/Hateoas-Test
/src/main/java/com/example/hateoastest/ds/Address.java
UTF-8
2,212
2.484375
2
[]
no_license
package com.example.hateoastest.ds; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import javax.persistence.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; import javax.validation.constraints.Positive; import javax.validation.constraints.Size; import static javax.persistence.FetchType.EAGER; import static javax.persistence.GenerationType.IDENTITY; @Entity @Getter @Setter @AllArgsConstructor public class Address { @Id @GeneratedValue(strategy = IDENTITY) private Integer id; @NotBlank(message = "Address name cannot be empty") private String addressName; @Positive(message = "Street Number cannot be empty") private Integer streetNumber; @NotBlank(message = "First name cannot be empty") @Pattern(regexp = "[A-Za-z-' ]*", message = "Street name contains illegal characters") private String streetName; private Integer aptNumber; @NotBlank(message = "City cannot be empty") @Pattern(regexp = "[A-Za-z-' ]*", message = "City contains illegal characters") private String city; @NotBlank(message = "State cannot be empty") @Size(min = 2, max = 2, message = "State needs to be 2 letter code") @Pattern(regexp = "[A-Z]*", message = "State contains illegal characters") private String state; @NotBlank(message = "Zip Code cannot be empty") @Pattern(regexp = "[0-9]*", message = "Zip Code contains illegal characters") private String zipCode; @ManyToOne(fetch = EAGER) @JoinColumn(name = "customer_id") @JsonIgnore private Customer customer; @SuppressWarnings("unused") public Address() { } @Override public String toString() { return "Address{" + "id=" + id + ", addressName='" + addressName + '\'' + ", streetNumber=" + streetNumber + ", streetName='" + streetName + '\'' + ", aptNumber=" + aptNumber + ", city='" + city + '\'' + ", state='" + state + '\'' + ", zipCode='" + zipCode + '\'' + '}'; } }
true
adfabe2cf7d97d94d139e7895dc75e9d753df641
Java
FredyKcrez/JAVA
/G9_Ejr1_CuentaClaseAbstracta/src/ejercicios/clasesabstractas/Ahorro.java
UTF-8
871
2.984375
3
[ "Apache-2.0" ]
permissive
package ejercicios.clasesabstractas; /** * @date 04/07/2018 * @author Fredy Kcrez */ public class Ahorro extends Cuenta { protected double tasaInteres; public Ahorro(int numeroCuenta, double ti) { super( numeroCuenta, "Ahorro" ); this.setTasaInteres( ti ); } @Override public int getNumeroCuenta() { return this.numeroCuenta; } @Override public double getSaldo() { return this.saldo; } /** * @return the tasaInteres */ public double getTasaInteres() { return tasaInteres; } /** * @param tasaInteres the tasaInteres to set */ public void setTasaInteres(double tasaInteres) { this.tasaInteres = tasaInteres; } @Override public String getTipoCuenta() { return this.tipoC; } }
true
3125bcc95550476bdcd33287f4fe6d99a476ae35
Java
kaushiknsanji/firestore-friendly-eats-android
/app/src/main/java/com/google/firebase/example/fireeats/RestaurantDetailActivity.java
UTF-8
9,113
1.882813
2
[ "CC-BY-4.0", "Apache-2.0", "LicenseRef-scancode-other-permissive" ]
permissive
/* * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.example.fireeats; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import com.google.android.gms.tasks.Task; import com.google.android.material.snackbar.Snackbar; import com.google.firebase.example.fireeats.adapter.RatingAdapter; import com.google.firebase.example.fireeats.databinding.ActivityRestaurantDetailBinding; import com.google.firebase.example.fireeats.model.Rating; import com.google.firebase.example.fireeats.model.Restaurant; import com.google.firebase.example.fireeats.util.FirebaseUtil; import com.google.firebase.example.fireeats.util.GlideApp; import com.google.firebase.example.fireeats.util.RestaurantUtil; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.ListenerRegistration; import com.google.firebase.firestore.Query; import java.util.Objects; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; public class RestaurantDetailActivity extends AppCompatActivity implements View.OnClickListener, EventListener<DocumentSnapshot>, RatingDialogFragment.RatingListener { public static final String KEY_RESTAURANT_ID = "key_restaurant_id"; private static final String TAG = "RestaurantDetail"; private static final int LIMIT = 50; private ActivityRestaurantDetailBinding mBinding; private RatingDialogFragment mRatingDialog; private FirebaseFirestore mFirestore; private DocumentReference mRestaurantRef; private ListenerRegistration mRestaurantRegistration; private RatingAdapter mRatingAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Inflate with ViewBinding mBinding = ActivityRestaurantDetailBinding.inflate(getLayoutInflater()); // Set the root view from ViewBinding instance setContentView(mBinding.getRoot()); mBinding.restaurantButtonBack.setOnClickListener(this); mBinding.fabShowRatingDialog.setOnClickListener(this); // Get restaurant ID from extras String restaurantId = getIntent().getExtras().getString(KEY_RESTAURANT_ID); if (restaurantId == null) { throw new IllegalArgumentException("Must pass extra " + KEY_RESTAURANT_ID); } // Initialize Firestore mFirestore = FirebaseUtil.getFirestore(); // Get reference to the restaurant mRestaurantRef = mFirestore.collection(Restaurant.COLLECTION).document(restaurantId); // Get ratings Query ratingsQuery = mRestaurantRef .collection(Rating.COLLECTION) .orderBy(Rating.FIELD_TIMESTAMP, Query.Direction.DESCENDING) .limit(LIMIT); // RecyclerView mRatingAdapter = new RatingAdapter(ratingsQuery) { @Override protected void onDataChanged() { if (getItemCount() == 0) { mBinding.recyclerRatings.setVisibility(View.GONE); mBinding.viewEmptyRatings.setVisibility(View.VISIBLE); } else { mBinding.recyclerRatings.setVisibility(View.VISIBLE); mBinding.viewEmptyRatings.setVisibility(View.GONE); } } }; mBinding.recyclerRatings.setLayoutManager(new LinearLayoutManager(this)); mBinding.recyclerRatings.setAdapter(mRatingAdapter); mRatingDialog = new RatingDialogFragment(); } @Override public void onStart() { super.onStart(); mRatingAdapter.startListening(); mRestaurantRegistration = mRestaurantRef.addSnapshotListener(this); } @Override public void onStop() { super.onStop(); mRatingAdapter.stopListening(); if (mRestaurantRegistration != null) { mRestaurantRegistration.remove(); mRestaurantRegistration = null; } } @Override public void onClick(View view) { if (view.getId() == mBinding.restaurantButtonBack.getId()) { onBackArrowClicked(view); } else if (view.getId() == mBinding.fabShowRatingDialog.getId()) { onAddRatingClicked(view); } } private Task<Void> addRating(final DocumentReference restaurantRef, final Rating rating) { // Create a reference to the new Rating document, for use inside the transaction final DocumentReference ratingRef = restaurantRef.collection(Rating.COLLECTION).document(); // In a transaction, add the new rating and update aggregate totals return mFirestore.runTransaction(transaction -> { // Read current restaurant document reference and convert to Restaurant POJO Restaurant restaurant = Objects.requireNonNull( transaction.get(restaurantRef).toObject(Restaurant.class) ); // Compute new number of ratings int newNumRatings = restaurant.getNumRatings() + 1; // Compute new average rating double oldRatingTotal = restaurant.getAvgRating() * restaurant.getNumRatings(); double newAvgRating = (rating.getRating() + oldRatingTotal) / newNumRatings; // Set new aggregate on Restaurant POJO restaurant.setNumRatings(newNumRatings); restaurant.setAvgRating(newAvgRating); // Commit Restaurant update and its Rating to Firestore transaction.set(restaurantRef, restaurant); transaction.set(ratingRef, rating); return null; }); } /** * Listener for the Restaurant document ({@link #mRestaurantRef}). */ @Override public void onEvent(DocumentSnapshot snapshot, FirebaseFirestoreException e) { if (e != null) { Log.w(TAG, "restaurant:onEvent", e); return; } onRestaurantLoaded(snapshot.toObject(Restaurant.class)); } private void onRestaurantLoaded(@Nullable Restaurant restaurant) { Objects.requireNonNull(restaurant); mBinding.restaurantName.setText(restaurant.getName()); mBinding.restaurantRating.setRating((float) restaurant.getAvgRating()); mBinding.restaurantNumRatings.setText(getString(R.string.fmt_num_ratings, restaurant.getNumRatings())); mBinding.restaurantCity.setText(restaurant.getCity()); mBinding.restaurantCategory.setText(restaurant.getCategory()); mBinding.restaurantPrice.setText(RestaurantUtil.getPriceString(restaurant)); // Background image GlideApp.with(mBinding.restaurantImage.getContext()) .load(restaurant.getPhoto()) .into(mBinding.restaurantImage); } public void onBackArrowClicked(View view) { onBackPressed(); } public void onAddRatingClicked(View view) { mRatingDialog.show(getSupportFragmentManager(), RatingDialogFragment.TAG); } @Override public void onRating(Rating rating) { // In a transaction, add the new rating and update the aggregate totals addRating(mRestaurantRef, rating) .addOnSuccessListener(this, aVoid -> { Log.d(TAG, "Rating added"); // Hide keyboard and scroll to top hideKeyboard(); mBinding.recyclerRatings.smoothScrollToPosition(0); }) .addOnFailureListener(this, e -> { Log.w(TAG, "Add rating failed", e); // Show failure message and hide keyboard hideKeyboard(); Snackbar.make(findViewById(android.R.id.content), "Failed to add rating", Snackbar.LENGTH_SHORT).show(); }); } private void hideKeyboard() { View view = getCurrentFocus(); if (view != null) { ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(view.getWindowToken(), 0); } } }
true
b7e70609db9a0c35b37ffc677f549d3772f494c0
Java
brianmontierth/Scheduler
/app/src/main/java/com/wgu/brian/scheduler/database/TermDao.java
UTF-8
852
2.15625
2
[]
no_license
package com.wgu.brian.scheduler.database; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; import android.arch.persistence.room.OnConflictStrategy; import android.arch.persistence.room.Query; import com.wgu.brian.scheduler.database.entities.Term; import java.util.List; @Dao public interface TermDao { @Query("SELECT * FROM Term ORDER BY id") List<Term> getAllTerms(); @Insert(onConflict = OnConflictStrategy.REPLACE) long[] insertAll(Term... terms); @Insert(onConflict = OnConflictStrategy.REPLACE) long[] insertAll(List<Term> terms); @Insert(onConflict = OnConflictStrategy.REPLACE) long insert(Term term); @Query("SELECT * FROM Term WHERE id = :id") Term findById(int id); @Delete void delete(Term term); }
true
0457eb6b3c324271d050f88bc68cd681343eba04
Java
utopia-group/dynamite
/src/dynamite/util/FileUtils.java
UTF-8
4,492
3.265625
3
[]
no_license
package dynamite.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** * Utility functions about File IO. */ public class FileUtils { /** * Read all lines from a file. * * @param filepath path to the file * @return a list of string where each string is a line in the file */ public static List<String> readLinesFromFile(String filepath) { try (BufferedReader reader = new BufferedReader(new FileReader(filepath))) { List<String> lines = new ArrayList<>(); String line; while ((line = reader.readLine()) != null) { lines.add(line); } return lines; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("File reading error"); } } /** * Read a file as a string. * * @param filepath path to the file * @return file content as a string */ public static String readFromFile(String filepath) { List<String> lines = readLinesFromFile(filepath); return lines.stream().collect(Collectors.joining(System.lineSeparator())); } /** * Write a list of strings to a file. * * @param filepath path to the file * @param lines a list of strings */ public static void writeLinesToFile(String filepath, List<String> lines) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(filepath))) { for (String line : lines) { writer.write(line); writer.newLine(); } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("File writing error"); } } /** * Write a string to a file. * * @param filepath path to the file * @param content the string */ public static void writeStringToFile(String filepath, String content) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(filepath))) { writer.write(content); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("File writing error"); } } /** * Create a directory and its parent directories. * * @param path the path to the directory */ public static void createDirectory(Path path) { try { Files.createDirectories(path); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(String.format("Cannot create dir: %s", path.toAbsolutePath())); } } /** * Delete a directory and all files inside. * * @param path the path to the directory */ public static void deleteDirAndFiles(Path path) { try { Files.walk(path) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(String.format("Deletion error for %s", path.toAbsolutePath())); } } /** * Get the file name without extension. * * @param fileName the provided file name * @return the file name without extension */ public static String removeExtension(String fileName) { int pos = fileName.lastIndexOf("."); if (pos > 0 && pos < (fileName.length() - 1)) { // If '.' is not the first or last character. fileName = fileName.substring(0, pos); } return fileName; } /** * Get the extension of a file. * * @param filepath path to the provided file * @return the file extension */ public static String getFileExtension(String filepath) { int pos = filepath.lastIndexOf('.'); if (pos < 0) { throw new IllegalArgumentException("Cannot find extension for file: " + filepath); } return filepath.substring(pos + 1); } public static String getRelationName(String filepath) { File f = new File(filepath); return removeExtension(f.getName()); } }
true
aa75ee9ad5bc037b56a69fcb9fdcf83ee8e8542d
Java
DmitryPronin/JAVA_IT_PARK_3
/test/myproject/src/main/java/ru/itpark/probro/services/FilesService.java
UTF-8
386
1.875
2
[]
no_license
package ru.itpark.probro.services; import org.springframework.security.core.Authentication; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; public interface FilesService { String save(Authentication authentication, MultipartFile multipartFile); void writeFileTOResponse(String fileName, HttpServletResponse response); }
true
521531dbdfc3f26e2f53f01add5868fb123c1476
Java
jack921/Weather
/app/src/main/java/com/jack/weather/app/WeatherApplication.java
UTF-8
2,298
2.171875
2
[]
no_license
package com.jack.weather.app; /* _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' | | \ .-\__ `-` ___/-. / ___`. .' /--.--\ `. . __ ."" '< `.___\_<|>_/___.' >'"". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `-. \_ __\ /__ _/ .-` / / ======`-.____`-.___\_____/___.-`____.-'====== `=---=' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 佛祖保佑 永无BUG */ import android.app.Application; import android.content.Context; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.jack.weather.util.LocalData; import com.jack.weather.util.LogUtil; import com.jack.weather.util.Util; /** * Created by Jack on 2016/6/25. */ public class WeatherApplication extends Application{ private static Context context=null; public LocationClient mLocationClient = null; public BDLocationListener myListener = null; public static String nowCity=""; public boolean CityFirst=true; public static String showCity=""; @Override public void onCreate() { super.onCreate(); myListener = new WeatherLocationListener(); mLocationClient=new LocationClient(getApplicationContext()); mLocationClient.setLocOption(Util.initLocationOptions()); mLocationClient.registerLocationListener(myListener); mLocationClient.start(); context=getApplicationContext(); initCity(); } //获取提醒城市 public void initCity(){ showCity = LocalData.getSharedPreferencesData(this,"nowcity","city"); if(showCity.equals("")){ showCity=nowCity; } } public static Context getWeatherApplication(){ if(context!=null){ return context; }else{ return null; } } //回调接口回去当前位置 public class WeatherLocationListener implements BDLocationListener { @Override public void onReceiveLocation(BDLocation bdLocation) { if(CityFirst){ CityFirst=false; nowCity=bdLocation.getCity(); } } } }
true
ef2bc0a81d725c7ad64a6151b1855fa99cfb8571
Java
wso2/micro-integrator
/components/org.wso2.micro.integrator.ndatasource.core/src/main/java/org/wso2/micro/integrator/ndatasource/core/services/WSDataSourceMetaInfo.java
UTF-8
3,884
1.953125
2
[ "Apache-2.0" ]
permissive
/** * Copyright (c) 2012, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.micro.integrator.ndatasource.core.services; import org.w3c.dom.Element; import org.wso2.micro.integrator.ndatasource.core.DataSourceMetaInfo; import org.wso2.micro.integrator.ndatasource.core.DataSourceMetaInfo.DataSourceDefinition; import org.wso2.micro.integrator.ndatasource.core.JNDIConfig; import org.wso2.micro.integrator.ndatasource.core.utils.DataSourceUtils; /** * This is a bean class to contain the DataSourceMetaInfo in a web services context. */ public class WSDataSourceMetaInfo { private String name; private String description; private JNDIConfig jndiConfig; private boolean system; private WSDataSourceDefinition definition; public WSDataSourceMetaInfo() { } public WSDataSourceMetaInfo(DataSourceMetaInfo metaInfo) { this.name = metaInfo.getName(); this.description = metaInfo.getDescription(); this.jndiConfig = metaInfo.getJndiConfig(); this.system = !metaInfo.isPersistable(); this.definition = new WSDataSourceDefinition(metaInfo.getDefinition()); } public DataSourceMetaInfo extractDataSourceMetaInfo() { DataSourceMetaInfo dsmInfo = new DataSourceMetaInfo(); dsmInfo.setName(this.getName()); dsmInfo.setDescription(this.getDescription()); dsmInfo.setSystem(this.isSystem()); dsmInfo.setJndiConfig(this.getJndiConfig()); dsmInfo.setDefinition(this.getDefinition().extractDataSourceDefinition()); return dsmInfo; } public boolean isSystem() { return system; } public void setSystem(boolean system) { this.system = system; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public JNDIConfig getJndiConfig() { return jndiConfig; } public void setJndiConfig(JNDIConfig jndiConfig) { this.jndiConfig = jndiConfig; } public WSDataSourceDefinition getDefinition() { return definition; } public void setDefinition(WSDataSourceDefinition definition) { this.definition = definition; } /** * This is a bean class to contain the DataSourceDefinition in a web services context. */ public static class WSDataSourceDefinition { private String type; private String dsXMLConfiguration; public WSDataSourceDefinition() { } public WSDataSourceDefinition(DataSourceDefinition dsDef) { this.type = dsDef.getType(); this.dsXMLConfiguration = DataSourceUtils.elementToString((Element) dsDef.getDsXMLConfiguration()); } public DataSourceDefinition extractDataSourceDefinition() { DataSourceDefinition dsDef = new DataSourceDefinition(); dsDef.setType(this.getType()); dsDef.setDsXMLConfiguration(DataSourceUtils.stringToElement( this.getDsXMLConfiguration())); return dsDef; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDsXMLConfiguration() { return dsXMLConfiguration; } public void setDsXMLConfiguration(String dsXMLConfiguration) { this.dsXMLConfiguration = dsXMLConfiguration; } } }
true
097652846a47385e400b2d35c054e5dba05a1612
Java
javargas1098/SuperEasy
/src/main/java/edu/eci/arsw/model/Trueque.java
UTF-8
258
2.265625
2
[]
no_license
package edu.eci.arsw.model; public class Trueque extends TipoDePago { Item item; TipoDePago tipoDePago; public Trueque() { } public Trueque(Item item, TipoDePago tipoDePago) { super(); this.item = item; this.tipoDePago = tipoDePago; } }
true
a9ec49cc8f8119150dd232b9cde7c978220b57d7
Java
MasterSchool4031/SchoolUserInterface
/src/main/java/school/client/commons/Lesson.java
UTF-8
678
2.703125
3
[]
no_license
package school.client.commons; import java.net.URL; /** * un Cours est définit par un nom et un contenu. * * <pre> * Propriétés * - nom :String // le nom du cours * - contenu :URL // le contenu du cours * * Contraintes sur les Propriétés * Le contenu et l'intitulé ne peuvent pas être null. * </pre> * * @author Yannick Boogaerts pour STE-Formations */ public interface Lesson { /** * Renvoit le nom du cours. * * @return le nom du cours. */ public String getName(); /** * Renvoit le dossier de cours. * * @return le dossier de cours. */ public URL getContent(); }
true
a753a177d77324aa0e4a6094a0de072a73f667be
Java
tadakazu1972/RedSword
/app/src/main/java/tadakazu1972/redsword/Shot.java
UTF-8
2,720
2.765625
3
[]
no_license
package tadakazu1972.redsword; /** * Created by tadakazu on 2015/09/22. */ public class Shot { public float x, y; public float wx, wy; public float vx, vy; public float l, r, t, b; public int base_index; //アニメーション基底 0:右向き 2:左向き public int index; public int visible; public Shot(MyChara m) { x = m.x + 24.0f; //最初の剣はこの位置 y = m.y; wx = m.wx + 24.0f; wy = m.wy; vx = 0.0f; vy = 0.0f; l = wx; r = wx + 7.0f; //最初の剣の当たり判定 t = wy; b = wy + 23.0f; base_index=0; index = 0; visible = 0; } public void Reset(MyChara m) { x = m.x + 24.0f; y = m.y; wx = m.wx + 24.0f; wy = m.wy; vx = 0.0f; vy = 0.0f; l = wx; r = wx + 7.0f; t = wy; b = wy + 23.0f; base_index=0; index = 0; visible = 0; //ステージ数で増えるときには見えるようにセット } public void move(MyChara m, MainActivity ac, Map map) { //発射されていたら飛んでいく if (visible!=0) { vy = -8.0f; vx = 0.0f; //当たり判定用マップ座標算出 int x1 = (int) (wx + vx) / 32; if (x1 < 0) x1 = 0; if (x1 > 9) x1 = 9; int y1 = (int) (wy + vy) / 32; if (y1 < 0) y1 = 0; if (y1 > 114) y1 = 114; int x2 = (int) (wx + 7.0f + vx) / 32; if (x2 > 9) x2 = 9; if (x2 < 0) x2 = 0; //int y2 = (int) (wy + 23.0f + vy) / 32; if (y2 > 114) y2 = 114; if (y2 < 0) y2 = 0; //カベ判定 if (map.MAP[ac.stage][y1][x1] > 0 || map.MAP[ac.stage][y1][x2] > 0) { vx = 0.0f; vy = 0.0f; Reset(m); } //ワールド座標更新 wx = wx + vx; if (wx < 0.0f) wx = 0.0f; if (wx > 9 * 32.0f) wx = 9 * 32.0f; wy = wy + vy; if (wy < -32.0f) wy=0.0f; if (wy > 114 * 32.0f) wy = 114 * 32.0f; //ワールド当たり判定移動 l = wx + vx; r = wx + 7.0f + vx; t = wy + vy; b = wy + 23.0f + vy; //座標更新 x = x + vx; y = y + vy; //アニメーションインデックス変更処理 index++; if (index > 19) index = 0; } else { //発射されていないなら、主人公の動きと合わせる x = m.x + 24.0f; y = m.y; wx = m.wx + 24.0f; wy = m.wy; } } }
true
321281759523a5ec7c01de47d4fa9d7ccad06c5e
Java
BeCandid/JaDX
/java/defpackage/xa.java
UTF-8
2,651
1.789063
2
[]
no_license
package defpackage; import android.os.Bundle; import com.facebook.FacebookException; import com.facebook.share.internal.ShareFeedContent; import com.facebook.share.model.ShareContent; import com.facebook.share.model.ShareHashtag; import com.facebook.share.model.ShareLinkContent; import com.facebook.share.model.ShareOpenGraphContent; import org.json.JSONObject; /* compiled from: WebDialogParameters */ public class xa { public static Bundle a(ShareLinkContent shareLinkContent) { Bundle params = xa.a((ShareContent) shareLinkContent); we.a(params, "href", shareLinkContent.h()); we.a(params, "quote", shareLinkContent.d()); return params; } public static Bundle a(ShareOpenGraphContent shareOpenGraphContent) { Bundle params = xa.a((ShareContent) shareOpenGraphContent); we.a(params, "action_type", shareOpenGraphContent.a().a()); try { JSONObject ogJSON = wz.a(wz.a(shareOpenGraphContent), false); if (ogJSON != null) { we.a(params, "action_properties", ogJSON.toString()); } return params; } catch (Throwable e) { throw new FacebookException("Unable to serialize the ShareOpenGraphContent to JSON", e); } } public static Bundle a(ShareContent shareContent) { Bundle params = new Bundle(); ShareHashtag shareHashtag = shareContent.l(); if (shareHashtag != null) { we.a(params, "hashtag", shareHashtag.a()); } return params; } public static Bundle b(ShareLinkContent shareLinkContent) { Bundle webParams = new Bundle(); we.a(webParams, "name", shareLinkContent.b()); we.a(webParams, "description", shareLinkContent.a()); we.a(webParams, "link", we.a(shareLinkContent.h())); we.a(webParams, "picture", we.a(shareLinkContent.c())); we.a(webParams, "quote", shareLinkContent.d()); if (shareLinkContent.l() != null) { we.a(webParams, "hashtag", shareLinkContent.l().a()); } return webParams; } public static Bundle a(ShareFeedContent shareFeedContent) { Bundle webParams = new Bundle(); we.a(webParams, "to", shareFeedContent.a()); we.a(webParams, "link", shareFeedContent.b()); we.a(webParams, "picture", shareFeedContent.f()); we.a(webParams, "source", shareFeedContent.g()); we.a(webParams, "name", shareFeedContent.c()); we.a(webParams, "caption", shareFeedContent.d()); we.a(webParams, "description", shareFeedContent.e()); return webParams; } }
true
4abea0825b3f6f3101d378430b6cb17c3ca21dd9
Java
744719042/misc2
/app/src/main/java/com/example/misc2/BugFixActivity.java
UTF-8
4,947
2.390625
2
[]
no_license
package com.example.misc2; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.example.misc2.utils.ExceptionUtils; import java.io.File; import java.lang.reflect.Array; import java.lang.reflect.Field; import dalvik.system.BaseDexClassLoader; import dalvik.system.DexClassLoader; import dalvik.system.PathClassLoader; public class BugFixActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG = "BugFixActivity"; private Button invokeBug; private Button invokeFix; private Button showLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bug_fix); invokeBug = findViewById(R.id.invokeError); invokeFix = findViewById(R.id.invokeFix); showLoader = findViewById(R.id.showLoader); invokeBug.setOnClickListener(this); invokeFix.setOnClickListener(this); showLoader.setOnClickListener(this); } @Override public void onClick(View v) { if (v == invokeBug) { try { ExceptionUtils.parseException(null); } catch (Exception e) { Toast.makeText(this, "调用BUG代码失败", Toast.LENGTH_SHORT).show(); return; } Toast.makeText(this, "调用修复BUG代码成功", Toast.LENGTH_SHORT).show(); } else if (v == invokeFix) { if (loadFixDex()) { Toast.makeText(this, "修复BUG成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "修复BUG失败", Toast.LENGTH_SHORT).show(); } } else if (v == showLoader) { ClassLoader classLoader = getClassLoader(); Log.d(TAG, classLoader.toString()); while (classLoader != null) { classLoader = classLoader.getParent(); if (classLoader != null) { Log.d(TAG, classLoader.toString()); } } } } private boolean loadFixDex() { String dexPath = Environment.getExternalStorageDirectory() + File.separator + "bugfix.dex"; String dexOutput = getCacheDir() + File.separator + "DEX"; File file = new File(dexOutput); if (!file.exists()) file.mkdirs(); // 从bugfix.dex文件加载修复bug的dex文件 DexClassLoader dexClassLoader = new DexClassLoader(dexPath, dexOutput, null, getClassLoader()); PathClassLoader pathClassLoader = (PathClassLoader) getClassLoader(); try { // 反射获取pathList成员变量Field Field dexPathList = BaseDexClassLoader.class.getDeclaredField("pathList"); dexPathList.setAccessible(true); // 现获取两个类加载器内部的pathList成员变量 Object pathList = dexPathList.get(pathClassLoader); Object fixPathList = dexPathList.get(dexClassLoader); // 反射获取DexPathList类的dexElements成员变量Field Field dexElements = pathList.getClass().getDeclaredField("dexElements"); dexElements.setAccessible(true); // 反射获取pathList对象内部的dexElements成员变量 Object originDexElements = dexElements.get(pathList); Object fixDexElements = dexElements.get(fixPathList); // 使用反射获取两个dexElements的长度 int originLength = Array.getLength(originDexElements); int fixLength = Array.getLength(fixDexElements); int totalLength = originLength + fixLength; // 获取dexElements数组的元素类型 Class<?> componentClass = originDexElements.getClass().getComponentType(); // 将修复dexElements的元素放在前面,原始dexElements放到后面,这样就保证加载类的时候优先查找修复类 Object[] elements = (Object[]) Array.newInstance(componentClass, totalLength); for (int i = 0; i < totalLength; i++) { if (i < fixLength) { elements[i] = Array.get(fixDexElements, i); } else { elements[i] = Array.get(originDexElements, i - fixLength); } } // 将新生成的dexElements数组注入到PathClassLoader内部, // 这样App查找类就会先从fixdex查找,在从App安装的dex里查找 dexElements.set(pathList, elements); return true; } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return false; } }
true
4f5607870c0a3cdd143af2f805f2b0fefc57d4e1
Java
Phenix-Collection/Android-6.0-packages
/code/apps/FileExplorer/src/com/sprd/fileexplorer/util/NotifyManager.java
UTF-8
1,751
2.734375
3
[]
no_license
package com.sprd.fileexplorer.util; import android.content.Context; import android.os.Handler; import android.widget.Toast; public class NotifyManager { private static final int TOAST_LONG_DELAY = 3500; private static final int TOAST_SHORT_DELAY = 2000; private static NotifyManager mManager; private Context mContext; private Toast mToast; private Handler mMainThreadHandler; private NotifyManager(Context context) { mContext = context; mMainThreadHandler = new Handler(mContext.getMainLooper()); } public static void init(Context context) { if (context == null) { throw new NullPointerException("context == null"); } mManager = new NotifyManager(context); } public static NotifyManager getInstance() { return mManager; } private Runnable cancelToast = new Runnable() { @Override public void run() { mToast = null; } }; public void showToast(String msg) { //Should get text from toast instead of last message. showToast(msg, Toast.LENGTH_SHORT); } public void showToast(String msg, int duration) { if (msg == null) { throw new NullPointerException("Toast to show what?"); } int delay = TOAST_SHORT_DELAY; if(duration == Toast.LENGTH_LONG) { delay = TOAST_LONG_DELAY; } if (mToast != null) { mToast.setText(msg); } else { mMainThreadHandler.removeCallbacks(cancelToast); mToast = Toast.makeText(mContext, msg, duration); mMainThreadHandler.postDelayed(cancelToast, delay); mToast.show(); } } }
true
b351ea4c3f930002792a6b353f15b54dd0371df4
Java
kalia305/ServletProgram
/RaliwayTicketReservation_LayeredApllication/src/kcp/servlet/bo/CustomerBO.java
UTF-8
1,305
2.3125
2
[]
no_license
package kcp.servlet.bo; public class CustomerBO { long PNRno; double price, distance, discountAmount,totalPrice; public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } String customerName, source, destination; public long getPNRno() { return PNRno; } public void setPNRno(long pNRno) { PNRno = pNRno; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public double getDistance() { return distance; } public void setDistance(double distance) { this.distance = distance; } public double getDiscountAmount() { return discountAmount; } public void setDiscountAmount(double discountAmount) { this.discountAmount = discountAmount; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getSource() { return source; } public void setSource(String source) { this.source = source; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } }
true
310a7c900a33d088ebbf36014e712baee965384f
Java
iDeliver1/iceHrmObjectModel
/IceHrmObjectModel/src/test/java/testcase/TC001_iceHrmAttendenceTest.java
UTF-8
4,250
2.328125
2
[]
no_license
package testcase; import org.testng.Assert; import org.testng.annotations.Test; import base.TestBase; import pages.AttendancePage; import pages.HomePage; import pages.LeavePage; import pages.LoginPage; public class TC001_iceHrmAttendenceTest extends TestBase{ <<<<<<< HEAD LoginPage pgLogin; HomePage pgHome; AttendancePage pgAtten; LeavePage pgLeave; @Test public void icehrmAttendenceTest() throws Throwable { //Login pgLogin = new LoginPage(driver); pgHome = pgLogin.userLogin(prop.getProperty("username"),prop.getProperty("password")); try { Assert.assertNotNull(pgHome); reporting("Login Validation", "User should log in", "User Logged in Successfully", "Pass"); }catch(AssertionError E) { reporting("Login Validation", "User should log in", "User Login Failed", "Fail"); } //Punch In pgAtten = (AttendancePage) pgHome.clickOnTab("Attendance"); checkBlnMethod = pgAtten.icehrmAttendancePage("IN",0); try { Assert.assertEquals(true, checkBlnMethod); reporting("Punch System Validation", "User should Punch In", "User Punch In Successful", "Pass"); }catch(AssertionError E) { reporting("Punch System Validation", "User should Punch In", "User punch In Failed", "Fail"); } //Apply for Leave pgLeave = (LeavePage) pgHome.clickOnTab("Leave"); pgLeave.applyForLeave("Causal Leave"); checkBlnMethod = pgLeave.checkEntryTable(); try { Assert.assertEquals(true, checkBlnMethod); //fail reporting("Leave Validation", "User must be able to apply for leave ", "User failed to applied for leave", "Fail"); }catch(AssertionError E) { //pass reporting("Leave Validation", "User must be able to apply for leave ", "User Successfully applied for leave", "Pass"); } //Punch Out pgHome.homeBtn.click(); pgHome.attendanceTab.click(); checkBlnMethod = pgAtten.icehrmAttendancePage("OUT",1); try { Assert.assertEquals(true, checkBlnMethod); reporting("Punch System Validation", "User should Punch Out", "User Punch Out Successful", "Pass"); }catch(AssertionError E) { reporting("Punch System Validation", "User should Punch Out", "User Punch Out Failed", "Fail"); ======= boolean checkblnmethod; LoginPage pglogin; HomePage pghome; AttendancePage pgAtten; LeavePage pgleave; @Test public void icehrmAttendenceTest() throws Throwable { //Login pglogin = new LoginPage(driver); pghome = pglogin.userLogin(prop.getProperty("username"),prop.getProperty("password")); try { Assert.assertNotNull(pghome); Reporting("Login Validation", "User should log in", "User log in Successful", "Pass"); }catch(AssertionError E) { Reporting("Login Validation", "User should log in", "User log in Unsuccessful", "Fail"); } //Punch In pgAtten = (AttendancePage) pghome.clickOnTab("Attendance"); checkBlnMethod = pgAtten.icehrmAttendancePage("IN",0); try { Assert.assertEquals(true, checkBlnMethod); Reporting("Punch System Validation", "User should punch in", "User punch in Successful", "Pass"); }catch(AssertionError E) { Reporting("Punch System Validation", "User should punch in", "User punch in Unsuccessful", "Fail"); } //Apply for Leave pgleave = (LeavePage) pghome.clickOnTab("Leave"); pgleave.applyForLeave("Causal Leave"); checkBlnMethod = pgleave.checkEntryTable(); try { Assert.assertEquals(true, checkBlnMethod); //fail Reporting("Leave Validation", "User must be able to apply for leave ", "User unable to applied for leave", "Fail"); }catch(AssertionError E) { //pass Reporting("Leave Validation", "User must be able to apply for leave ", "User Successfully applied for leave", "Pass"); } //Punch Out pghome.homeBtn.click(); pghome.attendanceTab.click(); checkBlnMethod = pgAtten.icehrmAttendancePage("OUT",1); try { Assert.assertEquals(true, checkBlnMethod); Reporting("Punch System Validation", "User should punch out", "User punch out Successful", "Pass"); }catch(AssertionError E) { Reporting("Punch System Validation", "User should log in", "User punch out Unsuccessful", "Fail"); >>>>>>> branch 'master' of https://github.com/iDeliver1/iceHrmObjectModel.git } } }
true
dfa5bfaf30e8caee48359e698149d985e1b730de
Java
xbhou/study_test
/src/main/java/cn/study/jdk/IDCard/IDCardComplete.java
UTF-8
2,404
2.953125
3
[]
no_license
/** * @author xiaobin.hou * @create 2018-07-02 15:15 **/ package cn.study.jdk.IDCard; import cn.study.jdk.util.DateUtils; import cn.study.jdk.util.IdcardValidator; import java.util.Calendar; public class IDCardComplete { public static void main(String[] args) { IdcardValidator validator = new IdcardValidator(); String name = "付瑜"; String idCard = "14272319880817"; String correct = null; String idCardStart = idCard.substring(0, 10); String idCardEnd = idCard.substring(10); String idCardYear = idCard.substring(6,10); int year = Integer.parseInt(idCardYear); Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, year); // 设置年份 StringBuffer idCardBf = new StringBuffer(); for (int month = 1; month <= 12; month++) { idCardBf.setLength(0); idCardBf.append(idCardStart); StringBuffer monthBf = new StringBuffer(); if (month < 10){ monthBf.append("0"); } monthBf.append(month); idCardBf.append(monthBf); int maxDay = DateUtils.getMaxDayOfMonth(year,month); StringBuffer dayBf = new StringBuffer(); for (int day = 1; day <= maxDay; day++) { StringBuffer idCardBakBf = new StringBuffer(idCardBf); dayBf.setLength(0); if (day < 10){ dayBf.append("0"); } dayBf.append(day); idCardBakBf.append(dayBf); idCardBakBf.append(idCardEnd); boolean result = validator.isValidatedAllIdcard(idCardBakBf.toString()); if (result){ correct = idCardBakBf.toString(); break; } } } System.out.println(correct + "\t" + name); // Calendar c = Calendar.getInstance(); // c.set(Calendar.YEAR, 2010); // 2010年 // c.set(Calendar.MONTH, 1); // 6 月 // System.out.println("------------" + c.get(Calendar.YEAR) + "年" + (c.get(Calendar.MONTH) + 1) + "月的天数和周数-------------"); // System.out.println("天数:" + c.getActualMaximum(Calendar.DAY_OF_MONTH)); // System.out.println("周数:" + c.getActualMaximum(Calendar.WEEK_OF_MONTH)); } }
true
db26ace6add70fd947ef73f59854a101ed00793e
Java
sqlancer/sqlancer
/src/sqlancer/materialize/ast/MaterializePOSIXRegularExpression.java
UTF-8
1,615
2.625
3
[ "MIT" ]
permissive
package sqlancer.materialize.ast; import sqlancer.Randomly; import sqlancer.common.ast.BinaryOperatorNode.Operator; import sqlancer.materialize.MaterializeSchema.MaterializeDataType; public class MaterializePOSIXRegularExpression implements MaterializeExpression { private MaterializeExpression string; private MaterializeExpression regex; private POSIXRegex op; public enum POSIXRegex implements Operator { MATCH_CASE_SENSITIVE("~"), MATCH_CASE_INSENSITIVE("~*"), NOT_MATCH_CASE_SENSITIVE("!~"), NOT_MATCH_CASE_INSENSITIVE("!~*"); private String repr; POSIXRegex(String repr) { this.repr = repr; } public String getStringRepresentation() { return repr; } public static POSIXRegex getRandom() { return Randomly.fromOptions(values()); } @Override public String getTextRepresentation() { return toString(); } } public MaterializePOSIXRegularExpression(MaterializeExpression string, MaterializeExpression regex, POSIXRegex op) { this.string = string; this.regex = regex; this.op = op; } @Override public MaterializeDataType getExpressionType() { return MaterializeDataType.BOOLEAN; } @Override public MaterializeConstant getExpectedValue() { return null; } public MaterializeExpression getRegex() { return regex; } public MaterializeExpression getString() { return string; } public POSIXRegex getOp() { return op; } }
true
8fac686e9e54ea6d7445fd9421e7a9bd98d62384
Java
GHMarcianoR/AlinhadorOnto
/src/br/ufjf/Ancoragem.java
UTF-8
11,105
2.34375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.ufjf; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein; /** * * @author zumbi */ public class Ancoragem { public Ancoragem(List<Cluster> s) throws IOException { ancorar(s); } /* private void loadCategories() throws FileNotFoundException, IOException { String database = "/root/ontology_alignment/dbpedia/article_categories_en.ttl"; BufferedReader br = new BufferedReader(new FileReader(database)); List<String> listCategories = new ArrayList<String>(); boolean n = false; String anterior = ""; while(br.ready()) { String [] campos = br.readLine().split(" "); listCategories.add(campos[2]); if(!anterior.equals(campos[0])) { articleCategories.put(anterior, listCategories); anterior = campos[0]; listCategories = new ArrayList<>(); } } }*/ private String selecionarLabels(List<String> list, String ancora) { String escolhida = null; Levenshtein lv = new Levenshtein(); double max = 0.8; for(String s : list) { String nova = s.replace("http://dbpedia.org/resource/", ""); nova = nova.substring(1, nova.indexOf(">")); if(lv.getSimilarity(nova, ancora) > max) { escolhida = nova; break; } } return escolhida; } private List<String> selecionarRedirects(List<String> listStr, String ancora) { List<String> escolhidas = new ArrayList<String>(); Levenshtein lv = new Levenshtein(); double max = 0.8; int i = 0; for(String s : listStr) { String separadas [] = s.split(" "); separadas[2] = separadas[2].replace("http://dbpedia.org/resource/", ""); separadas[2] = separadas[2].substring(1,separadas[2].indexOf(">")); separadas[0] = separadas[0].replace("http://dbpedia.org/resource/", ""); separadas[0] = separadas[0].substring(1,separadas[0].indexOf(">")); if(lv.getSimilarity(ancora, separadas[2]) > max) escolhidas.add(separadas[0]); } return escolhidas; } private List<String> selecionarCategories(List<String> listStr,String ancora) { List<String> escolhidas = new ArrayList<String>(); Levenshtein lv = new Levenshtein(); double max = 0.8; int i = 0; for(String s : listStr) { try { String separadas [] = s.split(" "); separadas[0] = separadas[0].replace("http://dbpedia.org/resource/", ""); separadas[0] = separadas[0].substring(1,separadas[0].indexOf(">")); if(lv.getSimilarity(ancora, separadas[0]) > max) { separadas[2] = separadas[2].replace("http://dbpedia.org/resource/Category:", ""); separadas[2] = separadas[2].substring(1,separadas[2].indexOf(">")); escolhidas.add(separadas[2]); } }catch(Exception e) { System.err.println(e.getMessage()); } } return escolhidas; } private List<String> selecionarSkosCategories(List<String> listStr,String ancora) { List<String> escolhidas = new ArrayList<String>(); Levenshtein lv = new Levenshtein(); double max = 0.8; int i = 0; for(String s : listStr) { try { String separadas [] = s.split(" "); separadas[0] = separadas[0].replace("http://dbpedia.org/resource/Category:", ""); separadas[0] = separadas[0].substring(1,separadas[0].indexOf(">")); if(lv.getSimilarity(ancora, separadas[0]) > max) { separadas[2] = separadas[2].replace("http://dbpedia.org/resource/Category:", ""); separadas[2] = separadas[2].substring(1,separadas[2].indexOf(">")); escolhidas.add(separadas[2]); } }catch(Exception e) { System.err.println(e.getMessage()); } } return escolhidas; } private String auxAncorarLabels(String s) throws IOException { // System.out.println("Ancorando: "+s+" ao labels"); String database = "/root/ontology_alignment/dbpedia/labels_en.ttl"; //String database = "/home/zumbi/dbpedia/labels_en.nt"; List<String> listStr = new ArrayList<String>(); String cmd = "grep "+s+ " "+database; String linha; String str = null; Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(cmd); BufferedReader is = new BufferedReader(new InputStreamReader(proc.getInputStream())); while( (linha = is.readLine() ) != null) listStr.add(linha.split(" ")[0]); if(!listStr.isEmpty()) str = selecionarLabels(listStr, s); return str; } private List<String> auxAncorarRedirects(String s) throws IOException { // System.out.println("Ancorando: "+s+" ao redirects"); String database = "/root/ontology_alignment/dbpedia/redirects_en.ttl"; System.out.flush(); // String database = "/home/zumbi/dbpedia/redirects_en.nt"; List<String> listStr = new ArrayList<String>(); String cmd = "grep "+s+ " "+database; String linha; String str = null; Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(cmd); BufferedReader is = new BufferedReader(new InputStreamReader(proc.getInputStream())); while( (linha = is.readLine() ) != null) listStr.add(linha); return selecionarRedirects(listStr,s); } private List<String> auxAncorarArtCategories(String s) throws IOException { // System.out.println("Ancorando: "+s+" ao Article Categories"); String database = "/root/ontology_alignment/dbpedia/article_categories_en.ttl"; System.out.flush(); // String database = "/home/zumbi/dbpedia/article_templates_en.ttl"; List<String> listStr = new ArrayList<String>(); String cmd = "grep "+s+ " "+database; String linha; List<String> result = null; String str = null; Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(cmd); BufferedReader is = new BufferedReader(new InputStreamReader(proc.getInputStream())); while( (linha = is.readLine() ) != null) listStr.add(linha); return selecionarCategories(listStr,s); } private List<String> auxAncorarSkosCategories(String s) throws IOException { // System.out.println("Ancorando: "+s+" ao skos_Categories"); String database = "/root/ontology_alignment/dbpedia/skos_categories_en.ttl"; System.out.flush(); // String database = "/home/zumbi/dbpedia/article_templates_en.ttl"; List<String> listStr = new ArrayList<String>(); String cmd = "grep "+s+ " "+database; String linha; String str = null; Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(cmd); BufferedReader is = new BufferedReader(new InputStreamReader(proc.getInputStream())); while( (linha = is.readLine() ) != null) listStr.add(linha); return selecionarSkosCategories(listStr,s); } private void ancoraSubCategorias(List<Cluster> listClusters) throws IOException { int aux = 0, nivel =3; for(Cluster c : listClusters) { if(c.getRoot().getCategorias() != null) { List<String> it = c.getRoot().getCategorias(); while(aux < nivel) { List<String> subCategorias = new ArrayList<String>(); for(String l : it ) subCategorias.addAll(auxAncorarSkosCategories(l)); if(!subCategorias.isEmpty()) { // c.getRoot().getSubCategorias().setSubCategorias(subCategorias, aux); // it = c.getRoot().getSubCategorias().getSubCategorias(aux); } aux++; } } aux= 0; for(Entidade e : c.getListEntidades()) { if(e.getCategorias() != null) { List<String> it = e.getCategorias(); while(aux < nivel) { List<String> subCategorias = new ArrayList<String>(); for(String l : it ) subCategorias.addAll(auxAncorarSkosCategories(l)); if(!subCategorias.isEmpty()) { // e.getSubCategorias().setSubCategorias(subCategorias, aux); // it = e.getSubCategorias().getSubCategorias(aux); } aux++; } } } } } private void ancorar(List<Cluster> listClusters) throws IOException { System.out.println("Iniciando Processo de Ancoragem labels"); System.out.println("Quantidade de Clusters "+listClusters.size()); int nivel = 3; for(Cluster c : listClusters) { c.getRoot().setrscLabel(auxAncorarLabels(c.getRoot().getNome())); for(Entidade s : c.getListEntidades()) s.setrscLabel(auxAncorarLabels(s.getNome())); } for(Cluster c : listClusters) { if(c.getRoot().getRscLabel()!= null) { c.getRoot().setRedirects(auxAncorarRedirects(c.getRoot().getRscLabel())); c.getRoot().addCategorias(auxAncorarArtCategories(c.getRoot().getRscLabel())); } for(Entidade e: c.getListEntidades()) { if(e.getRscLabel()!= null) { e.setRedirects(auxAncorarRedirects(e.getRscLabel())); e.addCategorias(auxAncorarArtCategories(e.getRscLabel())); } } } ancoraSubCategorias(listClusters); } }
true
8e82825dc13e0f907bbfc02514607db6f9ea816d
Java
aprilshenju/babybaby
/umeijia/src/main/java/com/umeijia/util/FileUtils.java
UTF-8
5,563
3.15625
3
[]
no_license
package com.umeijia.util; import java.io.*; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; /** * Created by Administrator on 2016/6/24. */ public class FileUtils { /** * the traditional io way * * @param filename * @return * @throws IOException */ public static byte[] fileToByteArrayByTraditionalWay(String filename) throws IOException { File f = new File(filename); if (!f.exists()) { throw new FileNotFoundException("找不到该图片"); } ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length()); BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(f)); int buf_size = 1024; byte[] buffer = new byte[buf_size]; int len = 0; while (-1 != (len = in.read(buffer, 0, buf_size))) { bos.write(buffer, 0, len); } return bos.toByteArray(); } finally { in.close(); bos.close(); } } /** * NIO way * * @param filename * @return * @throws IOException */ public static byte[] fileToByteArrayByNIOWay(String filename) throws IOException { File f = new File(filename); // if (!f.exists()) { // throw new FileNotFoundException(filename); // } FileChannel channel = null; FileInputStream fs = null; try { fs = new FileInputStream(f); channel = fs.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size()); while ((channel.read(byteBuffer)) > 0) { // do nothing // System.out.println("reading"); } return byteBuffer.array(); } finally { try { channel.close(); } catch (IOException e) { e.printStackTrace(); } try { fs.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能 * * @param filename * @return * @throws IOException */ public static byte[] fileToByteArrayByMappedFileWay(String filename) throws IOException { FileChannel fc = null; try { fc = new RandomAccessFile(filename, "r").getChannel(); MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()).load(); System.out.println(byteBuffer.isLoaded()); byte[] result = new byte[(int) fc.size()]; if (byteBuffer.remaining() > 0) { // System.out.println("remain"); byteBuffer.get(result, 0, byteBuffer.remaining()); } return result; } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { fc.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 复制单个文件 * * @param srcFileName * 待复制的文件名 * @param destFileName * 目标文件名 * @param overlay * 如果目标文件存在,是否覆盖 * @return 如果复制成功返回true,否则返回false */ public static boolean copyFile(String srcFileName, String destFileName, boolean overlay) { File srcFile = new File(srcFileName); // 判断源文件是否存在 if (!srcFile.exists()) { return false; } else if (!srcFile.isFile()) { return false; } // 判断目标文件是否存在 File destFile = new File(destFileName); if (destFile.exists()) { // 如果目标文件存在并允许覆盖 if (overlay) { // 删除已经存在的目标文件,无论目标文件是目录还是单个文件 new File(destFileName).delete(); } } else { // 如果目标文件所在目录不存在,则创建目录 if (!destFile.getParentFile().exists()) { // 目标文件所在目录不存在 if (!destFile.getParentFile().mkdirs()) { // 复制文件失败:创建目标文件所在目录失败 return false; } } } // 复制文件 int byteread = 0; // 读取的字节数 InputStream in = null; OutputStream out = null; try { in = new FileInputStream(srcFile); out = new FileOutputStream(destFile); byte[] buffer = new byte[1024]; while ((byteread = in.read(buffer)) != -1) { out.write(buffer, 0, byteread); } return true; } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } finally { try { if (out != null) out.close(); if (in != null) in.close(); } catch (IOException e) { e.printStackTrace(); } } } }
true
8d2f557f6aa8e1ae96b1a2e5072b26c4fd3bacd9
Java
guilhermejccavalcanti/sourceeis
/MergeConflictParserAndAnalyser/src/cin/ufpe/br/util/ConflictsCollector.java
UTF-8
4,418
2.453125
2
[]
no_license
package cin.ufpe.br.util; import java.io.IOException; import java.util.ArrayList; import org.eclipse.jdt.core.dom.ASTParser; import cin.ufpe.br.parser.Parsed; import cin.ufpe.br.parser.Parser; public final class ConflictsCollector { public static ArrayList<MergeConflict> collect(String filename) throws IOException{ ArrayList<ConflictPair> pairs = collectMineTheirsFromText(filename); ArrayList<MergeConflict> conflicts = new ArrayList<MergeConflict>(); int index = 0; while (index < pairs.size()) { ConflictPair pair = pairs.get(index); MergeConflict mc = new MergeConflict(String.join("\n",pair.getMine())+"\n", String.join("\n",pair.getYours())+"\n"); mc.originFile = pair.getOriginFile(); tryAndCallParser(mc); conflicts.add(mc); index++; } return conflicts; } public static ArrayList<MergeConflict> collectNoParser(String filename) throws IOException{ ArrayList<ConflictPair> pairs = collectMineTheirsFromText(filename); ArrayList<MergeConflict> conflicts = new ArrayList<MergeConflict>(); int index = 0; while (index < pairs.size()) { ConflictPair pair = pairs.get(index); MergeConflict mc = new MergeConflict(String.join("\n",pair.getMine())+"\n", String.join("\n",pair.getYours())+"\n"); mc.originFile = pair.getOriginFile(); conflicts.add(mc); index++; } return conflicts; } @SuppressWarnings("unchecked") public static void tryAndCallParser(MergeConflict mc) { Parser parser = new Parser(); if(!FileHandlerr.getStringContentIntoSingleLineNoSpacing(mc.right).isEmpty()){ Parsed rightparsed = null; //trying different types of parsing try{ rightparsed = parser.parse(mc.right, ASTParser.K_COMPILATION_UNIT); } catch(Exception e1){ try{ rightparsed = parser.parse(mc.right, ASTParser.K_CLASS_BODY_DECLARATIONS); }catch(Exception e2){ mc.rightunableToParse = true; } } if(null!=rightparsed){ mc.rightTypes = rightparsed.printer.getTypes(); mc.rightTypesString = rightparsed.printer.getResult(); } } if(!FileHandlerr.getStringContentIntoSingleLineNoSpacing(mc.left).isEmpty()){ Parsed leftparsed = null; try{ leftparsed = parser.parse(mc.left, ASTParser.K_COMPILATION_UNIT); } catch(Exception e1){ try{ leftparsed = parser.parse(mc.left, ASTParser.K_CLASS_BODY_DECLARATIONS); }catch(Exception e2){ mc.leftunableToParse = true; } } if(null!=leftparsed){ mc.leftTypes = leftparsed.printer.getTypes(); mc.leftTypesString = leftparsed.printer.getResult(); } } } public static ArrayList<ConflictPair> collectMineTheirsFromText(String filename) throws IOException{ ArrayList<String> fileText = FileHandlerr.readFile(filename); ArrayList<ConflictPair> allConflicts = new ArrayList<>(); int index = 0; while(index < fileText.size()){ if(checkForMine(fileText.get(index))){ String originFile = fileText.get(index).split(";")[0]; ArrayList<String> mine = new ArrayList<String>(); ArrayList<String> yours = new ArrayList<String>(); if(checkForEOF(fileText.size(), index + 1)){ index += 1; int mineIndex = 0; while(!checkForConflictHeadline(fileText.get(index))){ mine.add(mineIndex,fileText.get(index)); mineIndex++; index++; } /* Jumps the "======" */ index++; if(checkForEOF(fileText.size(), index + 1)){ int yoursIndex = 0; while(!checkForYoursEnd(fileText.get(index))){ yours.add(yoursIndex,fileText.get(index)); yoursIndex++; index++; } } ConflictPair ConflictPair = new ConflictPair(mine, yours,originFile); allConflicts.add(ConflictPair); } } index++; } return allConflicts; } private static Boolean checkForConflictHeadline(String text){ Boolean foundConflict = false; if(text.contains("=======")){ foundConflict = true; } return foundConflict; } private static Boolean checkForEOF(int numberOfLines, int index){ Boolean eof = false; if(index < numberOfLines){ eof = true; } return eof; } private static Boolean checkForYoursEnd(String text){ Boolean foundYoursEnd = false; if(text.contains(">>>>>>> YOURS")){ foundYoursEnd = true; } return foundYoursEnd; } private static Boolean checkForMine(String text){ Boolean foundMine = false; if(text.contains("<<<<<<< MINE")){ foundMine = true; } return foundMine; } }
true
93cc2a1c6c5845be42f0ca980814fa2dac6a36dc
Java
febbyftrp/Shopistic-Project
/app/src/main/java/mmu/edu/my/shopistic/model/RecentlyViewed.java
UTF-8
1,604
2.515625
3
[]
no_license
package mmu.edu.my.shopistic.model; public class RecentlyViewed { String name; String description; String price; String size; String colour; int imageUrl; int bigimageurl; public RecentlyViewed(String name, String description, String price, String size, String colour, int imageUrl, int bigimageurl) { this.name = name; this.description = description; this.price = price; this.size = size; this.colour = colour; this.imageUrl = imageUrl; this.bigimageurl = bigimageurl; } public int getBigimageurl() { return bigimageurl; } public void setBigimageurl(int bigimageurl) { this.bigimageurl = bigimageurl; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } public int getImageUrl() { return imageUrl; } public void setImageUrl(int imageUrl) { this.imageUrl = imageUrl; } }
true
5e84e35415620f25624c05c68f0f9d4976a179cf
Java
fight4gold/Playground
/src/test/java/net/fratzlow/jdk/Java8Test.java
UTF-8
2,228
3
3
[]
no_license
package net.fratzlow.jdk; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; /** * // TODO (FRa) : (FRa) : comment * * @author ratzlow@gmail.com * @since 2014-11-02 */ public class Java8Test { @Test public void test2_2() throws IOException { Path path = Paths.get(this.getClass().getResource("/war_and_peace.txt").getPath()); Stream<String> lines = Files.lines(path); long start = System.currentTimeMillis(); long wordCount = lines.map(s -> s.split("\\s+")).flatMap(sa -> Stream.<String>of(sa) ) //.peek(s -> System.out.println("\tbefore => " + s)) //.filter( s -> s.length() > 5) //.limit(5) //.forEach( s -> System.out.println("after => " + s)); .count(); System.out.println("Word count = " + wordCount + " -> after (ms):" + (System.currentTimeMillis()-start)); } @Test public void testIntStreamCreation2_4() { int[] ar = { 1,4,9,16 }; int[] intAr = IntStream.of(ar).toArray(); Assert.assertArrayEquals( ar, intAr ); } @Test public void test2_5() { } @Test public void testListIntoMapCollection() { Map<String, String> map = new HashMap<>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); List<Tuple> tuples = map.entrySet().stream() .map(entry -> new Tuple(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); Map<String, String> map2 = tuples.stream().collect(Collectors.toMap(Tuple::getKey, Tuple::getValue)); Assert.assertEquals(map, map2); } class Tuple { String key, value; Tuple(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public String getValue() { return value; } } }
true
1c4d27d395bf20e752c936a8cd25f6d260d34a8c
Java
tech-interview-prep/technical-interview-preparation
/src/utils/Interval.java
UTF-8
1,203
3.359375
3
[]
no_license
package utils; import java.util.ArrayList; import java.util.List; public class Interval { public int start; public int end; public Interval() { start = end = 0; } public Interval(int s, int e) { start = s; end = e; } public String toString() { return "[" + start + ", " + end + "]"; } //[1, 3], [2, 6], [5, 9], [8, 10], [15, 18] public static List<Interval> getSampleIntervals() { List<Interval> ret = new ArrayList<Interval>(); ret.add(new Interval(1, 3)); ret.add(new Interval(2, 6)); ret.add(new Interval(5, 9)); ret.add(new Interval(8, 10)); ret.add(new Interval(15, 18)); return ret; } //[1, 4], [4, 5] public static List<Interval> getSampleIntervals2() { List<Interval> ret = new ArrayList<Interval>(); ret.add(new Interval(1, 4)); ret.add(new Interval(4, 5)); return ret; } //[1, 4], [2, 3] public static List<Interval> getSampleIntervals3() { List<Interval> ret = new ArrayList<Interval>(); ret.add(new Interval(1, 4)); ret.add(new Interval(2, 3)); return ret; } }
true
b1dba244b32efb606d549852845053f9fb218917
Java
hhz1992/leetcode
/src/hashTable/No166_FractiontoRecurringDecimal.java
UTF-8
1,104
3.046875
3
[]
no_license
package hashTable; import java.util.HashMap; /** * Created by Huanzhou on 2016/2/22. */ public class No166_FractiontoRecurringDecimal { public String fractionToDecimal(int numerator, int denominator) { if(numerator == 0 ) return "0"; StringBuilder sb = new StringBuilder(); sb.append((numerator>0)^(denominator>0)? "-":""); long num = Math.abs((long)numerator); long denum = Math.abs((long)denominator); sb.append(num/denum); num%=denum; if(num == 0) return sb.toString(); sb.append("."); HashMap<Long,Integer> map = new HashMap<Long,Integer>(); map.put(num,sb.length()); while(num!=0){ num *= 10; sb.append(num/denum); num %=denum; if(map.containsKey(num)){ int index = map.get(num); sb.insert(index,"("); sb.append(")"); break; }else{ map.put(num, sb.length()); } } return sb.toString(); } }
true
d3f828e0608e36bd39ef679f333625a4968180f1
Java
epam/cloud-pipeline
/docker-comp-scan/src/test/java/com/epam/dockercompscan/owasp/analyzer/RPackageAnalyzerTest.java
UTF-8
2,054
1.96875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/) * * 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.epam.dockercompscan.owasp.analyzer; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.dependency.Dependency; public class RPackageAnalyzerTest { private RPackageAnalyzer rPackageAnalyzer; @Before public void setUp() { rPackageAnalyzer = new RPackageAnalyzer(); } @Test public void analyzeDependencyTestPositive() throws AnalysisException { Dependency dependency = new Dependency(); dependency.setActualFilePath(this.getClass().getClassLoader().getResource( "owasp/analyzer/positive/DESCRIPTION").getPath()); rPackageAnalyzer.analyzeDependency(dependency, null); Assert.assertEquals(RPackageAnalyzer.DEPENDENCY_ECOSYSTEM, dependency.getEcosystem()); Assert.assertEquals("PositiveTest", dependency.getName()); Assert.assertEquals("1.0", dependency.getVersion()); } @Test public void analyzeDependencyTestNegative() throws AnalysisException { Dependency dependency = new Dependency(); dependency.setActualFilePath(this.getClass().getClassLoader().getResource( "owasp/analyzer/negative/etc/DESCRIPTION").getPath()); rPackageAnalyzer.analyzeDependency(dependency, null); Assert.assertNull(dependency.getEcosystem()); } }
true
48404e98ec9302389f70f14b0a1dd1ea76ad8318
Java
littcai/littcore-codegen
/src/main/java/com/littcore/codegen/model/Func.java
UTF-8
1,201
2.203125
2
[ "MIT" ]
permissive
package com.littcore.codegen.model; public class Func { /** * 编号. */ private String code; private String fullCode; /** * 标题. */ private String title; private String descr; /** * */ private boolean isPermission = true; /** * @return the code */ public String getCode() { return code; } /** * @param code the code to set */ public void setCode(String code) { this.code = code; } public String getFullCode() { return fullCode; } public void setFullCode(String fullCode) { this.fullCode = fullCode; } /** * @return the title */ public String getTitle() { return title; } /** * @param title the title to set */ public void setTitle(String title) { this.title = title; } /** * @return the descr */ public String getDescr() { return descr; } /** * @param descr the descr to set */ public void setDescr(String descr) { this.descr = descr; } /** * @return the isPermission */ public boolean isPermission() { return isPermission; } /** * @param isPermission the isPermission to set */ public void setPermission(boolean isPermission) { this.isPermission = isPermission; } }
true
37525cb36d77a91841c9bc92abe3675f6e202f3d
Java
lzl471954654/IQIYI_OPEN_API_TEST
/app/src/main/java/com/lzl/iqiyi_open_api_test/MainActivity.java
UTF-8
10,264
1.992188
2
[]
no_license
package com.lzl.iqiyi_open_api_test; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; 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.ImageView; import android.widget.TextView; import com.lzl.iqiyi_open_api_test.Activity.PlayerActivity; import com.lzl.iqiyi_open_api_test.DataClass.RecommendData; import com.lzl.iqiyi_open_api_test.DataClass.VideoData; import com.lzl.iqiyi_open_api_test.DataClass.ChannelData; import com.lzl.iqiyi_open_api_test.HttpRequest.DataRequest; import com.lzl.iqiyi_open_api_test.HttpRequest.ParseDataFromHttp; import com.qiyi.video.playcore.QiyiVideoView; import java.io.IOException; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ Button getChannelList; Button getChannelData; Button recommendButton; Button getImageButton; Button searchButton; ImageView imageView; EditText editText; TextView data; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Intent intent = new Intent(this, PlayerActivity.class); //startActivity(intent); getChannelData = (Button)findViewById(R.id.get_channel_data_button); getChannelList = (Button)findViewById(R.id.get_list_button); getImageButton = (Button)findViewById(R.id.getImageButton); searchButton = (Button)findViewById(R.id.searchButton); imageView = (ImageView)findViewById(R.id.image_data); editText = (EditText)findViewById(R.id.edit_text); data = (TextView)findViewById(R.id.request_data_text); recommendButton = (Button)findViewById(R.id.recommendButton); recommendButton.setOnClickListener(this); getChannelList.setOnClickListener(this); getChannelData.setOnClickListener(this); getImageButton.setOnClickListener(this); searchButton.setOnClickListener(this); } @Override public void onClick(final View v) { switch (v.getId()) { case R.id.searchButton: { System.out.println("search!"); String s = editText.getText().toString(); DataRequest dataRequest = DataRequest.newInstance(); dataRequest.searchVideoNormally(s, new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { System.out.println("Search!!!"); String s = response.body().string(); System.out.println(s); final List<VideoData> list = ParseDataFromHttp.getSearchVideoList(s); runOnUiThread(new Runnable() { @Override public void run() { StringBuilder builder = new StringBuilder(); for (VideoData videoData : list) { builder.append(videoData); } data.setText(builder.toString()); if(list.size()!=0) { VideoData videoData = list.get(0); Bundle bundle = new Bundle(); bundle.putSerializable("videoData",videoData); Intent intent = new Intent(MainActivity.this,PlayerActivity.class); intent.putExtras(bundle); startActivity(intent); } } }); } }); break; } case R.id.getImageButton: { DataRequest dataRequest = DataRequest.newInstance(); dataRequest.getPic("http://m.qiyipic.com/common/lego/20170605/9fc9cfd0a4264ebca49d29e058a00ebf.jpg", new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); System.out.println("image error"); } @Override public void onResponse(Call call, Response response) throws IOException { //InputStream inputStream = response.body().byteStream(); // final Bitmap bitmap = BitmapFactory.decodeStream(inputStream); byte[] bytes = response.body().bytes(); final Bitmap bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length); if(bitmap==null) System.out.println("image null"); runOnUiThread(new Runnable() { @Override public void run() { imageView.setImageBitmap(bitmap); } }); } }); break; } case R.id.recommendButton: { System.out.println("recommendButton click!"); DataRequest dataRequest = DataRequest.newInstance(); dataRequest.getRecommendList(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { data.setText("Net ERROR"); } }); } @Override public void onResponse(Call call, Response response) throws IOException { System.out.println("recommendData success!"); final StringBuilder builder = new StringBuilder(); final String s = response.body().string(); List<RecommendData> list = ParseDataFromHttp.getRcommendDataList(s); for (RecommendData recommendData : list) { builder.append(recommendData); } runOnUiThread(new Runnable() { @Override public void run() { data.setText(builder.toString()); } }); } }); break; } case R.id.get_channel_data_button: { DataRequest dataRequest = DataRequest.newInstance(); dataRequest.getChannelDataDetails(editText.getText().toString(), new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { //System.out.println(response.body().string()); String s = response.body().string(); List<VideoData> list = ParseDataFromHttp.getChannelVideoList(s); final StringBuilder builder = new StringBuilder(); for (VideoData videoData : list) { builder.append(videoData.toString()); } System.out.println(builder.toString()); runOnUiThread(new Runnable() { @Override public void run() { data.setText(builder.toString()); } }); } }); break; } case R.id.get_list_button: { DataRequest dataRequest = DataRequest.newInstance(); dataRequest.getChannelList(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); System.out.println("error list"); } @Override public void onResponse(Call call, Response response) throws IOException { System.out.println("success list"); //System.out.println(response.body().string()); String s = response.body().string(); System.out.println(s); //response.body().close(); List<ChannelData> list = ParseDataFromHttp.getChannelList(s); final StringBuilder builder = new StringBuilder(); for(ChannelData channelData:list) { builder.append(channelData.toString()); } //System.out.println(builder.toString()); runOnUiThread(new Runnable() { @Override public void run() { data.setText(builder.toString()); } }); } }); break; } } } }
true
24f437f2aede51f020127a211ce6e8da77da0bb0
Java
SimonVT/cathode
/cathode/src/main/java/net/simonvt/cathode/ui/suggestions/shows/ShowSuggestionsFragment.java
UTF-8
2,030
1.804688
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2016 Simon Vig Therkildsen * * 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 net.simonvt.cathode.ui.suggestions.shows; import android.os.Bundle; import android.view.MenuItem; import androidx.annotation.Nullable; import androidx.appcompat.widget.Toolbar; import androidx.viewpager.widget.PagerAdapter; import net.simonvt.cathode.R; import net.simonvt.cathode.ui.suggestions.SuggestionsFragment; public class ShowSuggestionsFragment extends SuggestionsFragment { public static final String TAG = "net.simonvt.cathode.ui.suggestions.shows.ShowSuggestionsFragment"; private ShowSuggestionsPagerAdapter adapter; @Override public void onCreate(@Nullable Bundle inState) { super.onCreate(inState); setTitle(R.string.title_suggestions); adapter = new ShowSuggestionsPagerAdapter(requireContext(), getChildFragmentManager()); } @Override protected PagerAdapter getAdapter() { return adapter; } @Override public void createMenu(Toolbar toolbar) { super.createMenu(toolbar); toolbar.inflateMenu(R.menu.fragment_shows); toolbar.inflateMenu(R.menu.fragment_shows_recommended); } @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.sort_by: return adapter.getItem(getBinding().pager.getCurrentItem()).onMenuItemClick(item); case R.id.menu_search: getNavigationListener().onSearchClicked(); return true; default: return super.onMenuItemClick(item); } } }
true
77743ae533d4bd764f76af5b3ee770812f54b1b4
Java
jaxonjma/Prueba
/Prueba/src/main/java/com/jaxon/prueba/service/IStudentService.java
UTF-8
542
1.914063
2
[]
no_license
package com.jaxon.prueba.service; import java.util.List; import com.jaxon.prueba.model.Student; import com.jaxon.prueba.service.exceptions.BDException; import com.jaxon.prueba.service.exceptions.ElementNotFoundException; public interface IStudentService { List<Student> getAllStudents(); void saveStudentsInDataBase(); List<Student> generateAleatoryStudents(); Student create(Student student) throws BDException; Student modify(Student student) throws ElementNotFoundException; void delete(Long idt) throws BDException; }
true
7557943a0884901463ee3bae4d4db8c78f2356f4
Java
laura0luc/Collaborative
/src/edu/itesm/db/TaskTable.java
UTF-8
1,070
2.28125
2
[]
no_license
package edu.itesm.db; import android.database.sqlite.SQLiteDatabase; import android.util.Log; public class TaskTable { public static final String TABLA_TASKS = "tasks"; public static final String ID_COLUMN = "_id"; public static final String NAME_COLUMN = "name"; public static final String COLAB_COLUMN = "collaborators"; public static final String START_COLUMN = "start"; public static final String END_COLUMN="end"; private static final String CREATE_DB = "create table " + TABLA_TASKS + "(" + ID_COLUMN + " integer primary key autoincrement, " + NAME_COLUMN + " text not null, " + COLAB_COLUMN + " text not null, " + START_COLUMN + " text not null, " + END_COLUMN + " text not null" + ");"; public static void onCreate(SQLiteDatabase database) { Log.i("onCreate","query del create: "+CREATE_DB); database.execSQL(CREATE_DB); } public static void onUpgrade( SQLiteDatabase database, int oldVersion, int newVersion) { database.execSQL("DROP TABLE IF EXISTS"+TABLA_TASKS); onCreate(database); } }
true
b75d33aa83a534b52fecda0188f63a1a5acf34c0
Java
ngohado/MuaBanNhaDat
/app/src/main/java/com/qtd/muabannhadat/model/ApartmentCategory.java
UTF-8
683
2.53125
3
[]
no_license
package com.qtd.muabannhadat.model; import java.util.ArrayList; /** * Created by Dell on 4/9/2016. */ public class ApartmentCategory { private String name; private ArrayList<Apartment> apartments; public ApartmentCategory(String name, ArrayList<Apartment> apartments) { this.name = name; this.apartments = apartments; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ArrayList<Apartment> getApartments() { return apartments; } public void setApartments(ArrayList<Apartment> apartments) { this.apartments = apartments; } }
true
846630af14078ba355cd8313a9b3e03b7bacf1e7
Java
John-Smile/Practice
/src/main/java/practice/nia/chp5/ReferenceCounting.java
UTF-8
395
2.109375
2
[]
no_license
package practice.nia.chp5; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.Channel; public class ReferenceCounting { public static void main(String[] args) { Channel channel = null; ByteBufAllocator allocator = channel.alloc(); ByteBuf buffer = allocator.directBuffer(); assert buffer.refCnt() == 1; } }
true
8810eb7d4d7be63654c7f3281b2dbf1f52651a69
Java
lilavera/Cucumber-Tests
/cucumberTests/src/test/java/ogorek/NowyUzytkownikSteps.java
UTF-8
1,130
2.734375
3
[]
no_license
package ogorek; import cucumber.api.DataTable; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import java.util.Map; public class NowyUzytkownikSteps { @Given("^uzytkownik jest na stronie formularzu dodawania nowego uzytkownika$") public void uzytkownikJestNaStronieFormularzuDodawaniaNowegoUzytkownika() { System.out.println("Information is shown"); } @When("^Wprowadza poprawne dane do formularza:$") public void wprowadzaPoprawneDaneDoFormularza(DataTable dataTable) { Map<String,String> data = dataTable.asMaps(String.class,String.class).get(0); System.out.println("Imie" + data.get("imie")); System.out.println("Nazwisko" + data.get("nazwisko")); System.out.println("Miasto" + data.get("miasto")); System.out.println("Ulica" + data.get("ulica")); } @Then("^Informacja o dodaniu uzytkownika pojawia sie na ekranie$") public void informacjaODodaniuUzytkownikaPojawiaSieNaEkranie() { System.out.println("New user is added"); } }
true
5e5065534265bac0b97e826161b597fe7a12d278
Java
computerphilosopher/arcus-java-client
/src/main/java/net/spy/memcached/protocol/ascii/BaseGetOpImpl.java
UTF-8
7,093
2.15625
2
[ "Apache-2.0", "MIT" ]
permissive
/* * arcus-java-client : Arcus Java client * Copyright 2010-2014 NAVER Corp. * Copyright 2014-2022 JaM2in Co., 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 net.spy.memcached.protocol.ascii; import java.nio.Buffer; import java.nio.ByteBuffer; import java.util.Collection; import java.util.Iterator; import net.spy.memcached.ops.GetOperation; import net.spy.memcached.ops.GetsOperation; import net.spy.memcached.ops.OperationCallback; import net.spy.memcached.ops.OperationState; import net.spy.memcached.ops.OperationStatus; import net.spy.memcached.ops.OperationType; import net.spy.memcached.ops.StatusCode; /** * Base class for get and gets handlers. */ abstract class BaseGetOpImpl extends OperationImpl { private static final OperationStatus END = new OperationStatus(true, "END", StatusCode.SUCCESS); private static final String RN_STRING = "\r\n"; private final String cmd; private final Collection<String> keys; private String currentKey = null; private long casValue = 0; private int currentFlags = 0; private byte[] data = null; private int readOffset = 0; private byte lookingFor = '\0'; public BaseGetOpImpl(String c, OperationCallback cb, Collection<String> k) { super(cb); cmd = c; keys = k; setOperationType(OperationType.READ); } /** * Get the keys this GetOperation is looking for. */ public final Collection<String> getKeys() { return keys; } @Override public final void handleLine(String line) { if (line.equals("END")) { getLogger().debug("Get complete!"); getCallback().receivedStatus(END); transitionState(OperationState.COMPLETE); data = null; } else if (line.startsWith("VALUE ")) { getLogger().debug("Got line %s", line); String[] stuff = line.split(" "); assert stuff[0].equals("VALUE"); currentKey = stuff[1]; currentFlags = Integer.parseInt(stuff[2]); data = new byte[Integer.parseInt(stuff[3])]; if (stuff.length > 4) { casValue = Long.parseLong(stuff[4]); } readOffset = 0; getLogger().debug("Set read type to data"); setReadType(OperationReadType.DATA); } else { assert false : "Unknown line type: " + line; } } @Override public final void handleRead(ByteBuffer b) { assert currentKey != null; assert data != null; // This will be the case, because we'll clear them when it's not. assert readOffset <= data.length : "readOffset is " + readOffset + " data.length is " + data.length; getLogger().debug("readOffset: %d, length: %d", readOffset, data.length); // If we're not looking for termination, we're still looking for data if (lookingFor == '\0') { int toRead = data.length - readOffset; int available = b.remaining(); toRead = Math.min(toRead, available); getLogger().debug("Reading %d bytes", toRead); b.get(data, readOffset, toRead); readOffset += toRead; } // Transition us into a ``looking for \r\n'' kind of state if we've // read enough and are still in a data state. if (readOffset == data.length && lookingFor == '\0') { // The callback is most likely a get callback. If it's not, then // it's a gets callback. try { GetOperation.Callback gcb = (GetOperation.Callback) getCallback(); gcb.gotData(currentKey, currentFlags, data); } catch (ClassCastException e) { GetsOperation.Callback gcb = (GetsOperation.Callback) getCallback(); gcb.gotData(currentKey, currentFlags, casValue, data); } lookingFor = '\r'; } // If we're looking for an ending byte, let's go find it. if (lookingFor != '\0' && b.hasRemaining()) { do { byte tmp = b.get(); assert tmp == lookingFor : "Expecting " + lookingFor + ", got " + (char) tmp; switch (lookingFor) { case '\r': lookingFor = '\n'; break; case '\n': lookingFor = '\0'; break; default: assert false : "Looking for unexpected char: " + (char) lookingFor; } } while (lookingFor != '\0' && b.hasRemaining()); // Completed the read, reset stuff. if (lookingFor == '\0') { currentKey = null; data = null; readOffset = 0; currentFlags = 0; getLogger().debug("Setting read type back to line."); setReadType(OperationReadType.LINE); } } } @Override public final void initialize() { int size; StringBuilder commandBuilder = new StringBuilder(); byte[] commandLine; ByteBuffer b; String keysString = generateKeysString(); if (cmd.equals("get") || cmd.equals("gets")) { // make command string, for example, // "get <keys...>\r\n" commandBuilder.append(cmd); commandBuilder.append(' '); commandBuilder.append(keysString); commandBuilder.append(RN_STRING); } else { assert (cmd.equals("mget") || cmd.equals("mgets")) : "Unknown Command " + cmd; int lenKeys = keysString.getBytes().length; int numKeys = keys.size(); // make command string, for example, // "mget <lenKeys> <numkeys>\r\n<keys>\r\n" commandBuilder.append(cmd); commandBuilder.append(' '); commandBuilder.append(String.valueOf(lenKeys)); commandBuilder.append(' '); commandBuilder.append(String.valueOf(numKeys)); commandBuilder.append(RN_STRING); commandBuilder.append(keysString); commandBuilder.append(RN_STRING); } commandLine = commandBuilder.toString().getBytes(); size = commandLine.length; b = ByteBuffer.allocate(size); b.put(commandLine); ((Buffer) b).flip(); setBuffer(b); } private String generateKeysString() { StringBuilder keyString = new StringBuilder(); Iterator<String> iterator = keys.iterator(); // make keys line while (true) { keyString.append(iterator.next()); if (iterator.hasNext()) { keyString.append(' '); } else { break; } } return keyString.toString(); } @Override protected final void wasCancelled() { getCallback().receivedStatus(CANCELLED); } @Override public boolean isBulkOperation() { return false; } @Override public boolean isPipeOperation() { return false; } @Override public boolean isIdempotentOperation() { return true; } }
true
8ff41bb8bc1d0f9f75c0dadc8cfb5dcda6f29d34
Java
WuttipatNilsiri/Payroll
/src/TestCase/PayrollDBTest.java
UTF-8
2,921
2.53125
3
[]
no_license
package TestCase; import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import Command.AddEmployeeTransaction; import Command.Command; import DB.AccountDB; import DB.EmployeeDB; import DB.PayrollDB; import Entity.EmployeeType; import Entity.TimeCard; import Transaction.EmployeeTransaction; import Transaction.HourlyEmployeeTransaction; import Transaction.SalariedEmployeeTransaction; import Transaction.Transaction; public class PayrollDBTest { private static final double TOL = 1.0E-6; private Map<Integer,Transaction> listComissioned = new HashMap<Integer,Transaction>(); private Map<Integer,Transaction> listHourly = new HashMap<Integer,Transaction>(); private Map<Integer,Transaction> listSalaried = new HashMap<Integer,Transaction>(); Map<EmployeeType, Map<Integer,Transaction> > mapQTest = new HashMap<EmployeeType, Map<Integer,Transaction> >(); @Before public void setUp(){ mapQTest.put(EmployeeType.Salaried, listSalaried); mapQTest.put(EmployeeType.Hourly, listHourly); mapQTest.put(EmployeeType.Commissioned, listComissioned); } @Test public void testAddTransaction() { PayrollDB db = PayrollDB.getDB(); EmployeeTransaction trans = new HourlyEmployeeTransaction(1,"home","Nico",300); EmployeeTransaction trans2 = new SalariedEmployeeTransaction(1,"home","Nico",1000); db.addTransaction(trans, EmployeeType.Hourly); db.addTransaction(trans2, EmployeeType.Salaried); mapQTest.get(EmployeeType.Hourly).put(trans.getID(), trans); mapQTest.get(EmployeeType.Salaried).put(trans2.getID(), trans2); assertEquals(mapQTest.get(EmployeeType.Hourly),db.getMap().get(EmployeeType.Hourly)); assertEquals(mapQTest.get(EmployeeType.Salaried),db.getMap().get(EmployeeType.Salaried)); } @Test public void testTransMethod() { AccountDB bankDB = AccountDB.getDB(); EmployeeDB empDB = EmployeeDB.getDB(); Command addEmpCMD = new AddEmployeeTransaction(); PayrollDB db = PayrollDB.getDB(); addEmpCMD.input("name=Nico id=1 address=@home type=H money=salary>300"); addEmpCMD.exec(); empDB.get(1).addTimeCard(TimeCard.create("20:30", "22:30")); db.trans(EmployeeType.Hourly); assertEquals(bankDB.get(empDB.get(1).getaddress()).getBalance(),600,TOL); } @Test public void testDeleteTransaction() { PayrollDB db = PayrollDB.getDB(); EmployeeTransaction trans = new HourlyEmployeeTransaction(1,"home","Nico",300); EmployeeTransaction trans2 = new SalariedEmployeeTransaction(1,"home","Nico",1000); db.addTransaction(trans, EmployeeType.Hourly); db.addTransaction(trans2, EmployeeType.Salaried); db.delete(EmployeeType.Hourly, 1); db.delete(EmployeeType.Salaried, 1); assertEquals(mapQTest.get(EmployeeType.Hourly),db.getMap().get(EmployeeType.Hourly)); assertEquals(mapQTest.get(EmployeeType.Salaried),db.getMap().get(EmployeeType.Salaried)); } }
true
975adfa19dc323c4d6ce139f6760ffe26023580a
Java
alexbobp/TinkeredConstructer
/src/main/java/slimeknights/tconstruct/library/materials/ExtraMaterialStats.java
UTF-8
1,132
2.390625
2
[ "MIT" ]
permissive
package slimeknights.tconstruct.library.materials; import com.google.common.collect.ImmutableList; import java.util.List; import slimeknights.tconstruct.library.Util; public class ExtraMaterialStats extends AbstractMaterialStats { @Deprecated public final static String TYPE = MaterialTypes.EXTRA; public final static String LOC_Durability = "stat.extra.durability.name"; public final static String LOC_DurabilityDesc = "stat.extra.durability.desc"; public final static String COLOR_Durability = HeadMaterialStats.COLOR_Durability; public final int extraDurability; // usually between 0 and 500 public ExtraMaterialStats(int extraDurability) { super(MaterialTypes.EXTRA); this.extraDurability = extraDurability; } @Override public List<String> getLocalizedInfo() { return ImmutableList.of(formatDurability(extraDurability)); } @Override public List<String> getLocalizedDesc() { return ImmutableList.of(Util.translate(LOC_DurabilityDesc)); } public static String formatDurability(int durability) { return formatNumber(LOC_Durability, COLOR_Durability, durability); } }
true
434dea9a1b5c312ec593c1736832269811528f04
Java
lwlshawn/ip
/src/main/java/duke/TaskList.java
UTF-8
884
3.125
3
[]
no_license
package duke; import java.util.ArrayList; import duke.task.Task; /** * Class to manage the list of users tasks during an application run. Class is basically an alias for * Java's arraylist with a more limited interface, implemented due to course requirements. */ public class TaskList { private ArrayList<Task> tasks; public TaskList() { tasks = new ArrayList<>(); } /** * Constructor called when loading in data. * * @param loadedData loadedData is the TaskList from a previous session. */ public TaskList(ArrayList<Task> loadedData) { tasks = loadedData; } public int size() { return tasks.size(); } public Task get(int i) { return tasks.get(i); } public Task delete(int i) { return tasks.remove(i); } public void add(Task t) { tasks.add(t); } }
true
fc8c0e120fe954ee2ffd4c1d8a897b3597d67094
Java
Iskieria/super-computing-machine
/src/main/java/com/example/siobhan/trafficapp/MainActivity.java
UTF-8
3,775
2.390625
2
[]
no_license
package com.example.siobhan.trafficapp; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; public class MainActivity extends AppCompatActivity { private String sourceListingURL = "http://www.trafficscotland.org/rss/feeds/roadworks.aspx"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void roadworksData(View view) { Intent intent = new Intent(this, DisplayDataActivity.class); startActivity(intent); } // Method to handle the reading of the data from the XML stream private static String sourceListingString(String urlString)throws IOException { String result = ""; InputStream anInStream = null; int response = -1; URL url = new URL(urlString); URLConnection conn = url.openConnection(); // Check that the connection can be opened if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); try { // Open connection HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); // Check that connection is Ok if (response == HttpURLConnection.HTTP_OK) { // Connection is Ok so open a reader anInStream = httpConn.getInputStream(); InputStreamReader in= new InputStreamReader(anInStream); BufferedReader bin= new BufferedReader(in); // Read in the data from the RSS stream String line = new String(); // Read past the RSS headers bin.readLine(); bin.readLine(); // Keep reading until there is no more data while (( (line = bin.readLine())) != null) { result = result + "\n" + line; } } } catch (Exception ex) { throw new IOException("Error connecting"); } // Return result as a string for further processing return result; } // End of sourceListingString }
true
b79f9a299f123740fd530674009a70b6218cbc0c
Java
meetkiki/data-structure
/stack/src/main/java/MyQueue.java
UTF-8
1,063
4
4
[]
no_license
import java.util.Stack; /** * 用栈实现队列 */ class MyQueue { Stack<Integer> data1 = new Stack<>(); Stack<Integer> data2 = new Stack<>(); MyQueue() {} /** Push element x to the back of queue. */ void push(int x) { while (!data1.empty()) { data2.push(data1.peek()); data1.pop(); } data1.push(x); while (!data2.empty()) { data1.push(data2.peek()); data2.pop(); } } /** Removes the element from in front of queue and returns that element. */ int pop() { int val = data1.peek(); data1.pop(); return val; } /** Get the front element. */ int peek() { return data1.peek(); } /** Returns whether the queue is empty. */ boolean empty() { return data1.empty(); } public static void main(String[] args) { MyQueue myQueue = new MyQueue(); myQueue.push(1); int param_2 = myQueue.pop(); int param_3 = myQueue.peek(); boolean param_4 = myQueue.empty(); } }
true
b0ac3fa25af31b55bfba882f42f9ddb12ae8d8fa
Java
janscheidegger/mqtt-client
/src/main/java/mqttclient/MqttTestMain.java
UTF-8
860
2.265625
2
[]
no_license
package main.java.mqttclient; import main.java.mqttclient.mqtt.MqttAccessor; import org.eclipse.paho.client.mqttv3.MqttException; /** * mqqt-client * * @author jan */ public class MqttTestMain { public static void main(String[] args) { MqttAccessor mqttAccessor = MqttAccessor.getInstance(); try { mqttAccessor.subscribeTopic("tcp://iot.eclipse.org:1883", "jan/test", false); } catch (MqttException e) { e.printStackTrace(); } while(mqttAccessor.isCurrentlyListening()) { try { System.out.println(mqttAccessor.isCurrentlyListening()); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } mqttAccessor.disconnectAll(); System.exit(0); } }
true
8fb841dfe9f72eebbc05a140681ede4035b6e07b
Java
tusharsuthar4828/HomeMART
/app/src/main/java/com/homemart/models/CategoryToDisplay.java
UTF-8
356
2.328125
2
[]
no_license
package com.homemart.models; import com.thoughtbot.expandablerecyclerview.models.ExpandableGroup; import java.util.List; public class CategoryToDisplay extends ExpandableGroup<Product> { String mCategoryName; List<Product> mProductsList; public CategoryToDisplay(String title, List<Product> items) { super(title, items); } }
true
7ff970886bc53b4d799eb1a29387e7f86b76fff2
Java
nycjay/flyway
/flyway-sqlserver/src/main/java/org/flywaydb/database/sqlserver/synapse/SynapseTable.java
UTF-8
2,447
2.015625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) Red Gate Software Ltd 2010-2022 * * 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.flywaydb.database.sqlserver.synapse; import org.flywaydb.database.sqlserver.SQLServerDatabase; import org.flywaydb.database.sqlserver.SQLServerSchema; import org.flywaydb.database.sqlserver.SQLServerTable; import org.flywaydb.core.internal.database.InsertRowLock; import org.flywaydb.core.internal.jdbc.JdbcTemplate; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Calendar; import java.util.TimeZone; public class SynapseTable extends SQLServerTable { private final InsertRowLock insertRowLock; SynapseTable(JdbcTemplate jdbcTemplate, SQLServerDatabase database, String databaseName, SQLServerSchema schema, String name) { super(jdbcTemplate, database, databaseName, schema, name); this.insertRowLock = new InsertRowLock(jdbcTemplate, 10); } @Override protected void doLock() throws SQLException { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); Timestamp currentDateTime = new Timestamp(cal.getTime().getTime()); String updateLockStatement = "UPDATE " + this + " SET installed_on = '" + currentDateTime + "' WHERE version = '?' AND description = 'flyway-lock'"; String deleteExpiredLockStatement = "DELETE FROM " + this + " WHERE description = 'flyway-lock' AND installed_on < '?'"; if (lockDepth == 0) { insertRowLock.doLock(database.getInsertStatement(this), updateLockStatement, deleteExpiredLockStatement, database.getBooleanTrue()); } } @Override protected void doUnlock() throws SQLException { if (lockDepth == 1) { insertRowLock.doUnlock(getDeleteLockTemplate()); } } private String getDeleteLockTemplate() { return "DELETE FROM " + this + " WHERE version = '?' AND description = 'flyway-lock'"; } }
true
0434a751d5fdda86985369c57aec1b71dce17265
Java
lzl471954654/WanXiyouApp
/app/src/main/java/com/lzl/wanxiyouapp/Moudle/MoudleInterface/IXuptManagement.java
UTF-8
444
1.570313
2
[]
no_license
package com.lzl.wanxiyouapp.Moudle.MoudleInterface; import com.lzl.wanxiyouapp.CallBack; import okhttp3.Call; import okhttp3.Callback; /** * Created by LZL on 2017/7/20. */ public interface IXuptManagement { public void userLogon(String username,String password,String cookie); public void userLogon(String id,String password,String code,String cookie); public boolean checkPeEnable(); public void loadScretImage(); }
true
05138a261236387839b8cefa537dffd1b0c818db
Java
carlhume/summer-game-server
/src/main/java/com/tds/server/MapData.java
UTF-8
304
2.296875
2
[]
no_license
package com.tds.server; public class MapData { private Terrain terrain; public MapData() { this.terrain = new Terrain(); } public MapData( Terrain newTerrain ) { this.terrain = newTerrain; } public Terrain getTerrain() { return this.terrain; } }
true
47b4ad9174f86e4d95655d62fff04a551a49fba8
Java
imayavgi/ignite-exp
/src/main/java/uiak/exper/ignite/service/PriceService.java
UTF-8
192
1.796875
2
[]
no_license
package uiak.exper.ignite.service; import javax.cache.CacheException; /** * Created by imaya on 8/14/16. */ public interface PriceService { void updatePrice() throws CacheException; }
true
0a07dd5a49635266b8952e79f6cd1e8baa65f39a
Java
rshubhankar/crossover-test
/src/com/exam/config/ConfigurationChangeListener.java
UTF-8
4,060
2.875
3
[]
no_license
package com.exam.config; import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY; import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Check for changes in the configuration file. * * @author shubhankar_roy * */ class ConfigurationChangeListener implements Runnable { /** * logger instance */ private final Logger logger = LoggerFactory.getLogger(ConfigurationChangeListener.class); /** * Configuration file name. */ private String configFileName; /** * Configuration file absolute path. */ private final String fullFilePath; /** * Check if the application is still running. */ private boolean appRunning = true; /** * Constructor, which initializes with path of the configuration file. * * @param filePath */ public ConfigurationChangeListener(final String filePath) { this.fullFilePath = filePath; } public void run() { try { register(this.fullFilePath); } catch (IOException e) { e.printStackTrace(); } } /** * Register the configuration file. * * @param fileName * @throws IOException */ private void register(final String fileName) throws IOException { logger.info("Registering the configuration file: {}", fileName); File file = new File(fileName); String absolutePath = file.getAbsolutePath(); final int lastIndex = absolutePath.lastIndexOf(File.separatorChar); String dirPath = absolutePath.substring(0, lastIndex + 1); this.configFileName = fileName; if(file.exists()) { configurationChanged(fileName); startWatcher(dirPath, fileName); } else { logger.error("Properties File Does not Exists in path: {}, file name: {}", dirPath, fileName); } } /** * Starts watching the configuration file. * * @param dirPath * @param file * @throws IOException */ private void startWatcher(String dirPath, String file) throws IOException { logger.debug("Start watching the configuration file."); final WatchService watchService = FileSystems.getDefault() .newWatchService(); Path path = Paths.get(dirPath); path.register(watchService, ENTRY_MODIFY); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { watchService.close(); } catch (IOException e) { e.printStackTrace(); } } }); WatchKey key = null; while (appRunning) { try { key = watchService.poll(5000, TimeUnit.MILLISECONDS); if(key != null) { for (WatchEvent< ?> event : key.pollEvents()) { if (event.context().toString().equals(configFileName)) { configurationChanged(dirPath + file); } } boolean reset = key.reset(); if (!reset) { logger.debug("Could not reset the watch key."); break; } } } catch (Exception e) { logger.error("Exception occurred in watch service.", e); } } } /** * Shutdown WatchService. */ public void shutDown() { appRunning = false; } /** * Refresh the configurations. * * @param file */ public void configurationChanged(final String file) { logger.info("Refreshing the configuration."); ApplicationConfiguration.getInstance().initialize(file); } }
true