answer
stringlengths
15
1.25M
#ifndef <API key> #define <API key> #include <functional> #include <map> #include <string> #include <ncurses.h> #include "minibus/io/i_display.h" #include "minibus/io/key.h" #include "minibus/widgets/hotkeys.h" #include "minibus/widgets/widget.h" using namespace std; namespace minibus { class HotkeysSelect : public Hotkeys { public: template <typename... ARGS> HotkeysSelect(const string& name, ARGS... args) : Hotkeys(name, args...) { } virtual ~HotkeysSelect() {} virtual int keypress(const Key& key) { stringstream ss; if (_keys.count(key)) { toggle(key); return 0; } return 0; } virtual int render(IDisplay* win) { size_t pos = 0; size_t i = 0; for (auto &x : _keys) { stringstream ss; ss << "[" << (char) x.first.key() << ": " << x.second << "] "; if (!selected(x.first)) { win->write(0, pos, ss.str(), (i++ % 7) + 1); } else { win->write(0, pos, ss.str(), (i++ % 7) + 8); } pos += ss.str().length(); } return 0; } virtual bool selected(const Key& key) const { return _selected.count(key); } protected: virtual void toggle(const Key& key) { if (selected(key)) { _selected.erase(key); } else { _selected.insert(key); } } set<Key> _selected; }; } // namespace minibus #endif // <API key>
package hackerrank; import java.io.*; public class Solution { /** * popup sorting (assent) * @param integers * @return */ public static int[] sortPopup(int[] integers){ int [] sortedIntegers = new int[integers.length]; System.arraycopy(integers,0,sortedIntegers,0,integers.length); int arrayLength = sortedIntegers.length; for (int i = 0; i < arrayLength-1; i++) { int a = sortedIntegers[i]; for (int j = i+1; j < arrayLength; j++) { int b = sortedIntegers[j]; if(a > b){ sortedIntegers[i] = b; sortedIntegers[j] = a; a = b; } } } return sortedIntegers; } public static void main( String[] args ) throws <API key>,IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(in.readLine()); int K = Integer.parseInt(in.readLine()); int[] list = new int[N]; for(int i = 0; i < N; i ++) list[i] = Integer.parseInt(in.readLine()); int unfairness = Integer.MAX_VALUE; /* * Write your code here, to process numPackets N, numKids K, and the packets of candies * Compute the ideal value for unfairness over here */ int tempunfairness = 0; list = sortPopup(list); int length = list.length; System.out.printf(" "); for (int i = 0; i < length - K ; i++) { tempunfairness = list[K+i-1]-list[i]; if(unfairness > tempunfairness)unfairness = tempunfairness; } System.out.println(unfairness); } }
#!/bin/bash . $(dirname $0)/../testenv.sh source=$(curl -s -H "accept: text/uri-list" ${occi_srv}/collections/compute/ | head -1) target=$(curl -s -H "accept: text/uri-list" ${occi_srv}/collections/network/ | head -1) id=/store/mylinks/json/networkinterfaces/$(uuidgen) content=$(cat <<EOF { "links": [ { "kind": "http://schemas.ogf.org/occi/infrastructure#networkinterface", "mixins": [ "http://schemas.ogf.org/occi/infrastructure/networkinterface#ipnetworkinterface" ], "attributes": { "occi": { "networkinterface": { "interface": "eth0", "mac": "00:80:41:ae:fd:32", "address": "192.168.3.4", "gateway": "192.168.3.0", "allocation": "dynamic" } } }, "target": "${target}", "source": "${source}" } ] } EOF ) put 201 ${id} "application/json" "$content"
package com.bjlx.QinShihuang.core; import com.bjlx.QinShihuang.core.formatter.account.FavoriteFormatter; import com.bjlx.QinShihuang.core.formatter.account.UserInfoFormatter; import com.bjlx.QinShihuang.core.formatter.account.VoteFormatter; import com.bjlx.QinShihuang.core.formatter.activity.<API key>; import com.bjlx.QinShihuang.core.formatter.guide.GuideBasicFormatter; import com.bjlx.QinShihuang.core.formatter.im.<API key>; import com.bjlx.QinShihuang.core.formatter.marketplace.<API key>; import com.bjlx.QinShihuang.core.formatter.misc.<API key>; import com.bjlx.QinShihuang.core.formatter.misc.TravelNoteFormatter; import com.bjlx.QinShihuang.core.formatter.poi.HotelBasicFormatter; import com.bjlx.QinShihuang.core.formatter.poi.<API key>; import com.bjlx.QinShihuang.core.formatter.poi.<API key>; import com.bjlx.QinShihuang.core.formatter.poi.<API key>; import com.bjlx.QinShihuang.core.formatter.quora.<API key>; import com.bjlx.QinShihuang.core.formatter.timeline.<API key>; import com.bjlx.QinShihuang.core.formatter.trace.TraceBasicFormatter; import com.bjlx.QinShihuang.core.formatter.tripplan.<API key>; import com.bjlx.QinShihuang.model.account.Favorite; import com.bjlx.QinShihuang.model.account.PhoneNumber; import com.bjlx.QinShihuang.model.account.UserInfo; import com.bjlx.QinShihuang.model.account.Vote; import com.bjlx.QinShihuang.model.activity.Activity; import com.bjlx.QinShihuang.model.guide.Guide; import com.bjlx.QinShihuang.model.im.Chatgroup; import com.bjlx.QinShihuang.model.im.Post; import com.bjlx.QinShihuang.model.marketplace.Commodity; import com.bjlx.QinShihuang.model.misc.*; import com.bjlx.QinShihuang.model.poi.Hotel; import com.bjlx.QinShihuang.model.poi.Restaurant; import com.bjlx.QinShihuang.model.poi.Shopping; import com.bjlx.QinShihuang.model.poi.Viewspot; import com.bjlx.QinShihuang.model.quora.Answer; import com.bjlx.QinShihuang.model.quora.Question; import com.bjlx.QinShihuang.model.timeline.Moment; import com.bjlx.QinShihuang.model.trace.Trace; import com.bjlx.QinShihuang.model.tripplan.TripPlan; import com.bjlx.QinShihuang.requestmodel.TravelNoteReq; import com.bjlx.QinShihuang.utils.*; import com.fasterxml.jackson.databind.node.ObjectNode; import org.bson.types.ObjectId; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.query.Query; import org.mongodb.morphia.query.UpdateOperations; import java.util.ArrayList; import java.util.List; public class MiscAPI { private static Datastore ds = MorphiaFactory.getInstance(); /** * * @param userId id * @param key * @param tel * @return * @throws Exception */ public static String applySeller(Long userId, String key, String tel) throws Exception { try { if (!CommonAPI.checkKeyValid(userId, key)) { return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1013); } Query<Application> query = ds.createQuery(Application.class).field(Application.fd_userId).equal(userId).field(Application.fd_number).equal(tel); Application application = query.get(); if(application == null) { application = new Application(userId, new PhoneNumber(86, tel)); ds.save(application); } return QinShihuangResult.ok(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param offset * @param limit * @return * @throws Exception */ public static String getTravelNotes(Integer offset, Integer limit) throws Exception { try { Query<TravelNote> query = ds.createQuery(TravelNote.class).field(TravelNote.fd_status).equal(Constant.TRAVELNOTE_NORMAL).order(String.format("-%s", TravelNote.fd_publishTime)).offset(offset).limit(limit); List<TravelNote> travelNotes = query.asList(); if(travelNotes == null || travelNotes.isEmpty()) return QinShihuangResult.ok(<API key>.getMapper().valueToTree(new ArrayList<TravelNote>())); else return QinShihuangResult.ok(<API key>.getMapper().valueToTree(travelNotes)); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param travelNoteReq * @param userId id * @param key * @return * @throws Exception */ public static String addTravelNote(TravelNoteReq travelNoteReq, Long userId, String key) throws Exception { try { if (!CommonAPI.checkKeyValid(userId, key)) { return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1044); } UserInfo author = CommonAPI.getUserBasicById(userId); if(author == null) return QinShihuangResult.getResult(ErrorCode.USER_NOT_EXIST_1044); TravelNote travelNote = new TravelNote(travelNoteReq.getCover(), travelNoteReq.getImages(), travelNoteReq.getTitle(), author, travelNoteReq.getTravelTime(), travelNoteReq.getSummary() == null ? "" : travelNoteReq.getTitle()); if(travelNoteReq.getContents() != null && !travelNoteReq.getContents().isEmpty()) travelNote.setContents(travelNoteReq.getContents()); ds.save(travelNote); return QinShihuangResult.ok(TravelNoteFormatter.getMapper().valueToTree(travelNote)); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param travelNoteId id * @param travelNoteReq * @param userId id * @param key * @return * @throws Exception */ public static String updateTravelNote(String travelNoteId, TravelNoteReq travelNoteReq, Long userId, String key) throws Exception { try { if (!CommonAPI.checkKeyValid(userId, key)) { return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1045); } Query<TravelNote> query = ds.createQuery(TravelNote.class).field(TravelNote.fd_id).equal(new ObjectId(travelNoteId)).field(TravelNote.fd_authorId).equal(userId).field(TravelNote.fd_status).equal(Constant.TRAVELNOTE_NORMAL); UpdateOperations<TravelNote> ops = ds.<API key>(TravelNote.class); if(travelNoteReq.getContents() != null && !travelNoteReq.getContents().isEmpty()) ops.set(TravelNote.fd_contents, travelNoteReq.getContents()); if(travelNoteReq.getCover() != null) ops.set(TravelNote.fd_cover, travelNoteReq.getCover()); if(travelNoteReq.getImages() != null && !travelNoteReq.getImages().isEmpty()) ops.set(TravelNote.fd_images, travelNoteReq.getImages()); if(travelNoteReq.getSummary() != null) ops.set(TravelNote.fd_summary, travelNoteReq.getSummary()); if(travelNoteReq.getTitle() != null) ops.set(TravelNote.fd_title, travelNoteReq.getTitle()); if(travelNoteReq.getTravelTime() != null) ops.set(TravelNote.fd_travelTime, travelNoteReq.getTravelTime()); TravelNote travelNote = ds.findAndModify(query, ops, false); if(travelNote == null) return QinShihuangResult.getResult(ErrorCode.<API key>); else return QinShihuangResult.ok(TravelNoteFormatter.getMapper().valueToTree(travelNote)); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param travelNoteId id * @return * @throws Exception */ public static String getTravelNote(String travelNoteId) throws Exception { try { Query<TravelNote> query = ds.createQuery(TravelNote.class).field(TravelNote.fd_id).equal(new ObjectId(travelNoteId)).field(TravelNote.fd_status).equal(Constant.TRAVELNOTE_NORMAL); TravelNote travelNote = query.get(); if(travelNote == null) return QinShihuangResult.getResult(ErrorCode.<API key>); else return QinShihuangResult.ok(TravelNoteFormatter.getMapper().valueToTree(travelNote)); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param travelNoteId id * @param userId id * @param key * @return * @throws Exception */ public static String removeTravelNote(String travelNoteId, Long userId, String key) throws Exception { try { if (!CommonAPI.checkKeyValid(userId, key)) { return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1047); } Query<TravelNote> query = ds.createQuery(TravelNote.class).field(TravelNote.fd_id).equal(new ObjectId(travelNoteId)).field(TravelNote.fd_authorId).equal(userId) .field(TravelNote.fd_status).equal(Constant.TRAVELNOTE_NORMAL); UpdateOperations<TravelNote> ops = ds.<API key>(TravelNote.class).set(TravelNote.fd_status, Constant.TRAVELNOTE_UNENABLE); ds.updateFirst(query, ops); return QinShihuangResult.ok(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param userId id * @param key * @param offset * @param limit * @return * @throws Exception */ public static String getUserTravelNotes(Long userId, String key, Integer offset, Integer limit) throws Exception { try { if (!CommonAPI.checkKeyValid(userId, key)) { return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1048); } Query<TravelNote> query = ds.createQuery(TravelNote.class).field(TravelNote.fd_authorId).equal(userId) .field(TravelNote.fd_status).equal(Constant.TRAVELNOTE_NORMAL).order(String.format("-%s", TravelNote.fd_publishTime)).offset(offset).limit(limit); List<TravelNote> travelNotes = query.asList(); if(travelNotes == null || travelNotes.isEmpty()) return QinShihuangResult.ok(<API key>.getMapper().valueToTree(new ArrayList<TravelNote>())); else return QinShihuangResult.ok(<API key>.getMapper().valueToTree(travelNotes)); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param userId id * @param key * @param content * @param origin App, * @return * @throws Exception */ public static String feedback(Long userId, String key, String content, String origin) throws Exception { try { if (!CommonAPI.checkKeyValid(userId, key)) { return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1014); } Feedback feedback = new Feedback(userId, content, System.currentTimeMillis(), origin); ds.save(feedback); return QinShihuangResult.ok(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param userId id * @param key * @param query * @return */ public static String searchUser(Long userId, String key, String query) throws Exception { try { if (!CommonAPI.checkKeyValid(userId, key)) { return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1107); } Query<UserInfo> queryUser = ds.createQuery(UserInfo.class).field(UserInfo.fd_status).equal(Constant.USER_NORMAL); if(CommonUtil.isEmail(query)) { UserInfo userInfo = queryUser.field(UserInfo.fd_email).equal(query).get(); if(userInfo != null) return QinShihuangResult.ok(UserInfoFormatter.getMapper().valueToTree(userInfo)); else return QinShihuangResult.getResult(ErrorCode.USER_NOT_EXIST_1107); } if(CommonUtil.isTelLegal(query)) { UserInfo userInfo = queryUser.field(UserInfo.fd_number).equal(query).get(); if(userInfo != null) return QinShihuangResult.ok(UserInfoFormatter.getMapper().valueToTree(userInfo)); } if(CommonUtil.isLongDigit(query)) { Long uid = Long.getLong(query); UserInfo userInfo = queryUser.field(UserInfo.fd_userId).equal(uid).get(); if(userInfo != null) return QinShihuangResult.ok(UserInfoFormatter.getMapper().valueToTree(userInfo)); else return QinShihuangResult.getResult(ErrorCode.USER_NOT_EXIST_1107); } else { return QinShihuangResult.getResult(ErrorCode.QUERY_INVALID_1107); } } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param userId id * @param key * @param query * @return */ public static String searchChatgroup(Long userId, String key, String query) throws Exception { try { if (!CommonAPI.checkKeyValid(userId, key)) { return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1108); } List<Chatgroup> chatgroups = new ArrayList<Chatgroup>(); if(CommonUtil.isLongDigit(query)) { Long chatgroupId = Long.getLong(query); Chatgroup chatgroup = ds.createQuery(Chatgroup.class).field(Chatgroup.fd_chatGroupId).equal(chatgroupId).field(Chatgroup.fd_status).equal(Constant.CHATGROUP_NORMAL).get(); if(chatgroup != null) chatgroups.add(chatgroup); } List<Chatgroup> chatgroupList = ds.createQuery(Chatgroup.class).field(Chatgroup.fd_name).<API key>(query).field(Chatgroup.fd_status).equal(Constant.CHATGROUP_NORMAL).asList(); if(chatgroupList != null) { for(Chatgroup chatgroup : chatgroupList) chatgroups.add(chatgroup); } return QinShihuangResult.ok(<API key>.getMapper().valueToTree(chatgroups)); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param isAll * @param query * @return * @throws Exception */ public static List<Moment> queryMoments(Boolean isAll, String query) throws Exception { try { if(isAll) return ds.createQuery(Moment.class).field(Moment.fd_comment).containsIgnoreCase(query).offset(Constant.SEARCH_ALL_OFFSET) .limit(Constant.SEARCH_ALL_LIMIT).order(String.format("-%s", Moment.fd_publishTime)).asList(); else return ds.createQuery(Moment.class).field(Moment.fd_comment).containsIgnoreCase(query).offset(Constant.<API key>) .limit(Constant.<API key>).order(String.format("-%s", Moment.fd_publishTime)).asList(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param isAll * @param query * @return * @throws Exception */ public static List<Commodity> queryCommodities(Boolean isAll, String query) throws Exception { try { if(isAll) return ds.createQuery(Commodity.class).field(Commodity.fd_title).containsIgnoreCase(query).offset(Constant.SEARCH_ALL_OFFSET) .limit(Constant.SEARCH_ALL_LIMIT).order(String.format("-%s", Commodity.fd_updateTime)).asList(); else return ds.createQuery(Commodity.class).field(Commodity.fd_title).containsIgnoreCase(query).offset(Constant.<API key>) .limit(Constant.<API key>).order(String.format("-%s", Commodity.fd_updateTime)).asList(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param isAll * @param query * @return * @throws Exception */ public static List<Guide> queryGuides(Boolean isAll, String query) throws Exception { try { if(isAll) return ds.createQuery(Guide.class).field(Guide.fd_title).containsIgnoreCase(query).offset(Constant.SEARCH_ALL_OFFSET) .limit(Constant.SEARCH_ALL_LIMIT).order(String.format("-%s", Guide.fd_updateTime)).asList(); else return ds.createQuery(Guide.class).field(Guide.fd_title).containsIgnoreCase(query).offset(Constant.<API key>) .limit(Constant.<API key>).order(String.format("-%s", Guide.fd_updateTime)).asList(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param isAll * @param query * @return * @throws Exception */ public static List<Viewspot> queryViewspots(Boolean isAll, String query) throws Exception { try { if(isAll) return ds.createQuery(Viewspot.class).field(Viewspot.fd_zhName).containsIgnoreCase(query).offset(Constant.SEARCH_ALL_OFFSET) .limit(Constant.SEARCH_ALL_LIMIT).order(String.format("-%s", Viewspot.fd_hotness)).asList(); else return ds.createQuery(Viewspot.class).field(Viewspot.fd_zhName).containsIgnoreCase(query).offset(Constant.<API key>) .limit(Constant.<API key>).order(String.format("-%s", Viewspot.fd_hotness)).asList(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param isAll * @param query * @return * @throws Exception */ public static List<Trace> queryTraces(Boolean isAll, String query) throws Exception { try { if(isAll) return ds.createQuery(Trace.class).field(Trace.fd_title).containsIgnoreCase(query).offset(Constant.SEARCH_ALL_OFFSET) .limit(Constant.SEARCH_ALL_LIMIT).order(String.format("-%s", Trace.fd_updateTime)).asList(); else return ds.createQuery(Trace.class).field(Trace.fd_title).containsIgnoreCase(query).offset(Constant.<API key>) .limit(Constant.<API key>).order(String.format("-%s", Trace.fd_updateTime)).asList(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param isAll * @param query * @return * @throws Exception */ public static List<TripPlan> queryTripPlans(Boolean isAll, String query) throws Exception { try { if(isAll) return ds.createQuery(TripPlan.class).field(TripPlan.fd_title).containsIgnoreCase(query).offset(Constant.SEARCH_ALL_OFFSET) .limit(Constant.SEARCH_ALL_LIMIT).order(String.format("-%s", TripPlan.fd_updateTime)).asList(); else return ds.createQuery(TripPlan.class).field(TripPlan.fd_title).containsIgnoreCase(query).offset(Constant.<API key>) .limit(Constant.<API key>).order(String.format("-%s", TripPlan.fd_updateTime)).asList(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param isAll * @param query * @return * @throws Exception */ public static List<Question> queryQuestions(Boolean isAll, String query) throws Exception { try { if(isAll) return ds.createQuery(Question.class).field(Question.fd_title).containsIgnoreCase(query).offset(Constant.SEARCH_ALL_OFFSET) .limit(Constant.SEARCH_ALL_LIMIT).order(String.format("-%s", Question.fd_publishTime)).asList(); else return ds.createQuery(Question.class).field(Question.fd_title).containsIgnoreCase(query).offset(Constant.<API key>) .limit(Constant.<API key>).order(String.format("-%s", Question.fd_publishTime)).asList(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param isAll * @param query * @return * @throws Exception */ public static List<Activity> queryActivities(Boolean isAll, String query) throws Exception { try { if(isAll) return ds.createQuery(Activity.class).field(Activity.fd_title).containsIgnoreCase(query).offset(Constant.SEARCH_ALL_OFFSET) .limit(Constant.SEARCH_ALL_LIMIT).order(String.format("-%s", Activity.fd_endTime)).asList(); else return ds.createQuery(Activity.class).field(Activity.fd_title).containsIgnoreCase(query).offset(Constant.<API key>) .limit(Constant.<API key>).order(String.format("-%s", Activity.fd_endTime)).asList(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param isAll * @param query * @return * @throws Exception */ public static List<TravelNote> queryTravelNotes(Boolean isAll, String query) throws Exception { try { if(isAll) return ds.createQuery(TravelNote.class).field(TravelNote.fd_title).containsIgnoreCase(query).offset(Constant.SEARCH_ALL_OFFSET) .limit(Constant.SEARCH_ALL_LIMIT).order(String.format("-%s", TravelNote.fd_publishTime)).asList(); else return ds.createQuery(TravelNote.class).field(TravelNote.fd_title).containsIgnoreCase(query).offset(Constant.<API key>) .limit(Constant.<API key>).order(String.format("-%s", TravelNote.fd_publishTime)).asList(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param isAll * @param query * @return * @throws Exception */ public static List<Restaurant> queryRestaurants(Boolean isAll, String query) throws Exception { try { if(isAll) return ds.createQuery(Restaurant.class).field(Restaurant.fd_zhName).containsIgnoreCase(query).offset(Constant.SEARCH_ALL_OFFSET) .limit(Constant.SEARCH_ALL_LIMIT).order(String.format("-%s", Restaurant.fd_hotness)).asList(); else return ds.createQuery(Restaurant.class).field(Restaurant.fd_zhName).containsIgnoreCase(query).offset(Constant.<API key>) .limit(Constant.<API key>).order(String.format("-%s", Restaurant.fd_hotness)).asList(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param isAll * @param query * @return * @throws Exception */ public static List<Hotel> queryHotels(Boolean isAll, String query) throws Exception { try { if(isAll) return ds.createQuery(Hotel.class).field(Hotel.fd_zhName).containsIgnoreCase(query).offset(Constant.SEARCH_ALL_OFFSET) .limit(Constant.SEARCH_ALL_LIMIT).order(String.format("-%s", Hotel.fd_hotness)).asList(); else return ds.createQuery(Hotel.class).field(Hotel.fd_zhName).containsIgnoreCase(query).offset(Constant.<API key>) .limit(Constant.<API key>).order(String.format("-%s", Hotel.fd_hotness)).asList(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param isAll * @param query * @return * @throws Exception */ public static List<Shopping> queryShoppings(Boolean isAll, String query) throws Exception { try { if(isAll) return ds.createQuery(Shopping.class).field(Shopping.fd_zhName).containsIgnoreCase(query).offset(Constant.SEARCH_ALL_OFFSET) .limit(Constant.SEARCH_ALL_LIMIT).order(String.format("-%s", Shopping.fd_hotness)).asList(); else return ds.createQuery(Shopping.class).field(Shopping.fd_zhName).containsIgnoreCase(query).offset(Constant.SEARCH_ALL_OFFSET) .limit(Constant.SEARCH_ALL_LIMIT).order(String.format("-%s", Shopping.fd_hotness)).asList(); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param query * @return * @throws Exception */ public static String searchAll(String query) throws Exception { ObjectNode result = CommonAPI.mapper.createObjectNode(); try { List<Moment> moments = queryMoments(true, query); if(moments != null) result.set("moments", <API key>.getMapper().valueToTree(moments)); List<Commodity> commodities = queryCommodities(true, query); if(commodities != null) result.set("commodities", <API key>.getMapper().valueToTree(commodities)); List<Guide> guides = queryGuides(true, query); if(guides != null) result.set("guides", GuideBasicFormatter.getMapper().valueToTree(guides)); List<Viewspot> viewspots = queryViewspots(true, query); if(viewspots != null) result.set("viewspots", <API key>.getMapper().valueToTree(viewspots)); List<Trace> traces = queryTraces(true, query); if(traces != null) result.set("traces", TraceBasicFormatter.getMapper().valueToTree(traces)); List<TripPlan> tripPlans = queryTripPlans(true, query); if(tripPlans != null) result.set("tripPlans", <API key>.getMapper().valueToTree(tripPlans)); List<Question> questions = queryQuestions(true, query); if(questions != null) result.set("quoras", <API key>.getMapper().valueToTree(questions)); List<Activity> activities = queryActivities(true, query); if(activities != null) result.set("activities", <API key>.getMapper().valueToTree(activities)); List<TravelNote> travelNotes = queryTravelNotes(true, query); if(travelNotes != null) result.set("travelNotes", <API key>.getMapper().valueToTree(travelNotes)); List<Restaurant> restaurants = queryRestaurants(true, query); if(restaurants != null) result.set("restaurants", <API key>.getMapper().valueToTree(restaurants)); List<Hotel> hotels = queryHotels(true, query); if(hotels != null) result.set("hotels", HotelBasicFormatter.getMapper().valueToTree(hotels)); List<Shopping> shoppings = queryShoppings(true, query); if(shoppings != null) result.set("shoppings", <API key>.getMapper().valueToTree(shoppings)); return QinShihuangResult.ok(result); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param query * @param momemt * @param commodity * @param guide * @param viewspot * @param trace * @param tripPlan * @param quora * @param activity * @param travelNote * @param restaurant * @param hotel * @param shopping * @return * @throws Exception */ public static String searchCondition(String query , Boolean momemt, Boolean commodity, Boolean guide, Boolean viewspot, Boolean trace, Boolean tripPlan, Boolean quora, Boolean activity, Boolean travelNote, Boolean restaurant, Boolean hotel, Boolean shopping) throws Exception { ObjectNode result = CommonAPI.mapper.createObjectNode(); try { if(momemt) { List<Moment> moments = queryMoments(false, query); if (moments != null) result.set("moments", <API key>.getMapper().valueToTree(moments)); } if(commodity) { List<Commodity> commodities = queryCommodities(false, query); if (commodities != null) result.set("commodities", <API key>.getMapper().valueToTree(commodities)); } if(guide) { List<Guide> guides = queryGuides(false, query); if (guides != null) result.set("guides", GuideBasicFormatter.getMapper().valueToTree(guides)); } if(viewspot) { List<Viewspot> viewspots = queryViewspots(false, query); if (viewspots != null) result.set("viewspots", <API key>.getMapper().valueToTree(viewspots)); } if(trace) { List<Trace> traces = queryTraces(false, query); if (traces != null) result.set("traces", TraceBasicFormatter.getMapper().valueToTree(traces)); } if(tripPlan) { List<TripPlan> tripPlans = queryTripPlans(false, query); if (tripPlans != null) result.set("tripPlans", <API key>.getMapper().valueToTree(tripPlans)); } if(quora) { List<Question> questions = queryQuestions(false, query); if (questions != null) result.set("quoras", <API key>.getMapper().valueToTree(questions)); } if(activity) { List<Activity> activities = queryActivities(false, query); if (activities != null) result.set("activities", <API key>.getMapper().valueToTree(activities)); } if(travelNote) { List<TravelNote> travelNotes = queryTravelNotes(false, query); if (travelNotes != null) result.set("travelNotes", <API key>.getMapper().valueToTree(travelNotes)); } if(restaurant) { List<Restaurant> restaurants = queryRestaurants(false, query); if (restaurants != null) result.set("restaurants", <API key>.getMapper().valueToTree(restaurants)); } if(hotel) { List<Hotel> hotels = queryHotels(false, query); if (hotels != null) result.set("hotels", HotelBasicFormatter.getMapper().valueToTree(hotels)); } if(shopping) { List<Shopping> shoppings = queryShoppings(false, query); if (shoppings != null) result.set("shoppings", <API key>.getMapper().valueToTree(shoppings)); } return QinShihuangResult.ok(result); } catch (Exception e) { e.printStackTrace(); throw e; } } /** * * @param itemId id * @param favoriteType * @param isAdd true1false1 * @throws Exception */ public static void updateFavorCnt(String itemId, Integer favoriteType, Boolean isAdd) throws Exception { try { switch (favoriteType) { case Constant.FAVORITE_POST: Query<Post> queryPost = ds.createQuery(Post.class).field(Post.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Post> opsPost = ds.<API key>(Post.class); if (isAdd) opsPost.inc(Post.fd_favorCnt); else opsPost.dec(Post.fd_favorCnt); ds.updateFirst(queryPost, opsPost); break; case Constant.FAVORITE_TRACE: Query<Trace> queryTrace = ds.createQuery(Trace.class).field(Trace.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Trace> opsTrace = ds.<API key>(Trace.class); if (isAdd) opsTrace.inc(Trace.fd_favorCnt); else opsTrace.dec(Trace.fd_favorCnt); ds.updateFirst(queryTrace, opsTrace); break; case Constant.FAVORITE_TRIPPLAN: Query<TripPlan> queryTripPlan = ds.createQuery(TripPlan.class).field(TripPlan.fd_id).equal(new ObjectId(itemId)); UpdateOperations<TripPlan> opsTripPlan = ds.<API key>(TripPlan.class); if (isAdd) opsTripPlan.inc(TripPlan.fd_favorCnt); else opsTripPlan.dec(TripPlan.fd_favorCnt); ds.updateFirst(queryTripPlan, opsTripPlan); break; case Constant.FAVORITE_ACTIVITY: Query<Activity> queryActivity = ds.createQuery(Activity.class).field(Activity.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Activity> opsActivity = ds.<API key>(Activity.class); if (isAdd) opsActivity.inc(Activity.fd_favorCnt); else opsActivity.dec(Activity.fd_favorCnt); ds.updateFirst(queryActivity, opsActivity); break; case Constant.FAVORITE_QUORA: Query<Question> queryQuestion = ds.createQuery(Question.class).field(Question.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Question> opsQuestion = ds.<API key>(Question.class); if (isAdd) opsQuestion.inc(Question.fd_favorCnt); else opsQuestion.dec(Question.fd_favorCnt); ds.updateFirst(queryQuestion, opsQuestion); break; case Constant.FAVORITE_RESTAURANT: Query<Restaurant> queryRestaurant = ds.createQuery(Restaurant.class).field(Restaurant.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Restaurant> opsRestaurant = ds.<API key>(Restaurant.class); if (isAdd) opsRestaurant.inc(Restaurant.fd_favorCnt); else opsRestaurant.dec(Restaurant.fd_favorCnt); ds.updateFirst(queryRestaurant, opsRestaurant); break; case Constant.FAVORITE_HOTEL: Query<Hotel> queryHotel = ds.createQuery(Hotel.class).field(Hotel.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Hotel> opsHotel = ds.<API key>(Hotel.class); if (isAdd) opsHotel.inc(Hotel.fd_favorCnt); else opsHotel.dec(Hotel.fd_favorCnt); ds.updateFirst(queryHotel, opsHotel); break; case Constant.FAVORITE_TRAVELNOTE: Query<TravelNote> queryTravelNote = ds.createQuery(TravelNote.class).field(TravelNote.fd_id).equal(new ObjectId(itemId)); UpdateOperations<TravelNote> opsTravelNote = ds.<API key>(TravelNote.class); if (isAdd) opsTravelNote.inc(TravelNote.fd_favorCnt); else opsTravelNote.dec(TravelNote.fd_favorCnt); ds.updateFirst(queryTravelNote, opsTravelNote); break; case Constant.FAVORITE_VIEWSPOT: Query<Viewspot> queryViewspot = ds.createQuery(Viewspot.class).field(Viewspot.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Viewspot> opsViewspot = ds.<API key>(Viewspot.class); if (isAdd) opsViewspot.inc(Viewspot.fd_favorCnt); else opsViewspot.dec(Viewspot.fd_favorCnt); ds.updateFirst(queryViewspot, opsViewspot); break; case Constant.FAVORITE_SHOPPING: Query<Shopping> queryShopping = ds.createQuery(Shopping.class).field(Shopping.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Shopping> opsShopping = ds.<API key>(Shopping.class); if (isAdd) opsShopping.inc(Shopping.fd_favorCnt); else opsShopping.dec(Shopping.fd_favorCnt); ds.updateFirst(queryShopping, opsShopping); break; case Constant.FAVORITE_MOMENT: Query<Moment> queryMoment = ds.createQuery(Moment.class).field(Moment.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Moment> opsMoment = ds.<API key>(Moment.class); if (isAdd) opsMoment.inc(Moment.fd_favorCnt); else opsMoment.dec(Moment.fd_favorCnt); ds.updateFirst(queryMoment, opsMoment); break; case Constant.FAVORITE_COMMODITY: Query<Commodity> queryCommodity = ds.createQuery(Commodity.class).field(Commodity.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Commodity> opsCommodity = ds.<API key>(Commodity.class); if (isAdd) opsCommodity.inc(Commodity.fd_favorCnt); else opsCommodity.dec(Commodity.fd_favorCnt); ds.updateFirst(queryCommodity, opsCommodity); break; } } catch(Exception e) { e.printStackTrace(); throw e; } } /** * * @param userId id * @param key * @param favoriteType * @param itemId id * @param authorId id * @param authorNickName * @param authorAvatar * @param cover * @param title * @return * @throws Exception */ public static String addFavorite(Long userId, String key, Integer favoriteType, String itemId, Long authorId, String authorNickName, ImageItem authorAvatar, ImageItem cover, String title) throws Exception { try { if (!CommonAPI.checkKeyValid(userId, key)) { return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1098); } if(!Constant.checkFavoriteType(favoriteType)) { return QinShihuangResult.getResult(ErrorCode.<API key>); } if(!CommonAPI.isObjectId(itemId)) { return QinShihuangResult.getResult(ErrorCode.ITEMID_INVALID_1098); } Query<Favorite> query = ds.createQuery(Favorite.class).field(Favorite.fd_userId).equal(userId).field(Favorite.fd_itemId).equal(new ObjectId(itemId)); UpdateOperations<Favorite> ops = ds.<API key>(Favorite.class).set(Favorite.fd_id, new ObjectId()).set(Favorite.fd_userId, userId).set(Favorite.fd_favoriteType, favoriteType) .set(Favorite.fd_itemId, new ObjectId(itemId)).set(Favorite.fd_title, title).set(Favorite.fd_favoriteTime, System.currentTimeMillis()); if(authorId != null) ops.set(Favorite.fd_authorId, authorId); if(authorNickName != null) ops.set(Favorite.fd_authorNickName, authorNickName); if(authorAvatar != null) ops.set(Favorite.fd_authorAvatar, authorAvatar); if(cover != null) ops.set(Favorite.fd_cover, cover); Favorite favorite = ds.findAndModify(query, ops, false, true); updateFavorCnt(itemId, favoriteType, true); return QinShihuangResult.ok(FavoriteFormatter.getMapper().valueToTree(favorite)); } catch (Exception e) { throw e; } } /** * * @param itemId id * @param voteType * @param isAdd true1false1 * @throws Exception */ public static void updateVoteCnt(String itemId, Integer voteType, Boolean isAdd) throws Exception { try { switch (voteType) { case Constant.VOTE_POST: Query<Post> queryPost = ds.createQuery(Post.class).field(Post.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Post> opsPost = ds.<API key>(Post.class); if (isAdd) opsPost.inc(Post.fd_voteCnt); else opsPost.dec(Post.fd_voteCnt); ds.updateFirst(queryPost, opsPost); break; case Constant.VOTE_TRACE: Query<Trace> queryTrace = ds.createQuery(Trace.class).field(Trace.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Trace> opsTrace = ds.<API key>(Trace.class); if (isAdd) opsTrace.inc(Trace.fd_voteCnt); else opsTrace.dec(Trace.fd_voteCnt); ds.updateFirst(queryTrace, opsTrace); break; case Constant.VOTE_TRIPPLAN: Query<TripPlan> queryTripPlan = ds.createQuery(TripPlan.class).field(TripPlan.fd_id).equal(new ObjectId(itemId)); UpdateOperations<TripPlan> opsTripPlan = ds.<API key>(TripPlan.class); if (isAdd) opsTripPlan.inc(TripPlan.fd_voteCnt); else opsTripPlan.dec(TripPlan.fd_voteCnt); ds.updateFirst(queryTripPlan, opsTripPlan); break; case Constant.VOTE_ACTIVITY: Query<Activity> queryActivity = ds.createQuery(Activity.class).field(Activity.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Activity> opsActivity = ds.<API key>(Activity.class); if (isAdd) opsActivity.inc(Activity.fd_voteCnt); else opsActivity.dec(Activity.fd_voteCnt); ds.updateFirst(queryActivity, opsActivity); break; case Constant.VOTE_QUESTION: Query<Question> queryQuestion = ds.createQuery(Question.class).field(Question.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Question> opsQuestion = ds.<API key>(Question.class); if (isAdd) opsQuestion.inc(Question.fd_voteCnt); else opsQuestion.dec(Question.fd_voteCnt); ds.updateFirst(queryQuestion, opsQuestion); break; case Constant.VOTE_ANSWER: Query<Answer> queryAnswer = ds.createQuery(Answer.class).field(Answer.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Answer> opsAnswer = ds.<API key>(Answer.class); if (isAdd) opsAnswer.inc(Answer.fd_voteCnt); else opsAnswer.dec(Answer.fd_voteCnt); ds.updateFirst(queryAnswer, opsAnswer); break; case Constant.VOTE_MOMENT: Query<Moment> queryMoment = ds.createQuery(Moment.class).field(Moment.fd_id).equal(new ObjectId(itemId)); UpdateOperations<Moment> opsMoment = ds.<API key>(Moment.class); if (isAdd) opsMoment.inc(Moment.fd_voteCnt); else opsMoment.dec(Moment.fd_voteCnt); ds.updateFirst(queryMoment, opsMoment); break; case Constant.VOTE_TRAVELNOTE: Query<TravelNote> queryTravelNote = ds.createQuery(TravelNote.class).field(TravelNote.fd_id).equal(new ObjectId(itemId)); UpdateOperations<TravelNote> opsTravelNote = ds.<API key>(TravelNote.class); if (isAdd) opsTravelNote.inc(TravelNote.fd_voteCnt); else opsTravelNote.dec(TravelNote.fd_voteCnt); ds.updateFirst(queryTravelNote, opsTravelNote); break; } } catch(Exception e) { e.printStackTrace(); throw e; } } /** * * @param userId id * @param key * @param itemId id * @param favoriteType * @return * @throws Exception */ public static String cancelFavorite(Long userId, String key, String itemId, Integer favoriteType) throws Exception { try { if (!CommonAPI.checkKeyValid(userId, key)) { return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1099); } Query<Favorite> query = ds.createQuery(Favorite.class).field(Favorite.fd_userId).equal(userId).field(Favorite.fd_itemId).equal(new ObjectId(itemId)); ds.delete(query); updateFavorCnt(itemId, favoriteType, false); return QinShihuangResult.ok(); } catch (Exception e) { throw e; } } /** * * @param userId id * @param key * @return * @throws Exception */ public static String getFavorites(Long userId, String key) throws Exception { try { if (!CommonAPI.checkKeyValid(userId, key)) { return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1100); } Query<Favorite> query = ds.createQuery(Favorite.class).field(Favorite.fd_userId).equal(userId); List<Favorite> favorites = query.asList(); if(favorites == null) return QinShihuangResult.ok(FavoriteFormatter.getMapper().valueToTree(new ArrayList<Favorite>())); else return QinShihuangResult.ok(FavoriteFormatter.getMapper().valueToTree(favorites)); } catch (Exception e) { throw e; } } /** * * @param userId id * @param key * @param voteType * @param itemId id * @return * @throws Exception */ public static String addVote(Long userId, String key, Integer voteType, String itemId) throws Exception { try { if (!CommonAPI.checkKeyValid(userId, key)) { return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1101); } if(!Constant.checkVoteType(voteType)) { return QinShihuangResult.getResult(ErrorCode.<API key>); } if(!CommonAPI.isObjectId(itemId)) { return QinShihuangResult.getResult(ErrorCode.ITEMID_INVALID_1101); } Query<Vote> query = ds.createQuery(Vote.class).field(Vote.fd_userId).equal(userId).field(Vote.fd_itemId).equal(new ObjectId(itemId)); UpdateOperations<Vote> ops = ds.<API key>(Vote.class).set(Vote.fd_id, new ObjectId()).set(Vote.fd_userId, userId).set(Vote.fd_voteType, voteType) .set(Vote.fd_itemId, new ObjectId(itemId)).set(Vote.fd_voteTime, System.currentTimeMillis()); ds.updateFirst(query, ops, true); updateVoteCnt(itemId, voteType, true); // TODO return QinShihuangResult.ok(); } catch (Exception e) { throw e; } } /** * * @param userId id * @param key * @param itemId id * @param voteType * @return * @throws Exception */ public static String cancelVote(Long userId, String key, String itemId, Integer voteType) throws Exception { try { if (!CommonAPI.checkKeyValid(userId, key)) { return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1102); } Query<Vote> query = ds.createQuery(Vote.class).field(Vote.fd_userId).equal(userId).field(Vote.fd_itemId).equal(new ObjectId(itemId)); ds.delete(query); updateVoteCnt(itemId, voteType, false); return QinShihuangResult.ok(); } catch (Exception e) { throw e; } } /** * * @param userId id * @param key * @return * @throws Exception */ public static String getVotes(Long userId, String key) throws Exception { try { if (!CommonAPI.checkKeyValid(userId, key)) { return QinShihuangResult.getResult(ErrorCode.UNLOGIN_1103); } Query<Vote> query = ds.createQuery(Vote.class).field(Vote.fd_userId).equal(userId); List<Vote> votes = query.asList(); if(votes == null) return QinShihuangResult.ok(VoteFormatter.getMapper().valueToTree(new ArrayList<Vote>())); else return QinShihuangResult.ok(VoteFormatter.getMapper().valueToTree(votes)); } catch (Exception e) { throw e; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Demo1.Models { public class BlogModel { public string Title { get; set; } public string Content { get; set; } } }
package source; public enum TopEnum { FOO, BAR }
package com.ctrip.framework.cs.configuration; import com.ctrip.framework.cs.configuration.Configuration; import com.ctrip.framework.cs.configuration.<API key>; import com.ctrip.framework.cs.configuration.<API key>; import com.ctrip.framework.cs.util.IOUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.net.URL; import java.util.HashMap; import java.util.Properties; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import static org.junit.Assert.*; public class <API key> { public <API key>(){ <API key>.<API key>(false); } @Test public void testNoConfig(){ try { <API key>.<API key>(true); <API key>.setConfigPath("config1/"); Configuration config = <API key>.getConfigInstance(); }catch (Exception e) { Assert.fail(); }finally { <API key>.<API key>(false); } } @Test public void <API key>(){ <API key>.<API key>(true); System.out.println(<API key>.class.getProtectionDomain().getCodeSource().getLocation().toString()); URL url = getClass().getProtectionDomain().getCodeSource().getLocation(); try { InputStream in = <API key>.class.getClassLoader().getResourceAsStream("jar:"+url.toURI().toString()+"!/META-INF/MANIFEST.MF"); System.out.println(url.toURI().toString()); System.out.println(in); ZipInputStream zip = new ZipInputStream(url.openStream()); ZipEntry ze; while ((ze = zip.getNextEntry())!=null){ if(ze.getName().equals("META-INF/MANIFEST.MF")){ System.out.println(ze.getName()); break; } } System.out.println(IOUtils.readAll(zip)); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //assertNotNull(<API key>.getConfigInstance().getString("app.sso.url")); <API key>.<API key>(false); } @Test public void testLoadProperties() throws Exception { <API key>.<API key>("test.properties"); assertEquals("9", <API key>.getConfigInstance().getProperty("com.ctrip.config.samples.needCount")); assertEquals("9", <API key>.getConfigInstance().getString("com.ctrip.config.samples.needCount")); assertEquals("100", <API key>.getConfigInstance().getString("no.exist","100")); } @Test public void <API key>() throws Exception { Configuration config = <API key>.getConfigInstance(); double val = 12.3; config.setProperty("test-double",val); assertTrue(val == config.getDouble("test-double")); config.setProperty("test-int",10); assertTrue(10 == config.getDouble("test-int")); assertTrue(0 == config.getDouble("test-int-emp")); assertTrue(20 == config.getInt("test-int-emp",20)); assertTrue(new Integer(23) == config.getInt("test-int-emp",new Integer(23))); assertEquals(false,config.getBoolean("test-boolean")); } @Test public void <API key>() throws Exception { <API key>.getConfigInstance().clear(); <API key>.<API key>("test.properties"); assertEquals("", <API key>.getConfigInstance().getProperty("chinese")); } @Test public void <API key>() throws Exception { <API key>.<API key>("config/test"); assertEquals("7", <API key>.getConfigInstance().getProperty("com.ctrip.config.samples.needCount")); assertEquals("1", <API key>.getConfigInstance().getProperty("cascaded.property")); } @Test public void testInstallReadOnly() throws <API key> { Properties pros = new Properties(); pros.setProperty("hello","world"); <API key>.<API key>(pros); assertEquals("world",<API key>.getConfigInstance().getString("#.hello")); <API key>.setProperties(new HashMap<String, String>(){{ put("#.hello", "abc"); }},"root"); assertEquals("world", <API key>.getConfigInstance().getString("#.hello")); } }
package net.cpollet.itinerants.web.context; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.neo4j.repository.config.<API key>; import org.springframework.transaction.annotation.<API key>; @Configuration @<API key> @<API key>(basePackages = "net.cpollet.itinerants.da.neo4j") @EntityScan(basePackages = "net.cpollet.itinerants.da.neo4j") public class Neo4jContext { // nothing }
veneer("veneer-timer", { events: { remove: function(e){ clearTimeout(e.target._timer); }, update: function(e){ var elm=e.target, delay = +elm.interval || 80 , code=elm.getAttribute("onchange"); if(!code) return; elm.cancel=function(){clearInterval(elm._timer);}; var FN=Function("event", "with(this){"+code+"}").bind(elm, e); clearInterval(elm._timer); return elm._timer=setTimeout(function(){ elm._timer= window[elm.repeat ? "setInterval" : "setTimeout"]( FN, delay ); }, elm.delay||0 ); } }, props: { onchange: veneer.k, repeat: veneer.bool, interval: Number, delay: Number, num: Number, str: String, bool: veneer.bool, a: veneer.k, b: veneer.k }, defaults: { str: "" }, css: "veneer-timer {display:inline;}" });
<?php namespace Magento\Bundle\Pricing\Price; use Magento\Catalog\Pricing\Price\RegularPrice; /** * Bundle tier prices model */ class TierPrice extends \Magento\Catalog\Pricing\Price\TierPrice implements <API key> { /** * @var bool */ protected $filterByBasePrice = false; /** * @var float|false */ protected $percent; /** * Returns percent discount * * @return bool|float */ public function getDiscountPercent() { if ($this->percent === null) { $percent = parent::getValue(); $this->percent = ($percent) ? max(0, min(100, 100 - $percent)) : null; } return $this->percent; } /** * Returns pricing value * * @return bool|float */ public function getValue() { if ($this->value !== null) { return $this->value; } $tierPrice = $this->getDiscountPercent(); if ($tierPrice) { $regularPrice = $this->getRegularPrice(); $this->value = $regularPrice * ($tierPrice / 100); } else { $this->value = false; } return $this->value; } /** * Returns regular price * * @return bool|float */ protected function getRegularPrice() { return $this->priceInfo->getPrice(RegularPrice::PRICE_CODE)->getValue(); } /** * Returns true if first price is better * * Method filters tiers price values, higher discount value is better * * @param float $firstPrice * @param float $secondPrice * @return bool */ protected function isFirstPriceBetter($firstPrice, $secondPrice) { return $firstPrice > $secondPrice; } /** * @return bool */ public function <API key>() { return true; } }
package avans.ivh11a1.facturatie.domain.billing.State; import avans.ivh11a1.facturatie.domain.billing.Invoice; import java.util.Date; public class PendingState implements State { @Override public void doAction(Invoice i) { i.setState(InvoiceState.PAID); i.setDatePayed(new Date()); } @Override public String currentState() { return "The invoice was pending"; } }
// UIImage+Alpha.h // Free for personal or commercial use, with or without modification. // NOTE: TitaniumCalendar modified to convert from Category to // new Class name since iPhone seems to have some issues with Categories // of built in Classes // Helper methods for adding an alpha layer to an image @interface UIImageAlpha : NSObject { } + (BOOL)hasAlpha:(UIImage*)image; + (UIImage *)imageWithAlpha:(UIImage*)image; + (UIImage *)<API key>:(NSUInteger)borderSize image:(UIImage*)image; @end
package cz.cesnet.meta.pbs; public class TextWithCount implements Comparable<TextWithCount> { private String text; private int pocet; public TextWithCount(String text, int pocet) { this.text = text; this.pocet = pocet; } @Override public int compareTo(TextWithCount o) { return o.pocet - this.pocet; } public String getText() { return text; } public int getPocet() { return pocet; } }
package com.nortal.lorque; /** * @author Vassili Jakovlev */ public enum QueryStatus { SUBMITTED, CANCELLED, RUNNING, COMPLETED, FAILED, CALLBACK_FAILED; }
package bayesGame.ui; import javax.swing.JPanel; public class ResolutionSelection extends JPanel { }
package org.vaadin.appbase.event; import lombok.extern.slf4j.Slf4j; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.<API key>; import com.google.common.eventbus.<API key>; import org.springframework.stereotype.Component; import org.vaadin.spring.UIScope; @Component @UIScope @Slf4j public class AppEventBus implements IEventBus { private static final long serialVersionUID = <API key>; private EventBus eventbus; public AppEventBus() { eventbus = new EventBus(new <API key>() { @Override public void handleException(Throwable exception, <API key> context) { log.error("Could not dispatch event: " + context.getSubscriber() + " to " + context.getSubscriberMethod()); exception.printStackTrace(); } }); } @Override public void post(IEvent event) { if (log.isTraceEnabled()) { log.trace(event.getSource() + " posted event: " + event); } eventbus.post(event); } @Override public void register(Object listener) { if (log.isTraceEnabled()) { log.trace("Registering event bus listener: " + listener); } eventbus.register(listener); } @Override public void unregister(Object listener) { if (log.isTraceEnabled()) { log.trace("Removing listener from event bus: " + listener); } eventbus.unregister(listener); } }
// YR_NewArtsAuthModel.h // Artand #import "YR_BaseModel.h" @class <API key>; @interface YR_NewArtsAuthModel : YR_BaseModel @property (nonatomic, copy) NSString *type; //@property (nonatomic, strong) <API key> *extral; @end
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Mon Mar 03 10:44:38 EST 2014 --> <title>Uses of Class org.hibernate.type.<API key> (Hibernate JavaDocs)</title> <meta name="date" content="2014-03-03"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.hibernate.type.<API key> (Hibernate JavaDocs)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../org/hibernate/type/<API key>.html" title="class in org.hibernate.type">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/hibernate/type/class-use/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class org.hibernate.type.<API key>" class="title">Uses of Class<br>org.hibernate.type.<API key></h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../org/hibernate/type/<API key>.html" title="class in org.hibernate.type"><API key></a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.hibernate.type">org.hibernate.type</a></td> <td class="colLast"> <div class="block"><div class="paragraph"></div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.hibernate.type"> </a> <h3>Uses of <a href="../../../../org/hibernate/type/<API key>.html" title="class in org.hibernate.type"><API key></a> in <a href="../../../../org/hibernate/type/package-summary.html">org.hibernate.type</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../org/hibernate/type/package-summary.html">org.hibernate.type</a> declared as <a href="../../../../org/hibernate/type/<API key>.html" title="class in org.hibernate.type"><API key></a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/hibernate/type/<API key>.html" title="class in org.hibernate.type"><API key></a></code></td> <td class="colLast"><span class="strong"><API key>.</span><code><strong><a href="../../../../org/hibernate/type/<API key>.html#INSTANCE">INSTANCE</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../org/hibernate/type/<API key>.html" title="class in org.hibernate.type"><API key></a></code></td> <td class="colLast"><span class="strong"><API key>.</span><code><strong><a href="../../../../org/hibernate/type/<API key>.html#INSTANCE">INSTANCE</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../org/hibernate/type/<API key>.html" title="class in org.hibernate.type"><API key></a></code></td> <td class="colLast"><span class="strong"><API key>.</span><code><strong><a href="../../../../org/hibernate/type/<API key>.html#INSTANCE">INSTANCE</a></strong></code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../org/hibernate/type/<API key>.html" title="class in org.hibernate.type">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/hibernate/type/class-use/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small>Copyright &copy; 2001-2014 <a href="http: </body> </html>
"""This exists only as a test harness for examining slightly non-trivial coverage output.""" import sys from collections import defaultdict def calculate_answer(a, b): return a * b def the_answer(): return calculate_answer( 6, 7, )
package info.ipeanut.youngnews.ui.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import info.ipeanut.youngnews.ui.base.BaseFragment; public class VoteFragment extends BaseFragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } }
require 'test_helper' class <API key> < ActionController::TestCase setup do @plant = plants(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:plants) end test "should get new" do get :new assert_response :success end test "should create plant" do assert_difference('Plant.count') do post :create, plant: { name: @plant.name, profile: @plant.profile } end <API key> plant_path(assigns(:plant)) end test "should show plant" do get :show, id: @plant assert_response :success end test "should get edit" do get :edit, id: @plant assert_response :success end test "should update plant" do patch :update, id: @plant, plant: { name: @plant.name, profile: @plant.profile } <API key> plant_path(assigns(:plant)) end test "should destroy plant" do assert_difference('Plant.count', -1) do delete :destroy, id: @plant end <API key> plants_path end end
FROM fedora RUN dnf -y update && dnf install -y make git golang <API key> \ # storage deps btrfs-progs-devel \ device-mapper-devel \ # gpgme bindings deps libassuan-devel gpgme-devel \ ostree-devel \ gnupg \ # OpenShift deps which tar wget hostname util-linux bsdtar socat ethtool device-mapper iptables tree findutils nmap-ncat e2fsprogs xfsprogs lsof docker iproute \ && dnf clean all # Install two versions of the registry. The first is an older version that # only supports schema1 manifests. The second is a newer version that supports # both. This allows integration-cli tests to cover push/pull with both schema1 # and schema2 manifests. RUN set -x \ && <API key>=<SHA1-like> \ && REGISTRY_COMMIT=<SHA1-like> \ && export GOPATH="$(mktemp -d)" \ && git clone https://github.com/docker/distribution.git "$GOPATH/src/github.com/docker/distribution" \ && (cd "$GOPATH/src/github.com/docker/distribution" && git checkout -q "$REGISTRY_COMMIT") \ && GOPATH="$GOPATH/src/github.com/docker/distribution/Godeps/_workspace:$GOPATH" \ go build -o /usr/local/bin/registry-v2 github.com/docker/distribution/cmd/registry \ && (cd "$GOPATH/src/github.com/docker/distribution" && git checkout -q "$<API key>") \ && GOPATH="$GOPATH/src/github.com/docker/distribution/Godeps/_workspace:$GOPATH" \ go build -o /usr/local/bin/registry-v2-schema1 github.com/docker/distribution/cmd/registry \ && rm -rf "$GOPATH" RUN set -x \ && export GOPATH=$(mktemp -d) \ && git clone --depth 1 -b v1.5.0-alpha.3 git://github.com/openshift/origin "$GOPATH/src/github.com/openshift/origin" \ && sed -i -e 's/\[\[ "\${go_version\[2]}" < "go1.5" ]]/false/' "$GOPATH/src/github.com/openshift/origin/hack/common.sh" \ && (cd "$GOPATH/src/github.com/openshift/origin" && make clean build && make all WHAT=cmd/dockerregistry) \ && cp -a "$GOPATH/src/github.com/openshift/origin/_output/local/bin/linux"/*/* /usr/local/bin \ && cp "$GOPATH/src/github.com/openshift/origin/images/dockerregistry/config.yml" /<API key>.yml \ && rm -rf "$GOPATH" \ && mkdir /registry ENV GOPATH /usr/share/gocode:/go ENV PATH $GOPATH/bin:/usr/share/gocode/bin:$PATH RUN go get github.com/golang/lint/golint WORKDIR /go/src/github.com/containers/skopeo COPY . /go/src/github.com/containers/skopeo #ENTRYPOINT ["hack/dind"]
package dao import ( "bytes" "context" xsql "database/sql" "fmt" "strconv" "time" "go-common/app/job/main/coupon/model" "go-common/library/database/sql" "go-common/library/xstr" "github.com/pkg/errors" ) const ( _updateStateSQL = "UPDATE `coupon_info_%02d` SET `state` = ?,`use_ver` = ?,`ver` = ? WHERE `coupon_token` = ? AND `ver` = ?;" _couponByTokenSQL = "SELECT `id`,`coupon_token`,`mid`,`state`,`start_time`,`expire_time`,`origin`,`coupon_type`,`order_no`,`oid`,`remark`,`use_ver`,`ver`,`ctime`,`mtime` FROM `coupon_info_%02d` WHERE `coupon_token` = ?;" _couponsSQL = "SELECT `id`,`coupon_token`,`mid`,`state`,`start_time`,`expire_time`,`origin`,`coupon_type`,`order_no`,`oid`,`remark`,`use_ver`,`ver`,`ctime`,`mtime` FROM `coupon_info_%02d` WHERE `state` = ? AND `mtime` > ?;" <API key> = "INSERT INTO `coupon_change_log_%02d` (`coupon_token`,`mid`,`state`,`ctime`) VALUES(?,?,?,?);" // balance coupon _byOrderNoSQL = "SELECT `id`,`order_no`,`mid`,`count`,`state`,`coupon_type`,`third_trade_no`,`remark`,`tips`,`use_ver`,`ver`,`ctime`,`mtime` FROM `coupon_order` WHERE `order_no` = ?;" _updateOrderSQL = "UPDATE `coupon_order` SET `state` = ?,`use_ver` =?,`ver` = ? WHERE `order_no` = ? AND `ver` = ?;" _addOrderLogSQL = "INSERT INTO `coupon_order_log`(`order_no`,`mid`,`state`,`ctime`)VALUES(?,?,?,?);" <API key> = "SELECT `id`,`order_no`,`mid`,`batch_token`,`balance`,`change_balance`,`change_type`,`ctime`,`mtime` FROM `<API key>%02d` WHERE `order_no` = ? AND `change_type` = ?;" <API key> = "SELECT `id`,`batch_token`,`mid`,`balance`,`start_time`,`expire_time`,`origin`,`coupon_type`,`ver`,`ctime`,`mtime` FROM `<API key>%02d` WHERE `mid` = ? AND `batch_token` = ? ;" _inPayOrderSQL = "SELECT `id`,`order_no`,`mid`,`count`,`state`,`coupon_type`,`third_trade_no`,`remark`,`tips`,`use_ver`,`ver`,`ctime`,`mtime` FROM `coupon_order` WHERE `state` = ? AND `mtime` > ?;" _batchUpdateBalance = "UPDATE `<API key>%02d` SET `ver` =`ver` + 1, `balance` = CASE id" _addBalanceLogSQL = "INSERT INTO `<API key>%02d`(`order_no`,`mid`,`batch_token`,`balance`,`change_balance`,`change_type`,`ctime`)VALUES " _couponBlancesSQL = "SELECT `id`,`batch_token`,`mid`,`balance`,`start_time`,`expire_time`,`origin`,`coupon_type`,`ver`,`ctime`,`mtime` FROM `<API key>%02d` WHERE `mid` = ? AND `coupon_type` = ?;" _updateBlanceSQL = "UPDATE `<API key>%02d` SET `balance` = ?,`ver` = `ver` + 1 WHERE `id` = ? AND `ver` = ?;" _updateUserCardSQL = "UPDATE coupon_user_card SET state=? WHERE mid=? AND coupon_token=? AND batch_token=?" ) func hitInfo(mid int64) int64 { return mid % 100 } func hitChangeLog(mid int64) int64 { return mid % 100 } func hitUser(mid int64) int64 { return mid % 10 } func hitUserLog(mid int64) int64 { return mid % 10 } // UpdateCoupon update coupon in use. func (d *Dao) UpdateCoupon(c context.Context, tx *sql.Tx, mid int64, state int8, useVer int64, ver int64, couponToken string) (a int64, err error) { var res xsql.Result if res, err = tx.Exec(fmt.Sprintf(_updateStateSQL, hitInfo(mid)), state, useVer, ver+1, couponToken, ver); err != nil { err = errors.WithStack(err) return } if a, err = res.RowsAffected(); err != nil { err = errors.WithStack(err) return } return } // CouponInfo coupon info. func (d *Dao) CouponInfo(c context.Context, mid int64, token string) (r *model.CouponInfo, err error) { var row *sql.Row r = &model.CouponInfo{} row = d.db.QueryRow(c, fmt.Sprintf(_couponByTokenSQL, hitInfo(mid)), token) if err = row.Scan(&r.ID, &r.CouponToken, &r.Mid, &r.State, &r.StartTime, &r.ExpireTime, &r.Origin, &r.CouponType, &r.OrderNO, &r.Oid, &r.Remark, &r.UseVer, &r.Ver, &r.CTime, &r.MTime); err != nil { if err == xsql.ErrNoRows { err = nil r = nil return } err = errors.WithStack(err) return } return } // CouponList query . func (d *Dao) CouponList(c context.Context, index int64, state int8, t time.Time) (res []*model.CouponInfo, err error) { var rows *sql.Rows if rows, err = d.db.Query(c, fmt.Sprintf(_couponsSQL, hitInfo(index)), state, t); err != nil { err = errors.WithStack(err) return } defer rows.Close() for rows.Next() { r := &model.CouponInfo{} if err = rows.Scan(&r.ID, &r.CouponToken, &r.Mid, &r.State, &r.StartTime, &r.ExpireTime, &r.Origin, &r.CouponType, &r.OrderNO, &r.Oid, &r.Remark, &r.UseVer, &r.Ver, &r.CTime, &r.MTime); err != nil { err = errors.WithStack(err) res = nil return } res = append(res, r) } err = rows.Err() return } //InsertPointHistory . func (d *Dao) InsertPointHistory(c context.Context, tx *sql.Tx, l *model.CouponChangeLog) (a int64, err error) { var res xsql.Result if res, err = tx.Exec(fmt.Sprintf(<API key>, hitChangeLog(l.Mid)), l.CouponToken, l.Mid, l.State, l.Ctime); err != nil { err = errors.WithStack(err) return } if a, err = res.RowsAffected(); err != nil { err = errors.WithStack(err) } return } // BeginTran begin transaction. func (d *Dao) BeginTran(c context.Context) (*sql.Tx, error) { return d.db.Begin(c) } // ByOrderNo query order by order no. func (d *Dao) ByOrderNo(c context.Context, orderNo string) (r *model.CouponOrder, err error) { var row *sql.Row r = &model.CouponOrder{} row = d.db.QueryRow(c, _byOrderNoSQL, orderNo) if err = row.Scan(&r.ID, &r.OrderNo, &r.Mid, &r.Count, &r.State, &r.CouponType, &r.ThirdTradeNo, &r.Remark, &r.Tips, &r.UseVer, &r.Ver, &r.Ctime, &r.Mtime); err != nil { if err == sql.ErrNoRows { err = nil r = nil return } err = errors.WithStack(err) return } return } // UpdateOrderState update order state. func (d *Dao) UpdateOrderState(c context.Context, tx *sql.Tx, mid int64, state int8, useVer int64, ver int64, orderNo string) (a int64, err error) { var res xsql.Result if res, err = tx.Exec(_updateOrderSQL, state, useVer, ver+1, orderNo, ver); err != nil { err = errors.WithStack(err) return } if a, err = res.RowsAffected(); err != nil { err = errors.WithStack(err) return } return } // AddOrderLog add order log. func (d *Dao) AddOrderLog(c context.Context, tx *sql.Tx, o *model.CouponOrderLog) (a int64, err error) { var res xsql.Result if res, err = tx.Exec(_addOrderLogSQL, o.OrderNo, o.Mid, o.State, o.Ctime); err != nil { err = errors.WithStack(err) return } if a, err = res.RowsAffected(); err != nil { err = errors.WithStack(err) } return } // ConsumeCouponLog consume coupon log. func (d *Dao) ConsumeCouponLog(c context.Context, mid int64, orderNo string, ct int8) (rs []*model.<API key>, err error) { var rows *sql.Rows if rows, err = d.db.Query(c, fmt.Sprintf(<API key>, hitUserLog(mid)), orderNo, ct); err != nil { err = errors.WithStack(err) return } defer rows.Close() for rows.Next() { r := &model.<API key>{} if err = rows.Scan(&r.ID, &r.OrderNo, &r.Mid, &r.BatchToken, &r.Balance, &r.ChangeBalance, &r.ChangeType, &r.Ctime, &r.Mtime); err != nil { err = errors.WithStack(err) rs = nil return } rs = append(rs, r) } err = rows.Err() return } // ByMidAndBatchToken query coupon by batch token and mid. func (d *Dao) ByMidAndBatchToken(c context.Context, mid int64, batchToken string) (r *model.CouponBalanceInfo, err error) { var row *sql.Row r = &model.CouponBalanceInfo{} row = d.db.QueryRow(c, fmt.Sprintf(<API key>, hitUser(mid)), mid, batchToken) if err = row.Scan(&r.ID, &r.BatchToken, &r.Mid, &r.Balance, &r.StartTime, &r.ExpireTime, &r.Origin, &r.CouponType, &r.Ver, &r.CTime, &r.MTime); err != nil { if err == sql.ErrNoRows { err = nil r = nil return } err = errors.WithStack(err) return } return } // UpdateBlance update blance. func (d *Dao) UpdateBlance(c context.Context, tx *sql.Tx, id int64, mid int64, ver int64, balance int64) (a int64, err error) { var res xsql.Result if res, err = tx.Exec(fmt.Sprintf(_updateBlanceSQL, hitUser(mid)), balance, id, ver); err != nil { err = errors.WithStack(err) return } if a, err = res.RowsAffected(); err != nil { err = errors.WithStack(err) return } return } // OrderInPay order in pay. func (d *Dao) OrderInPay(c context.Context, state int8, t time.Time) (res []*model.CouponOrder, err error) { var rows *sql.Rows if rows, err = d.db.Query(c, _inPayOrderSQL, state, t); err != nil { err = errors.WithStack(err) return } defer rows.Close() for rows.Next() { r := &model.CouponOrder{} if err = rows.Scan(&r.ID, &r.OrderNo, &r.Mid, &r.Count, &r.State, &r.CouponType, &r.ThirdTradeNo, &r.Remark, &r.Tips, &r.UseVer, &r.Ver, &r.Ctime, &r.Mtime); err != nil { if err == sql.ErrNoRows { err = nil res = nil return } err = errors.WithStack(err) return } res = append(res, r) } err = rows.Err() return } // BatchUpdateBlance batch update blance. func (d *Dao) BatchUpdateBlance(c context.Context, tx *sql.Tx, mid int64, blances []*model.CouponBalanceInfo) (a int64, err error) { var ( res xsql.Result buf bytes.Buffer ids []int64 ) buf.WriteString(fmt.Sprintf(_batchUpdateBalance, hitUser(mid))) for _, v := range blances { buf.WriteString(" WHEN ") buf.WriteString(strconv.FormatInt(v.ID, 10)) buf.WriteString(" THEN ") buf.WriteString(strconv.FormatInt(v.Balance, 10)) ids = append(ids, v.ID) } buf.WriteString(" END WHERE `id` in (") buf.WriteString(xstr.JoinInts(ids)) buf.WriteString(") AND `ver` = CASE id ") for _, v := range blances { buf.WriteString(" WHEN ") buf.WriteString(strconv.FormatInt(v.ID, 10)) buf.WriteString(" THEN ") buf.WriteString(strconv.FormatInt(v.Ver, 10)) } buf.WriteString(" END;") if res, err = tx.Exec(buf.String()); err != nil { err = errors.WithStack(err) return } if a, err = res.RowsAffected(); err != nil { err = errors.WithStack(err) return } return } // <API key> Batch Insert Balance log func (d *Dao) <API key>(c context.Context, tx *sql.Tx, mid int64, ls []*model.<API key>) (a int64, err error) { var ( buf bytes.Buffer res xsql.Result sql string ) buf.WriteString(fmt.Sprintf(_addBalanceLogSQL, hitUserLog(mid))) for _, v := range ls { buf.WriteString("('") buf.WriteString(v.OrderNo) buf.WriteString("',") buf.WriteString(strconv.FormatInt(v.Mid, 10)) buf.WriteString(",'") buf.WriteString(v.BatchToken) buf.WriteString("',") buf.WriteString(strconv.FormatInt(v.Balance, 10)) buf.WriteString(",") buf.WriteString(strconv.FormatInt(v.ChangeBalance, 10)) buf.WriteString(",") buf.WriteString(strconv.Itoa(int(v.ChangeType))) buf.WriteString(",'") buf.WriteString(fmt.Sprintf("%v", v.Ctime.Time().Format("2006-01-02 15:04:05"))) buf.WriteString("'),") } sql = buf.String() if res, err = tx.Exec(sql[0 : len(sql)-1]); err != nil { err = errors.WithStack(err) return } if a, err = res.RowsAffected(); err != nil { err = errors.WithStack(err) } return } // BlanceList user balance by mid. func (d *Dao) BlanceList(c context.Context, mid int64, ct int8) (res []*model.CouponBalanceInfo, err error) { var rows *sql.Rows if rows, err = d.db.Query(c, fmt.Sprintf(_couponBlancesSQL, hitUser(mid)), mid, ct); err != nil { err = errors.WithStack(err) return } defer rows.Close() for rows.Next() { r := &model.CouponBalanceInfo{} if err = rows.Scan(&r.ID, &r.BatchToken, &r.Mid, &r.Balance, &r.StartTime, &r.ExpireTime, &r.Origin, &r.CouponType, &r.Ver, &r.CTime, &r.MTime); err != nil { err = errors.WithStack(err) res = nil return } res = append(res, r) } err = rows.Err() return } // UpdateUserCard . func (d *Dao) UpdateUserCard(c context.Context, mid int64, state int8, couponToken, batchToken string) (a int64, err error) { var res xsql.Result if res, err = d.db.Exec(c, _updateUserCardSQL, state, mid, couponToken, batchToken); err != nil { err = errors.WithStack(err) return } if a, err = res.RowsAffected(); err != nil { err = errors.WithStack(err) return } return }
package ru.stqa.pft.addressbook.Task9.appmanager; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class NavigationHelper extends BaseHelper { public NavigationHelper(WebDriver wd) { super(wd); } public void gotoHomePage() { if (isElementPresent(By.id("maintable"))) { return; } click (By.linkText("home")); } public void gotoAddContactPage() { if (isElementPresent(By.tagName("h1")) && wd.findElement(By.tagName("h1")).getText().equals("Edit / add address book entry")){ return; } click(By.linkText("add new")); } public void gotoGroupsPage() { if (isElementPresent(By.tagName("h1")) && wd.findElement(By.tagName("h1")).getText().equals("Groups") && isElementPresent(By.name("new"))) { return; } click(By.linkText("groups")); } public void gotoEditGroupsPage() { if (isElementPresent(By.tagName("h1")) && wd.findElement(By.tagName("h1")).getText().equals("Groups") && isElementPresent(By.name("update"))) { return; } gotoGroupsPage(); click(By.name("edit")); } public void gotoNewGroupsPage() { if (isElementPresent(By.tagName("h1")) && wd.findElement(By.tagName("h1")).getText().equals("Groups") && isElementPresent(By.name("submit"))) { return; } gotoGroupsPage(); click(By.name("new")); } public void <API key>() { if (isElementPresent(By.tagName("h1")) && wd.findElement(By.tagName("h1")).getText().equals("Next birthdays")){ return; } click(By.linkText("next birthdays")); } public void gotoPrintAllPage() { click(By.linkText("print all")); } public void gotoPrintPhonesPage() { click(By.linkText("print phones")); } public void gotoMapPage() { click(By.linkText("map")); } public void gotoExportPage() { if (isElementPresent(By.tagName("h1")) && wd.findElement(By.tagName("h1")).getText().equals("Export")){ return; } click(By.linkText("export")); } public void gotoImportPage() { if (isElementPresent(By.tagName("h1")) && wd.findElement(By.tagName("h1")).getText().equals("Import")){ return; } click(By.linkText("import")); } public void backToPreviousPage() { wd.navigate().back(); } public void selection() { click(By.name("selected[]")); } }
package com.github.jankroken.commandline.error; import com.github.jankroken.commandline.ParseResult; import com.github.jankroken.commandline.domain.<API key>; import com.github.jankroken.commandline.domain.<API key>; import com.github.jankroken.commandline.domain.<API key>; import org.junit.jupiter.api.Test; import static com.github.jankroken.commandline.CommandLineParser.parse; import static com.github.jankroken.commandline.CommandLineParser.tryParse; import static com.github.jankroken.commandline.OptionStyle.SIMPLE; import static com.github.jankroken.commandline.util.Constants.EMPTY_STRING_ARRAY; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class <API key> { @Test public void testMissingSwitches() { var args = EMPTY_STRING_ARRAY; assertThatThrownBy(() -> parse(<API key>.class, args, SIMPLE)) .isInstanceOf(<API key>.class); } @Test public void <API key>() { var args = new String[]{"-invalidswitch", "-filename", "hello.txt"}; assertThatThrownBy(() -> parse(<API key>.class, args, SIMPLE)) .isInstanceOf(<API key>.class); } @Test public void <API key>() { var args = EMPTY_STRING_ARRAY; var result = tryParse(<API key>.class, args, SIMPLE); assertThat(result.isSuccess()).isFalse(); assertThat(result.getErrorType()).isEqualTo(ParseResult.ErrorType.<API key>); } @Test public void <API key>() { var args = new String[]{"-invalidswitch", "-filename", "hello.txt"}; assertThatThrownBy(() -> tryParse(<API key>.class, args, SIMPLE).get()) .isInstanceOf(<API key>.class); } }
# ssh-tunnel-server ## Variables # Source ports list SOURCE_PORTS="22 80" # Remote ports (a kind of prefix), example (calculation): $REMOTE_PORTS + $SOURCE_PORT = 10022 REMOTE_PORTS=10000 # Remote server bind to (e.g 0.0.0.0) REMOTE_BIND=localhost REMOTE_HOST=remote.example.com REMOTE_USER=robot ## Initial (master) server setup Use root or other fully privileged user account (with sudo) sh git clone https://github.com/1it/ssh-tunnel-server.git sh cd ssh-tunnel-server; ./server-bootstrap.sh ## Initial client setup sh git clone https://github.com/1it/ssh-tunnel-server.git sh cd ssh-tunnel-server; SOURCE_PORTS="22 80" REMOTE_HOST="remote.example.com" ./client-bootstrap.sh You will see the ssh-rsa key line in script stdout and this message: "Put the below key to the master server file: /home/$REMOTE_USER/.ssh/authorized_keys" So, copy this line and paste it to the master server's /home/robot/.ssh/authorized_keys file. And that's all. You can check that the cron-job file created: sh cat /etc/cron.d/ssh-tunnel */5 * * * * robot /home/$REMOTE_USER/ssh-tunnel start To manually stop the tunnel: sh cd /home/robot; ./ssh-tunnel stop
require 'pathname' Puppet::Type.type(:x509_cert).provide(:openssl) do desc 'Manages certificates with OpenSSL' commands :openssl => 'openssl' def self.private_key(resource) file = File.read(resource[:private_key]) if resource[:authentication] == :dsa OpenSSL::PKey::DSA.new(file, resource[:password]) elsif resource[:authentication] == :rsa OpenSSL::PKey::RSA.new(file, resource[:password]) else raise Puppet::Error, "Unknown authentication type '#{resource[:authentication]}'" end end def self.check_private_key(resource) cert = OpenSSL::X509::Certificate.new(File.read(resource[:path])) priv = self.private_key(resource) cert.check_private_key(priv) end def self.old_cert_is_equal(resource) cert = OpenSSL::X509::Certificate.new(File.read(resource[:path])) altName = '' cert.extensions.each do |ext| altName = ext.value if ext.oid == 'subjectAltName' end cdata = {} cert.subject.to_s.split('/').each do |name| k,v = name.split('=') cdata[k] = v end require 'inifile' ini_file = IniFile.load(resource[:template]) ini_file.each do |section, parameter, value| return false if parameter == 'subjectAltName' and value.delete(' ').gsub(/^"|"$/, '') != altName.delete(' ').gsub(/^"|"$/, '') return false if parameter == 'commonName' and value != cdata['CN'] end return true end def exists? if Pathname.new(resource[:path]).exist? if resource[:force] and !self.class.check_private_key(resource) return false end if !self.class.old_cert_is_equal(resource) return false end return true else return false end end def create options = [ 'req', '-config', resource[:template], '-new', '-x509', '-days', resource[:days], '-key', resource[:private_key], '-out', resource[:path], ] options << ['-passin', "pass:#{resource[:password]}",] if resource[:password] options << ['-extensions', "req_ext",] if resource[:req_ext] != :false openssl options end def destroy Pathname.new(resource[:path]).delete end end
package com.orbitz.monitoring.lib.processor; import java.util.Date; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; import org.mockito.Mockito; import com.orbitz.monitoring.api.Attribute; import com.orbitz.monitoring.api.Monitor; import com.orbitz.monitoring.api.monitor.AbstractMonitor; import com.orbitz.monitoring.api.monitor.TransactionMonitor; import com.orbitz.monitoring.lib.processor.<API key>.<API key>; import com.orbitz.monitoring.lib.processor.<API key>.GapHandler; public class <API key> extends TestCase { private <API key> processor; private GapHandler handler; private long latency; protected void setUp() throws Exception { handler = Mockito.mock(GapHandler.class); processor = new <API key>(handler); latency = processor.getThreshold() + 5; } public void testDefaults() { <API key> processor = new <API key>(); assertTrue(processor.getGapHandler() instanceof <API key>); } public void testNotTransaction() { Monitor monitor = new AbstractMonitor() {}; processor.process(monitor); Mockito.<API key>(handler); } public void <API key>() { TransactionMonitor monitor = new TransactionMonitor("Test"){}; monitor.set(Attribute.LATENCY, 0); processor.process(monitor); Mockito.<API key>(handler); } public void <API key>() { Date parentStart = new Date(); Date parentEnd = new Date(parentStart.getTime() + latency); TransactionMonitor parent = createParent(parentStart, parentEnd); parent.set(Attribute.LATENCY, latency); processor.process(parent); Mockito.verify(handler).handleGap(parent, null, null, latency); } public void <API key>() { Date parentStart = new Date(); Date parentEnd = new Date(parentStart.getTime() + latency); Date childStart = new Date(parentEnd.getTime() - 5); Date childEnd = parentEnd; TransactionMonitor parent = createParent(parentStart, parentEnd); addChild(parent, childStart, childEnd); parent.set(Attribute.LATENCY, latency); processor.process(parent); Mockito.<API key>(handler); } public void <API key>() { Date parentStart = new Date(); Date parentEnd = new Date(parentStart.getTime() + latency); Date childStart = new Date(parentEnd.getTime() - 1); Date childEnd = parentEnd; TransactionMonitor parent = createParent(parentStart, parentEnd); TransactionMonitor child = addChild(parent, childStart, childEnd); parent.set(Attribute.LATENCY, latency); processor.process(parent); Mockito.verify(handler).handleGap(parent, null, child, latency - 1); } public void <API key>() { Date parentStart = new Date(); Date parentEnd = new Date(parentStart.getTime() + latency); Date childStart = parentStart; Date childEnd = new Date(parentStart.getTime() + 1); TransactionMonitor parent = createParent(parentStart, parentEnd); TransactionMonitor child = addChild(parent, childStart, childEnd); parent.set(Attribute.LATENCY, latency); processor.process(parent); Mockito.verify(handler).handleGap(parent, child, null, latency - 1); } public void <API key>() { Date parentStart = new Date(); Date parentEnd = new Date(parentStart.getTime() + latency); Date child1Start = parentStart; Date child1End = new Date(parentStart.getTime() + 3); Date child2Start = new Date(parentEnd.getTime() - 3); Date child2End = parentEnd; TransactionMonitor parent = createParent(parentStart, parentEnd); addChild(parent, child1Start, child1End); addChild(parent, child2Start, child2End); parent.set(Attribute.LATENCY, latency); processor.process(parent); Mockito.<API key>(handler); } public void <API key>() { Date parentStart = new Date(); Date parentEnd = new Date(parentStart.getTime() + latency); Date child1Start = parentStart; Date child1End = new Date(parentStart.getTime() + 1); Date child2Start = new Date(parentEnd.getTime() - 1); Date child2End = parentEnd; TransactionMonitor parent = createParent(parentStart, parentEnd); TransactionMonitor child1 = addChild(parent, child1Start, child1End); TransactionMonitor child2 = addChild(parent, child2Start, child2End); parent.set(Attribute.LATENCY, latency); processor.process(parent); Mockito.verify(handler).handleGap(parent, child1, child2, latency - 2); } public void <API key>() { Date parentStart = new Date(); Date parentEnd = new Date(parentStart.getTime() + latency); Date child1Start = new Date(parentEnd.getTime() - 2); Date child1End = new Date(child1Start.getTime() + 1); Date child2Start = child1End; Date child2End = parentEnd; TransactionMonitor parent = createParent(parentStart, parentEnd); TransactionMonitor child1 = addChild(parent, child1Start, child1End); addChild(parent, child2Start, child2End); parent.set(Attribute.LATENCY, latency); processor.process(parent); Mockito.verify(handler).handleGap(parent, null, child1, latency - 2); } public void <API key>() { Date parentStart = new Date(); Date parentEnd = new Date(parentStart.getTime() + latency); Date child1Start = parentStart; Date child1End = new Date(child1Start.getTime() + 1); Date child2Start = child1End; Date child2End = new Date(child1End.getTime() + 1); TransactionMonitor parent = createParent(parentStart, parentEnd); addChild(parent, child1Start, child1End); TransactionMonitor child2 = addChild(parent, child2Start, child2End); parent.set(Attribute.LATENCY, latency); processor.process(parent); Mockito.verify(handler).handleGap(parent, child2, null, latency - 2); } private TransactionMonitor createParent(Date parentStart, Date parentEnd) { Map<String, Object> parentAttrs = new HashMap<String, Object>(); parentAttrs.put(Attribute.START_TIME, parentStart); parentAttrs.put(Attribute.END_TIME, parentEnd); TransactionMonitor parent = new TransactionMonitor("Parent", parentAttrs); return parent; } private TransactionMonitor addChild(TransactionMonitor parent, Date childStart, Date childEnd) { Map<String, Object> childAttrs = new HashMap<String, Object>(); childAttrs.put(Attribute.START_TIME, childStart); childAttrs.put(Attribute.END_TIME, childEnd); TransactionMonitor child = new TransactionMonitor("Child", childAttrs); parent.addChildMonitor(child); return child; } public void <API key>() { TestAppender appender = new TestAppender(); Logger logger = Logger.getLogger(<API key>.class.getName()); logger.addAppender(appender); logger.setLevel(Level.ALL); Date parentStart = new Date(); Date parentEnd = new Date(parentStart.getTime() + latency); TransactionMonitor parent = createParent(parentStart, parentEnd); //Must have latency to be processed //parent.set(Attribute.LATENCY, latency); processor.process(parent); LoggingEvent loggingEvent = appender.getEvents().get(0); assertEquals(Level.WARN, loggingEvent.getLevel()); assertEquals("failed to check monitoring coverage; application is unaffected", loggingEvent.getMessage()); } }
using Owin; namespace <API key> { public partial class Startup { public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider app.UseSignInCookies(); // Uncomment the following lines to enable logging in with third party login providers //app.<API key>( // clientId: "", // clientSecret: ""); //app.Use<TwitterConsumerkey>( // consumerKey: "", // consumerSecret: ""); //app.<API key>( // appId: "", // appSecret: ""); //app.<API key>(); } } }
package org.hl7.fhir.instance.model.valuesets; // Generated on Tue, Jul 14, 2015 17:35-0400 for FHIR v0.5.0 import org.hl7.fhir.instance.model.EnumFactory; public class <API key> implements EnumFactory<<API key>> { public <API key> fromCode(String codeString) throws <API key> { if (codeString == null || "".equals(codeString)) return null; if ("SEQL".equals(codeString)) return <API key>.SEQL; throw new <API key>("Unknown <API key> code '"+codeString+"'"); } public String toCode(<API key> code) { if (code == <API key>.SEQL) return "SEQL"; return "?"; } }
<!DOCTYPE HTML PUBLIC "- <!--NewPage <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_22) on Tue Nov 16 12:39:13 CET 2010 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> org.resthub.core.service (RESThub framework 1.0 API) </TITLE> <META NAME="date" CONTENT="2010-11-16"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.resthub.core.service (RESThub framework 1.0 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <A NAME="navbar_top"></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/resthub/core/model/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../org/resthub/core/test/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/resthub/core/service/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <HR> <H2> Package org.resthub.core.service </H2> Provides generic service classes for CRUD operations. <P> <B>See:</B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF="#package_description"><B>Description</B></A> <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Interface Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/resthub/core/service/<API key>.html" title="interface in org.resthub.core.service"><API key>&lt;T extends Resource&gt;</A></B></TD> <TD>Generic Resource Service</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/resthub/core/service/GenericService.html" title="interface in org.resthub.core.service">GenericService&lt;T,ID extends Serializable&gt;</A></B></TD> <TD>Generic Service interface.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/resthub/core/service/<API key>.html" title="class in org.resthub.core.service"><API key>&lt;T extends Resource,D extends GenericResourceDao&lt;T&gt;&gt;</A></B></TD> <TD>Generic Service implementation.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../org/resthub/core/service/GenericServiceImpl.html" title="class in org.resthub.core.service">GenericServiceImpl&lt;T,D extends GenericDao&lt;T,ID&gt;,ID extends Serializable&gt;</A></B></TD> <TD>Generic Service implementation.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="package_description"></A><H2> Package org.resthub.core.service Description </H2> <P> Provides generic service classes for CRUD operations. <P> <P> <DL> </DL> <HR> <A NAME="navbar_bottom"></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="<API key>"></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/resthub/core/model/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../org/resthub/core/test/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/resthub/core/service/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <! if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <HR> Copyright & </BODY> </HTML>
import type { Country } from './utils/countries'; import { noop } from 'lodash'; import React, { PureComponent } from 'react'; import classNames from 'classnames'; import Emoji from '../Emoji/Emoji'; import { <API key> } from '@dlghq/react-l10n'; import { getCountryName } from '@dlghq/country-codes'; import styles from './CountryCodeSelector.css'; type Props = { style?: Object, country: Country, isFocused: boolean, isSelected: boolean, onFocus: (country: Country) => void, onSelect: (country: Country) => void, }; class <API key> extends PureComponent<Props> { static contextTypes = { l10n: <API key>, }; static renderOption({ focusedOption, focusOption, key, option, selectValue, style, valueArray, }: $FlowIssue) { return ( <<API key> key={key} style={style} country={option} isFocused={option === focusedOption} isSelected={valueArray.indexOf(option) >= 0} onFocus={focusOption} onSelect={selectValue} /> ); } static renderValue(country: Country) { return ( <<API key> country={country} isFocused={false} isSelected={false} onFocus={noop} onSelect={noop} /> ); } handleClick = () => { this.props.onSelect(this.props.country); }; handleMouseEnter = () => { this.props.onFocus(this.props.country); }; renderFlag() { const { country } = this.props; if (country.flag) { return ( <Emoji className={styles.optionFlag} char={country.flag} size={26} /> ); } return null; } render() { const { l10n: { locale }, } = this.context; const { style, country, isFocused, isSelected } = this.props; const className = classNames( styles.option, isFocused ? styles.optionFocused : null, isSelected ? styles.optionSelected : null, ); const title = getCountryName(country.alpha, locale); return ( <div className={className} style={style} onClick={this.handleClick} onMouseEnter={this.handleMouseEnter} title={title} > {this.renderFlag()} <div className={styles.optionLabel}>{title}</div> <span className={styles.optionCode}>{country.code}</span> </div> ); } } export default <API key>;
// UIImage+Alpha.h // Free for personal or commercial use, with or without modification. // NOTE: BUGO modified to convert from Category to // new Class name since iPhone seems to have some issues with Categories // of built in Classes // Helper methods for adding an alpha layer to an image @interface UIImageAlpha : NSObject { } + (BOOL)hasAlpha:(UIImage*)image; + (UIImage *)imageWithAlpha:(UIImage*)image; + (UIImage *)<API key>:(NSUInteger)borderSize image:(UIImage*)image; @end
<!DOCTYPE html> <html lang="en"> <head> <title>FlexBox Testing</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/gene.css" type="text/css"> <link rel="stylesheet" href="css/normalize.css"> <style> .header{border:1px solid #f52b63; background: #e6ae27;} .spoons{border:1px solid #2b90f5; background: #3ad4b5; height:100px;} </style> </head> <body> <div class="row header"> <div class="col-2 col-m-4 col-l-1 spoons"></div> <div class="col-2 col-m-1 col-l-3 spoons"></div> <div class="col-2 col-m-1 col-l-1 spoons"></div> <div class="col-2 col-m-1 col-l-2 spoons"></div> <div class="col-2 col-m-1 col-l-2 spoons"></div> <div class="col-2 col-m-4 col-l-3 spoons"></div> </div> </body> </html>
-- CHECKS LAST.FM TRACK DATA -- Gets LAST.FM TRACK IDs with mixradio artist name/track name OR musicbrainz artist/track ID. -- API Parameters: artist/release names and musicbrainz artist/release IDs (when available) -- API REQUEST: http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=API_KEY&artist=Cher&track=Believe&format=json -- OR: http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key=API_KEY&artist=ARTIST_MBID&track=TRACK_MBID&format=json -- Data Columns = mixradio_release_ID | Track JSON -- JSON track format = [ {"mr_track_id": "12342", "position": "5", "mr_track_name": "Sabotage","mr_release_name":"Ill Communication","mr_artist_name":"Beastie Boys","<API key>": "NULL","<API key>": "454542","lfm_track_id":"1234"}, ... ] SET SESSION <API key> = 1000000; SELECT DISTINCT gt.mixradio_track_id, CONCAT('[',GROUP_CONCAT(DISTINCT CONCAT('{ \"position\":\"',gt.<API key>,'\", \"mr_track_name\":\"',gt.mixradio_track_name,'\", \"mr_artist_name\":\"',ga.<API key>,'\", \"mr_release_name\":\"',gr.<API key>,'\", \"mb_track_id\":\"',IF(gr.<API key> IS NULL, "NULL",gr.<API key>),'\", \"lfm_track_id\":\"',IF(gt.lastfm_track_id IS NULL, "NULL",gr.lastfm_track_id),'\", \"mb_artist_id\":\"',IF(ga.<API key> IS NULL, "NULL",gr.<API key>),'\" }')),']') as trackSeed FROM grail.grail_track as gt, grail.grail_release as gr, grail.grail_artist as ga WHERE gt.grail_artist_id = ga.grail_artist_id AND gr.grail_release_id = gt.grail_release_id AND LENGTH(gt.isrc) = 12 GROUP BY gt.mixradio_track_id ORDER BY gt.updatedat_track DESC; -- CHECK TRACK: -- SELECT count(*) FROM grail_track -- WHERE <API key> != "<API key>" AND <API key> IS NOT NULL AND lastfm_track_id != "LASTFM_track_ID" AND lastfm_track_id IS NOT NULL AND mixradio_track_id = MIXRADIO_TRACK_ID; -- UPDATE RELEASE (if CHECK == 0): -- UPDATE grail.grail_track SET grail.grail_track.<API key> = "<API key>", grail.grail_track.lastfm_track_id = "MATCHED LASTFM TRACK ID" ,grail.grail_track.<API key> = "<API key>" -- WHERE grail.grail_track.mixradio_track_id = MIXRADIO_TRACK_ID -- INSERT RELEASE (if CHECK > 0): -- INSERT INTO grail_track(<API key>,lastfm_track_id,<API key>,updatedat_track,grail_artist_id,grail_release_id,isrc,spotify_track_id,spotify_track_name,<API key>,echonest_track_id,<API key>,musixmatch_track,mixradio_track_id,mixradio_track_name,<API key>,msd_track_id,lastfm_track_id,<API key>) -- SELECT DISTINCT "NEW MUSICBRAINZ TRACK ID","NEW LASTFM TRACK ID","LASTFM JSON_CRITERIA","NEW UPDATE TIMESTAMP",<API key>,<API key>,updatedat_track,grail_artist_id,grail_release_id,isrc,spotify_track_id,spotify_track_name,<API key>,echonest_track_id,<API key>,musixmatch_track,mixradio_track_id,mixradio_track_name,<API key>,msd_track_id,lastfm_track_id,<API key> -- FROM grail.grail_track -- WHERE mixradio_track_id = MIXRADIO TRACK ID;
package com.orionplatform.file_system.directories; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import com.orionplatform.core.abstraction.OrionService; import com.orionplatform.file_system.FileSystemService; public class DirectoryService extends OrionService { public static synchronized boolean emptyDirectory(File directory) throws IOException { FileUtils.cleanDirectory(directory); return true; } public static synchronized boolean emptyDirectory(String directory) throws IOException { return emptyDirectory(new File(directory)); } public static synchronized void renameDirectory(String <API key>, String newDirectoryName) throws IOException { FileSystemService.<API key>(<API key>, newDirectoryName); } public static synchronized void renameDirectory(File <API key>, String newDirectoryName) throws IOException { FileSystemService.<API key>(<API key>, newDirectoryName); } public static synchronized boolean createDirectory(String newDirectoryName) { return createDirectory(new File(newDirectoryName)); } public static synchronized boolean createDirectory(File newDirectoryName) { return newDirectoryName.mkdirs(); } }
#!/usr/bin/env python from subprocess import Popen, PIPE from sys import argv __autor__ = "Jose Jiménez" __email__ = "jjimenezlopez@gmail.com" __date__ = "2012/05/03" if len(argv) == 1 or len(argv) > 2: print 'Wrong execution format.' print 'Correct format: any2utf /path/to/the/files' exit(0) path = argv[1] if not path.endswith('/'): path = path + '/' path = path.replace(' ', '\ ') proc = Popen('ls ' + path + '*.srt', stdout=PIPE, stderr=PIPE, shell=True) result = proc.communicate() if proc.returncode == 2: print 'SRT files not found in path \'' + path + '\'' list = result[0].splitlines() for f in list: aux_f = f aux_f.replace(' ', '\ ') # file --mime /path/to/file.srt #print 'file --mime \"' + aux_f + '\"' proc = Popen('file --mime \"' + aux_f + '\"', stdout=PIPE, shell=True) result = proc.communicate()[0] charset = result.split('charset=')[1] charset = charset.replace('\n', '') if charset == 'unknown-8bit': charset = 'iso-8859-15' if charset != 'utf-8' and charset != 'binary': # print 'iconv -f ' + charset + ' -t utf-8 ' + aux_f + ' > ' + aux_f + '.utf' proc = Popen('iconv -f ' + charset + ' -t utf-8 \"' + aux_f + '\" > \"' + aux_f + '.utf\"', stdout=PIPE, shell=True) result = proc.communicate()[0] if proc.returncode == 0: #proc = Popen('rm ' + aux_f, stdout=PIPE, shell=True) proc = Popen('mv \"' + aux_f + '.utf\" \"' + aux_f + '\"', stdout=PIPE, shell=True) proc.wait() proc = Popen('file --mime \"' + aux_f + '\"', stdout=PIPE, shell=True) text = proc.communicate()[0] print f.split('/')[-1] + ' | ' + charset + ' --> ' + text.split('charset=')[1].replace('\n', '') else: proc = Popen('file --mime \"' + aux_f + '\"', stdout=PIPE, shell=True) text = proc.communicate()[0] print f + ' --> conversion ERROR: ' + text.split('charset=')[1].replace('\n', '')
package org.ssase.util; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.math.BigDecimal; import java.util.*; public class Data { static int startIndex = 0; static String prefix = "/Users/tao/research/analysis/results/"; //"/Users/tao/research/experiments-data/femosaa/"; //"/Users/tao/research/monitor/sas-soa/final/"; static String[] compare = new String[]{ // // "moead/sas/rubis_software/", // "moead-plain/sas/rubis_software/", // "moead-k/sas/rubis_software/", // "moead-d/sas/rubis_software/", // "moead-01/sas/rubis_software/", // "femosaa-nsgaii/sas/rubis_software/", // "nsgaii/sas/rubis_software/", // "nsgaii-k/sas/rubis_software/", // "nsgaii-d/sas/rubis_software/", // "nsgaii-01/sas/rubis_software/", // "femosaa-ibea/sas/rubis_software/", // "ibea/sas/rubis_software/", // "ibea-k/sas/rubis_software/", // "ibea-d/sas/rubis_software/", // "ibea-01/sas/rubis_software/", // "moead/sas/rubis_software/", // "femosaa-nsgaii/sas/rubis_software/", // "femosaa-ibea/sas/rubis_software/", // "nsgaii/sas/rubis_software/", // "gp/sas/rubis_software/", // "bb/sas/rubis_software/" // // // "read/fifa-read-12-w-r/moead/sas/rubis_software/", // //"read/fifa-read-12-w-r/moead-k/sas/rubis_software/", // "read/fifa-read-12-w-r/moead-k/run1/sas/rubis_software/", // "read/fifa-read-12-w-r/moead-d/sas/rubis_software/", // "read/fifa-read-12-w-r/moead-nothing/sas/rubis_software/", // "read/fifa-read-12-w-r/moead-01/sas/rubis_software/", // "read/fifa-read-12-w-r/femosaa-nsgaii/sas/rubis_software/", // "read/fifa-read-12-w-r/nsgaii/sas/rubis_software/", // "read/fifa-read-12-w-r/nsgaii-k/sas/rubis_software/", // "read/fifa-read-12-w-r/nsgaii-d/sas/rubis_software/", // "read/fifa-read-12-w-r/nsgaii-01/sas/rubis_software/", // "read/fifa-read-12-w-r/femosaa-ibea/sas/rubis_software/", // "read/fifa-read-12-w-r/ibea/run1/sas/rubis_software/", // "read/fifa-read-12-w-r/ibea-k/sas/rubis_software/", // "read/fifa-read-12-w-r/ibea-d/sas/rubis_software/", // "read/fifa-read-12-w-r/ibea-01/sas/rubis_software/", // "read/fifa-read-12-w-r/moead/sas/rubis_software/", // "read/fifa-read-12-w-r/femosaa-nsgaii/sas/rubis_software/", // "read/fifa-read-12-w-r/femosaa-ibea/sas/rubis_software/", // "read/fifa-read-12-w-r/nsgaii/sas/rubis_software/", // "read/fifa-read-12-w-r/gp/sas/rubis_software/", // "read/fifa-read-12-w-r/bb/sas/rubis_software/", // // // "sas/FEMOSAA/", // "sas/FEMOSAAnothing/", // "sas/FEMOSAA01/", // "sas/NSGAIIkd/", // "sas/NSGAII/", // "sas/NSGAII01/", // "sas/IBEAkd/", // "sas/IBEA/", // "sas/IBEA01/", // "sas/GP/", // "sas/BB/" // "soa/FEMOSAA/", // "soa/FEMOSAAd/", // "soa/FEMOSAAk/", // "soa/FEMOSAA01/", // "soa/FEMOSAAnothing/", // "soa/NSGAIIkd/", // "soa/NSGAIId/", // "soa/NSGAIIk/", // "soa/NSGAII/", // "soa/NSGAII01/", // "soa/IBEAkd/", // "soa/IBEAd/", // "soa/IBEAk/", // "soa/IBEA/", // "soa/IBEA01/", // "soa/FEMOSAA/", // "soa/FEMOSAAnothing/", // "soa/FEMOSAA01/", // "soa/NSGAIIkd/", // "soa/NSGAII/", // "soa/NSGAII01/", // "soa/IBEAkd/", // "soa/IBEA/", // "soa/IBEA01/", // "soa/GP/", // "soa/BB/" // // "moead/sas/rubis_software/", "debt-aware/femosaa/htree-0.01-rt-0.05-3.5-ec-5-0.5/sas/rubis_software/", "debt-aware/femosaa/nb-0.01-rt-0.05-3.5-ec-5-0.5/sas/rubis_software/", "debt-aware/femosaa/svm-0.01-rt-0.05-3.5-ec-5-0.5/sas/rubis_software/", "debt-aware/femosaa/knn-0.01-rt-0.05-3.5-ec-5-0.5/all/sas/rubis_software/", "debt-aware/femosaa/mlp-0.01-rt-0.05-3.5-ec-5-0.5/all/sas/rubis_software/", "debt-aware/femosaa/random-10/sas/rubis_software/", "debt-aware/femosaa/rt-0.05-ec-5/sas/rubis_software/", "debt-aware/femosaa/pred/sas/rubis_software/" // "gp/sas/rubis_software/", // "debt-aware/plato/htree/sas/rubis_software/", // "debt-aware/plato/nb/sas/rubis_software/", // "debt-aware/plato/svm/sas/rubis_software/", // "debt-aware/plato/knn/sas/rubis_software/", // "debt-aware/plato/mlp/sas/rubis_software/", // "debt-aware/plato/random/sas/rubis_software/", // "debt-aware/plato/rt-0.05-ec-5/sas/rubis_software/", // "debt-aware/plato/pred/sas/rubis_software/" // "debt-aware/femosaa/sensitivity/nb/r-2.5-e-0.01/sas/rubis_software/",//129.83 // "debt-aware/femosaa/sensitivity/nb/r-3-e-0.1/sas/rubis_software/",// actually e-0.1 22.26 // "debt-aware/femosaa/nb-0.01-rt-0.05-3.5-ec-5-0.5/sas/rubis_software/",//8.31 // "debt-aware/femosaa/sensitivity/nb/r-4-e-1/sas/rubis_software/",//53.65 // "debt-aware/femosaa/sensitivity/nb/r-4.5-e-1.5/sas/rubis_software/",//-286.17 // "debt-aware/femosaa/sensitivity/ht/r-2.5-e-0.01/sas/rubis_software/",//152.03 // "debt-aware/femosaa/sensitivity/ht/r-3-ec-0.1/sas/rubis_software/",// -0.73 // "debt-aware/femosaa/htree-0.01-rt-0.05-3.5-ec-5-0.5/sas/rubis_software/",//8.31 // "debt-aware/femosaa/sensitivity/ht/r-4-e-1/sas/rubis_software/",//-133.56 // "debt-aware/femosaa/sensitivity/ht/r-4.5-e-1.5/sas/rubis_software/",//887.03 // "debt-aware/femosaa/sensitivity/sgd/r-2.5-e-0.01/sas/rubis_software/",//293.62 // "debt-aware/femosaa/sensitivity/sgd/r-3-e-0.1/sas/rubis_software/",// -4.34 // "debt-aware/femosaa/svm-0.01-rt-0.05-3.5-ec-5-0.5/sas/rubis_software/",//8.31 // "debt-aware/femosaa/sensitivity/sgd/r-4-e-1/sas/rubis_software/",//-196.36 // "debt-aware/femosaa/sensitivity/sgd/r-4.5-e-1.5/sas/rubis_software/",//-210.60 // "debt-aware/femosaa/sensitivity/knn/r-2.5-e-0.01/sas/rubis_software/",//61.26 // "debt-aware/femosaa/sensitivity/knn/r-3-e-0.1/sas/rubis_software/",// 845.91 // "debt-aware/femosaa/knn-0.01-rt-0.05-3.5-ec-5-0.5/all/sas/rubis_software/",//8.31 // "debt-aware/femosaa/sensitivity/knn/r-4-e-1/sas/rubis_software/",//215.56 // "debt-aware/femosaa/sensitivity/knn/r-4.5-e-1.5/sas/rubis_software/",//-305.48 // "debt-aware/femosaa/sensitivity/mlp/r-2.5-e-0.01/sas/rubis_software/",//16.91 // "debt-aware/femosaa/sensitivity/mlp/r-3-e-0.1/sas/rubis_software/",// 87.22 // "debt-aware/femosaa/mlp-0.01-rt-0.05-3.5-ec-5-0.5/all/sas/rubis_software/",//8.31 // "debt-aware/femosaa/sensitivity/mlp/r-4-e-1/sas/rubis_software/",//-184.58 // "debt-aware/femosaa/sensitivity/mlp/r-4.5-e-1.5/sas/rubis_software/",//191.48 // "debt-aware/femosaa/sensitivity/nb/0.001-u/sas/rubis_software/",//97.48 // "debt-aware/femosaa/sensitivity/nb/0.005-u/sas/rubis_software/",//-90.70 // "debt-aware/femosaa/nb-0.01-rt-0.05-3.5-ec-5-0.5/sas/rubis_software/",//8.31 // "debt-aware/femosaa/sensitivity/nb/0.1-u/sas/rubis_software/",//282.85 // "debt-aware/femosaa/sensitivity/nb/1-u/sas/rubis_software/",//-43.69 // "debt-aware/femosaa/sensitivity/ht/u-0.001/sas/rubis_software/",//45.06 // "debt-aware/femosaa/sensitivity/ht/u-0.005/sas/rubis_software/",// 602.87 // "debt-aware/femosaa/htree-0.01-rt-0.05-3.5-ec-5-0.5/sas/rubis_software/",//8.31 // "debt-aware/femosaa/sensitivity/ht/u-0.1/sas/rubis_software/",//24.86 // "debt-aware/femosaa/sensitivity/ht/u-1/sas/rubis_software/",//3.17 // "debt-aware/femosaa/sensitivity/sgd/u-0.001/sas/rubis_software/",//-120.06 // "debt-aware/femosaa/sensitivity/sgd/u-0.005/sas/rubis_software/",// 628.33 // "debt-aware/femosaa/svm-0.01-rt-0.05-3.5-ec-5-0.5/sas/rubis_software/",//8.31 // "debt-aware/femosaa/sensitivity/sgd/u-0.1/sas/rubis_software/",//169.05 // "debt-aware/femosaa/sensitivity/sgd/u-1/sas/rubis_software/",//101.41 // "debt-aware/femosaa/sensitivity/knn/u-0.001/sas/rubis_software/",//616.59 // "debt-aware/femosaa/sensitivity/knn/u-0.005/sas/rubis_software/",// 189.31 // "debt-aware/femosaa/knn-0.01-rt-0.05-3.5-ec-5-0.5/all/sas/rubis_software/",//8.31 // "debt-aware/femosaa/sensitivity/knn/u-0.1/sas/rubis_software/",//220.60 // "debt-aware/femosaa/sensitivity/knn/u-1/sas/rubis_software/",//129.72 // "debt-aware/femosaa/sensitivity/mlp/u-0.001/sas/rubis_software/",//429.90 // "debt-aware/femosaa/sensitivity/mlp/u-0.005/sas/rubis_software/",// 524.77 // "debt-aware/femosaa/mlp-0.01-rt-0.05-3.5-ec-5-0.5/all/sas/rubis_software/",//8.31 // "debt-aware/femosaa/sensitivity/mlp/u-0.1/sas/rubis_software/",//-101.17 // "debt-aware/femosaa/sensitivity/mlp/u-1/sas/rubis_software/",//733.06 // "moead/sas/rubis_software/", // "debt-aware/femosaa/random-10/sas/rubis_software/", // "debt-aware/femosaa/rt-0.05-ec-5/sas/rubis_software/", // "debt-aware/femosaa/pred/sas/rubis_software/" // }; static String[] compare1 = new String[]{ "moead/sas/rubis_software/", "moead-plain/sas/rubis_software/", "moead-d/sas/rubis_software/", "moead-k/sas/rubis_software/", "moead-01/sas/rubis_software/" }; static String[] obj = new String[]{ "Response Time.rtf", "Energy.rtf", // "Throughput.rtf", // "Cost.rtf", }; static double[] requirements = new double[]{ 0.05, 5, }; static double[] price = new double[]{ 3.5, 0.5 }; static double adaptCost = 1; static Map<String, Map<Integer, Double>> debt = new HashMap<String, Map<Integer, Double>>(); static Map<String, Double> RTmap = new HashMap<String, Double> (); static Map<String, Double> Emap = new HashMap<String, Double> (); static Map<String, List<Double>> Vmap = new HashMap<String, List<Double>> (); static double RTmax = 0; static double RTmin = 100000; static double Emax = 0; static double Emin = 100000; static Map<String, List<Double>> surface = new HashMap<String, List<Double>> (); static Map<String, double[]> log_values = new HashMap<String, double[]> (); static Map<String, Double[]> values = new HashMap<String, Double[]> (); static Map<String, List<Double>> AdaMap = new HashMap<String, List<Double>> (); static Map<String, List<Double>> AdaTimeMap = new HashMap<String, List<Double>> (); static Map<String, double[]> log_values_add = new HashMap<String, double[]> (); static double[] workload = new double[]{ 38.54367256463304, 78.00051667097227, 49.998600039998834, 73.49827920774206, 106.00031666930559, 147.99772503631885, 125.99685007874801, 108.49643345096833, 154.99587094503167, 182.99772503145786, 224.9917087017167, 276.49363767197497, 512.9914501424976, 463.48455051498286, 384.500716672639, 85.99910417711787, 579.9855003624909, 436.9913126798919, 552.9871919699233, 140.9967750756232, 478.9851254685267, 488.9845546601577, 474.49209179846997, 214.9924044377333, 174.9995750035416, 1333.4632635317416, 813.9820920736712, 133.4969250724983, 149.9973167159713, 1336.4668924892853, 2214.418957169297, 741.989741820067, 428.4898377448898, 545.9863503412414, 590.9889293816972, 370.4877462393962, 265.99527925253307, 353.4923585044405, 399.4866837772074, 319.49201269968245, 224.9963958921865, 337.4918918638841, 324.4916627159319, 1981.9575759418535, 638.4862044754443, 300.9899670010999, 349.4958833877075, 289.4925835247173, 188.47460342398256, 250.4985000124999, 2164.945876353091, 1185.470363240919, 113.49716257093571, 136.49515434051457, 162.49624175555343, 169.49836251739563, 104.49660011124632, 115.99806669888838, 171.4959625967685, 145.49637925690743, 222.99450013624664, 301.4832009405721, 347.992021020794, 287.99280017999547, 271.99108362679584, 320.4989666752777, 475.9769594537648, 2694.9662629691243, 970.4793712884965, 1102.972425689358, 479.48801279967995, 319.4973375221873, 176.99928750593747, 538.9891627269741, 3100.9332931540634, 1770.455738606535, 161.99595010124744, 575.9856003599909, 653.4860419759652, 4306.923276402264, 2240.9082954321375, 154.4972792156588, 208.9965167247213, 201.49664172263795, 138.99073395106993, 127.993600319984, 184.99383353888203, 174.49540012291337, 125.99813752906202, 1892.4526886827832, 1858.4583134625814, 612.483850431655, 417.9914793475307, 444.988875278118, 653.9836504087398, 759.4846669890902, 543.4860295287058, 161.4957209483649, 221.49630839486002, 950.9789671467944, 600.980596464389, 33.4900936202264, }; private static void test(){ double sample = 102; double mean1 = 1.7; double var1 = 42; double mean2 = 1.9; double var2 = 25; double t = Math.abs(mean1 - mean2) / Math.pow(var1/sample + var2/sample, 0.5); double v = Math.pow(var1/sample + var2/sample, 2) / (var1*var1/(sample*sample*(sample-1)) + var2*var2/(sample*sample*(sample-1)) ); System.out.print("t: " + t + ", v: " + v + "\n"); System.out.print("m: " + Math.abs(mean1 - mean2) + ", v: " + Math.pow(var1/sample + var2/sample, 0.5) + "\n"); } public static void main(String[] a) { // test(); // for (String n : compare) { // for (String o : obj) { // try { // double t = read(prefix+n+o,o); // System.out.print("Mean: " + n +", "+o+"="+t+"\n"); // } catch (Throwable e) { // // TODO Auto-generated catch block // e.printStackTrace(); for (String n : compare) { for (String o : obj) { try { double t = readGmean(prefix+n+o,n,o); System.out.print("GMean: " + n +", "+o+"="+t+"\n"); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } } } System.out.print("\n"); for (String n : compare) { double t = IGD(n); System.out.print("IGD: " + n +"="+t+"\n"); } System.out.print("\n"); for (String n : compare) { double t = HV(n); System.out.print("HV: " + n +"="+t+"\n"); } System.out.print("\n"); for (String n : compare) { try { double t = readDependency(prefix+n); System.out.print("Dependency: " + n +"="+t+"\n"); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.print("\n"); for (String n : compare) { try { double t = readTime(prefix+n); System.out.print("Execution Time: " + n +"="+t+"\n"); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } } <API key>(); // staTest("sas/FEMOSAA/", "sas/FEMOSAAd/"); // staTest("sas/FEMOSAA/", "sas/FEMOSAAk/"); // staTest("sas/FEMOSAA/", "sas/FEMOSAAnothing/"); // staTest("sas/FEMOSAA/", "sas/FEMOSAA01/"); // staTest("sas/FEMOSAAnothing/", "sas/FEMOSAAd/"); // staTest("sas/FEMOSAAnothing/", "sas/FEMOSAAk/"); // staTest("sas/FEMOSAAnothing/", "sas/FEMOSAA01/"); // staTest("sas/NSGAIIkd/", "sas/NSGAIId/"); // staTest("sas/NSGAIIkd/", "sas/NSGAIIk/"); // staTest("sas/NSGAIIkd/", "sas/NSGAII/"); // staTest("sas/NSGAIIkd/", "sas/NSGAII01/"); // staTest("sas/NSGAII/", "sas/NSGAIId/"); // staTest("sas/NSGAII/", "sas/NSGAIIk/"); // staTest("sas/NSGAII/", "sas/NSGAII01/"); // staTest("sas/IBEAkd/", "sas/IBEAd/"); // staTest("sas/IBEAkd/", "sas/IBEAk/"); // staTest("sas/IBEAkd/", "sas/IBEA/"); // staTest("sas/IBEAkd/", "sas/IBEA01/"); // staTest("sas/IBEA/", "sas/IBEAd/"); // staTest("sas/IBEA/", "sas/IBEAk/"); // staTest("sas/IBEA/", "sas/IBEA01/"); // staTest("sas/FEMOSAA/", "sas/NSGAII/"); // staTest("sas/NSGAIIkd/", "sas/NSGAII/"); // staTest("sas/IBEAkd/", "sas/NSGAII/"); // staTest("sas/FEMOSAA/", "sas/GP/"); // staTest("sas/NSGAIIkd/", "sas/GP/"); // staTest("sas/IBEAkd/", "sas/GP/"); // staTest("sas/FEMOSAA/", "sas/BB/"); // staTest("sas/NSGAIIkd/", "sas/BB/"); // staTest("sas/IBEAkd/", "sas/BB/"); // print3DForSOA(); if(1 == 1) return; for (String n : compare) { try { double t = readAdaptation(prefix+n); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } } <API key>(prefix+compare[0], prefix+compare[1], compare[0], compare[1], obj[1]); // for (String n : compare) { // for (String o : obj) { // try { // double dp = 0.5; // double t = readP(prefix+n+o, dp); // System.out.print(dp+"P: " + n +", "+o+"="+t+"\n"); // } catch (Throwable e) { // // TODO Auto-generated catch block // e.printStackTrace(); for (String n : compare) { int k = 0; double adapCost = 0.0; for(Double d : AdaMap.get(prefix+n)) { int i = (int)(d - 122); //System.out.print(AdaMap.get(prefix+n).size() + " " + i + " " + debt.get(n).size() + "\n"); if(i == debt.get(n).size() || !debt.get(n).containsKey(i)) { break; } double original = debt.get(n).get(i); original += (30/*mean training time*/ + AdaTimeMap.get(prefix+n).get(k)/1000) * adaptCost; //4.0464566409062 debt.get(n).put(i, original); adapCost += (30/*mean training time*/ + AdaTimeMap.get(prefix+n).get(k)/1000) * adaptCost; System.out.print(n + " adapting at: " + i+"\n"); k++; } System.out.print(n + " adaptation cost: " + adapCost+"\n"); } System.out.print("Debt\n\n"); List<Double> allDebt = new ArrayList<Double>(); Map<String, List<Double>> tempMap = new HashMap<String, List<Double>>(); Map<String, Double> bestDebt = new HashMap<String,Double>(); Map<String,String> bestDebtIndex = new HashMap<String,String>(); Map<String,List<Boolean>> classification = new HashMap<String,List<Boolean>>(); for (String app : debt.keySet()) { System.out.print(app + "\n"); tempMap.put(app, new ArrayList<Double>()); double total = 0.0; double f_total = 0.0; int i = 0; double preS = Double.MAX_VALUE; classification.put(app, new ArrayList<Boolean>()); for(Map.Entry<Integer, Double> e : debt.get(app).entrySet()) { tempMap.get(app).add(e.getValue()); allDebt.add(e.getValue()); total = e.getValue(); f_total += e.getValue(); List<Double> l = AdaMap.get(prefix+app); boolean b = l.contains(e.getKey().doubleValue() + 122.0); boolean net = b? total < preS : 0 < total; //System.out.print(e.getKey()+ " " +b + ",\n"); classification.get(app).add(b); //System.out.print(e.getKey()+ " " +b + ",\n"); System.out.print(e.getKey()+" " +total + " : " + b + ",\n"); //System.out.print("(" + e.getKey() + "," + (Math.log10(e.getValue()+250)) + ")\n"); if(!bestDebt.containsKey(String.valueOf(e.getKey())) || total < bestDebt.get(String.valueOf(e.getKey())) ) { bestDebt.put(String.valueOf(e.getKey()), total); bestDebtIndex.put(String.valueOf(e.getKey()), app + ":" + String.valueOf(e.getKey())); } i++; double c = 0; preS = b? total - ((30/*mean training time*/ + l.get(l.indexOf(e.getKey().doubleValue() + 122.0))/1000) * adaptCost) : total; } System.out.print("total " + f_total + "\n"); } double best_debt = 0.0; for (String i : bestDebt.keySet()) { best_debt += bestDebt.get(i); } System.out.print("total best" + best_debt + "\n"); System.out.print("Merged data\n"); List<Double> mergedRT = new ArrayList<Double>(); List<Double> mergedEC = new ArrayList<Double>(); List<Boolean> mergedIsAdapt = new ArrayList<Boolean>(); for(int i = 0; i < 102; i++) { String s = String.valueOf(i); List<Double> l = AdaMap.get(prefix+bestDebtIndex.get(s).split(":")[0]); boolean b = l.contains(Double.parseDouble(bestDebtIndex.get(s).split(":")[1]) + 122.0); mergedIsAdapt.add(b); mergedRT.add(surface.get(bestDebtIndex.get(s).split(":")[0] + "Response Time.rtf").get(Integer.parseInt(bestDebtIndex.get(s).split(":")[1]))); mergedEC.add(surface.get(bestDebtIndex.get(s).split(":")[0] + "Energy.rtf").get(Integer.parseInt(bestDebtIndex.get(s).split(":")[1]))); System.out.print(bestDebtIndex.get(s) + " = " + bestDebt.get(s) + " = " + b + "\n"); } System.out.print("Merged RT\n"); double mt = 0.0; for(int i = 0; i < mergedRT.size(); i++) { System.out.print(mergedRT.get(i) + "\n"); mt += mergedRT.get(i); } System.out.print("total RT " + (mt/mergedRT.size()) + "\n"); mt = 0.0; System.out.print("Merged EC\n"); for(int i = 0; i < mergedEC.size(); i++) { System.out.print(mergedEC.get(i) + "\n"); mt += mergedEC.get(i); } System.out.print("total EC " + (mt/mergedRT.size()) + "\n"); for (String app : debt.keySet()) { System.out.print(app+"\n"); double total = 0.0; double under = 0.0; double over = 0.0; for(int i = 0; i < mergedIsAdapt.size(); i++) { List<Double> l = AdaMap.get(prefix+app); boolean b = l.contains((double)i + 122.0); // under adapt if(mergedIsAdapt.get(i) && !b) { // // System.out.print( (surface.get(app + "Response Time.rtf").get(i) - mergedRT.get(i)) + "\n"); // // System.out.print( surface.get(app + "Response Time.rtf").get(i) + "\n"); // System.out.print(i + " : " + ( debt.get(app).get(i) - bestDebt.get(String.valueOf(i))) + "\n"); // total += ( debt.get(app).get(i) - bestDebt.get(String.valueOf(i))); under += ( debt.get(app).get(i) - bestDebt.get(String.valueOf(i))); } // over adapt if(!mergedIsAdapt.get(i) && b) { //System.out.print( surface.get(app + "Response Time.rtf").get(i) + "\n"); System.out.print(i + " : " + ( debt.get(app).get(i) - bestDebt.get(String.valueOf(i))) + "\n"); total += ( debt.get(app).get(i) - bestDebt.get(String.valueOf(i))); over += ( debt.get(app).get(i) - bestDebt.get(String.valueOf(i))); } } System.out.print("total " + total + "\n"); System.out.print("over % " + (over/(over+under)) + "\n"); } System.out.print("Classification accuracy RT\n"); for (String app : debt.keySet()) { System.out.print(app+"\n"); double tp = 0.0; double tn = 0.0; double fp = 0.0; double fn = 0.0; for(int i = 0; i < mergedIsAdapt.size(); i++) { if(i >= classification.get(app).size()) { continue; } boolean classify = classification.get(app).get(i); boolean turth = mergedIsAdapt.get(i); if (classify == turth && turth && classify) { tp++; } if (classify == turth && !turth && !classify) { tn++; } if (!classify && turth) { fp++; } if (classify && !turth) { fn++; } } double precision = tp / (tp + fp); double recall = tp / (tp + fn); double ac = (tp+tn) / (tp + tn +fp + fn); double f_measure = 2*(precision*recall)/(precision+recall); System.out.print("precision: " + precision + "\n"); System.out.print("recall: " + recall + "\n"); System.out.print("ac: " + ac + "\n"); System.out.print("f_measure: " + f_measure + "\n"); } // staTest("debt-aware/plato/pred/sas/rubis_software/", "debt-aware/plato/htree/sas/rubis_software/"); // staTest("debt-aware/plato/pred/sas/rubis_software/", "debt-aware/plato/nb/sas/rubis_software/"); // staTest("debt-aware/plato/pred/sas/rubis_software/", "debt-aware/plato/svm/sas/rubis_software/"); // staTest("debt-aware/plato/pred/sas/rubis_software/", "debt-aware/plato/knn/sas/rubis_software/"); // staTest("debt-aware/plato/pred/sas/rubis_software/", "debt-aware/plato/mlp/sas/rubis_software/"); // staTest("debt-aware/plato/pred/sas/rubis_software/", "debt-aware/plato/random/sas/rubis_software/"); // staTest("debt-aware/plato/pred/sas/rubis_software/", "debt-aware/plato/rt-0.05-ec-5/sas/rubis_software/"); // staTest("debt-aware/plato/pred/sas/rubis_software/", "gp/sas/rubis_software/"); // System.out.print("Debt CDF\n\n"); // Collections.sort(allDebt); // System.out.print(allDebt.size()+"\n"); // for (String app : debt.keySet()) { // System.out.print(app + "\n"); // Collections.sort(tempMap.get(app)); // for (int i = 0; i < allDebt.size(); i++) { // double total = 0.0; // for(Double d : tempMap.get(app)) { // total += (d <= allDebt.get(i))? (1.0/tempMap.get(app).size()) : 0; // //System.out.print("(" + e.getKey() + "," + (Math.log10(e.getValue()+250)) + ")\n"); // System.out.print("(" +allDebt.get(i) + "," + total + ")\n"); String sur = "read/fifa-read-12-w-r/femosaa-ibea/sas/rubis_software/"; List<Double> l1 = surface.get(sur+"Response Time.rtf"); List<Double> l2 = surface.get(sur+"Energy.rtf"); for(int i = 0; i < l1.size();i++) { //System.out.print(l2.get(i) + " " + i + " " + l1.get(i) + "\n"); } File f = new File(prefix+sur); List<Double> list = new ArrayList<Double>(); for(File fi : f.listFiles()){ if(fi.getName().startsWith("Workload-")) { //System.out.print(fi.getName()+"\n"); try { readWorkload(prefix+sur+fi.getName(),list); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } } } for(int i = 0; i < l1.size();i++) { //System.out.print(l2.get(i) + " " + (i >= workload.length? workload[workload.length-1] : workload[i]) + " " + l1.get(i) + "\n"); System.out.print(l2.get(i) + " " + (i >= list.size()? list.get(list.size()-1)*60 : (list.get(i)*60)) + " " + l1.get(i) + "\n"); } for(int i = 0; i < l1.size();i++) { //System.out.print((list.get(i)*60) + ",\n"); } } private static void <API key>(){ double threshold = 5; for (Map.Entry<String, Double[]> e : values.entrySet()) { double c = 0.0; double m = Double.MIN_VALUE; //System.out.print(e.getKey() + "\n"); for (double d : e.getValue()) { c += d < threshold? 0.0 : d - threshold; m = m < d? d : m; } c = c / e.getValue().length; System.out.print(e.getKey() + ", Compliance: " + c + ", Overshoot: " + m + "\n"); } } private static void print3DForSOA(){ String data = ""; try { BufferedReader reader = new BufferedReader(new FileReader(new File("/Users/tao/research/<API key>" + "/FEMOSAA/paper/TOSEM/soa/soa-ibea-01.txt"))); String line = ""; int i = 0; while((line = reader.readLine()) != null) { data += log_values_add.get("sas/IBEA01/")[i] + " " + line.split(" ")[1] + " " + log_values.get("sas/IBEA01/")[i] + "\n"; i++; } } catch (Exception e) { e.printStackTrace(); } System.out.print(data); } private static void staTest(String a, String b){ if(log_values.get(a).length != log_values.get(b).length) { //int n = 0; if(log_values.get(a).length > log_values.get(b).length) { //n = log_values.get(a).length - log_values.get(b).length; double[] temp = new double[log_values.get(b).length]; System.arraycopy(log_values.get(a), 0, temp, 0, log_values.get(b).length); log_values.put(a, temp); } else { // n = log_values.get(b).length - log_values.get(a).length; double[] temp = new double[log_values.get(a).length]; System.arraycopy(log_values.get(b), 0, temp, 0, log_values.get(a).length); log_values.put(b, temp); } } <API key> test = new <API key>(); System.out.print(" double p = test.<API key>(log_values.get(a), log_values.get(b), false); double es = test.getEffectSize(log_values.get(a), log_values.get(b)); String e = ""; if (es < 0.1) { e = "trivial"; } else if (0.1 < es && es < 0.24) { e = "small"; } else if (0.24 < es && es < 0.37) { e = "medium"; } else { e = "large"; } System.out.print("p value: " + p +"\n"); System.out.print("effect size: " + es + "-" + e +"\n"); } private static double read(String name, String obj) throws Throwable { BufferedReader reader = new BufferedReader(new FileReader(new File(name))); String line = null; double total = 0; int i = 0; int no = 0; List<Double> list = new ArrayList<Double>(); while((line = reader.readLine()) != null) { if(Double.parseDouble(line) != 0 && i < startIndex) { i++; continue; } if(Double.parseDouble(line) != 0 ) { if(obj.equals("Response Time.rtf")) { list.add(Double.parseDouble(line)* 1000); total += Double.parseDouble(line)* 1000 ; } else { list.add(Double.parseDouble(line)* 1); total += Double.parseDouble(line)* 1 ; } i++; no++; } } reader.close(); double mean = total/no; double std = 0; for (int j = 0; j < list.size();j ++) { std += Math.pow(list.get(j) - mean, 2); } double v = std; std = Math.pow(std/no, 0.5); System.out.print(no+"STD: " + std + "\n"); System.out.print(no+"Var: " + (v/no) + "\n"); return total/no; } private static double readWorkload(String name, List<Double> list) throws Throwable { BufferedReader reader = new BufferedReader(new FileReader(new File(name))); String line = null; double total = 0; int i = 0; int no = 0; while((line = reader.readLine()) != null) { if( i < 121) { i++; continue; } if(list.size() <= no) { list.add(Double.parseDouble(line)); } else { double n = list.get(no); //System.out.print(no + "=" +n + " : " + (n + Double.parseDouble(line)) + "\n"); list.remove(no); list.add(no, (n + Double.parseDouble(line))); } i++; no++; } reader.close(); return total/no; } private static void <API key>(String name1, String name2, String a1, String a2, String obj) { List<Double> list1 = AdaMap.get(name1); List<Double> list2 = AdaMap.get(name2); List<Double> missingFrom1 = new ArrayList<Double>(); List<Double> missingFrom2 = new ArrayList<Double>(); for(Double d : list1) { if(!list2.contains(d)) { missingFrom2.add(d); //System.out.print("missingFrom2 " + d + "\n"); } } for(Double d : list2) { if(!list1.contains(d)) { missingFrom1.add(d); //System.out.print("missingFrom1 " + d + "\n"); } } int f = 0; double total = 1.0; int count = 0; System.out.print(missingFrom1.size()+" In " + name2 + " but not in " + name1 + "\n"); System.out.print(a1 + "\n"); // for(Double d : missingFrom1) { // if((int)(d + f - 122) < Vmap.get(a1+obj).size()) { // System.out.print(Vmap.get(a1+obj).get((int)(d + f - 122))+"\n"); // System.out.print(a2 + "\n"); // for(Double d : missingFrom1) { // if((int)(d + f - 122) < Vmap.get(a2+obj).size()) { // System.out.print(Vmap.get(a2+obj).get((int)(d + f - 122))+"\n"); Set<Double> filter = new HashSet<Double>(); for(Double d : missingFrom1) { int l = -1; for (int k = 0; k < AdaMap.get(name1).size();k++) { //System.out.print("AdaMap.get(name1).get(k) " + AdaMap.get(name1).get(k) + " d " + d + "\n"); if(AdaMap.get(name1).get(k) > d ) { l = (int) (AdaMap.get(name1).get(k) - d); break; } } if (l == -1 && missingFrom1.indexOf(d)+1 < missingFrom1.size()) { l = (int) (missingFrom1.get(missingFrom1.indexOf(d)+1) - d); } if(missingFrom1.indexOf(d) == missingFrom1.size() - 1 && (d - 122) < Vmap.get(a1+obj).size()) { l = (int) (Vmap.get(a1+obj).size() + 122 - d); } for (int i = 0; i < l; i++) { if(filter.contains(d + i)) { continue; } if(Vmap.get(a1+obj).size() >= (d + i - 122)) { break; } //System.out.print( Vmap.get(a1+obj).get((int)(d + i - 122))+"\n"); System.out.print(obj.equals("Response Time.rtf")? Math.log10(Vmap.get(a1+obj).get((int)(d + i - 122))*1000)+"\n" : Math.log10(Vmap.get(a1+obj).get((int)(d + i - 122)))+"\n"); total *= Vmap.get(a1+obj).get((int)(d + i - 122)); count++; filter.add(d + i); } } System.out.print("Total " + Math.pow(total, 1.0/count) + " : " + count + "\n"); filter.clear(); total = 1.0; count = 0; System.out.print(a2 + "\n"); for(Double d : missingFrom1) { int l = -1; for (int k = 0; k < AdaMap.get(name2).size();k++) { //System.out.print("AdaMap.get(name1).get(k) " + AdaMap.get(name1).get(k) + " d " + d + "\n"); if(AdaMap.get(name2).get(k) > d ) { l = (int) (AdaMap.get(name2).get(k) - d); break; } } if (l == -1 && missingFrom1.indexOf(d)+1 < missingFrom1.size()) { l = (int) (missingFrom1.get(missingFrom1.indexOf(d)+1) - d); } if(missingFrom1.indexOf(d) == missingFrom1.size() - 1 && (d - 122) < Vmap.get(a2+obj).size()) { l = (int) (Vmap.get(a2+obj).size() + 122 - d); } for (int i = 0; i < l; i++) { if(filter.contains(d + i)) { continue; } //System.out.print(Vmap.get(a2+obj).get((int)(d + i - 122))+"\n"); System.out.print(obj.equals("Response Time.rtf")? Math.log10(Vmap.get(a2+obj).get((int)(d + i - 122))*1000) +"\n" : Math.log10(Vmap.get(a2+obj).get((int)(d + i - 122)))+"\n"); total *= Vmap.get(a2+obj).get((int)(d + i - 122)); count++; filter.add(d + i); } } System.out.print("Total " + Math.pow(total, 1.0/count) + " : " + count + "\n"); System.out.print(missingFrom2.size()+" In " + name1 + " but not in " + name2 + "\n"); System.out.print(a1 + "\n"); // for(Double d : missingFrom2) { // if((int)(d + f - 122) < Vmap.get(a1+obj).size()) { // System.out.print(Vmap.get(a1+obj).get((int)(d+ f - 122))+"\n"); // System.out.print(a2 + "\n"); // for(Double d : missingFrom2) { // if((int)(d + f - 122) < Vmap.get(a2+obj).size()) { // System.out.print(Vmap.get(a2+obj).get((int)(d + f - 122))+"\n"); filter.clear(); total = 1.0; count = 0; for(Double d : missingFrom2) { int l = -1; for (int k = 0; k < AdaMap.get(name1).size();k++) { //System.out.print("AdaMap.get(name1).get(k) " + AdaMap.get(name1).get(k) + " d " + d + "\n"); if(AdaMap.get(name1).get(k) > d ) { l = (int) (AdaMap.get(name1).get(k) - d); break; } } if (l == -1 && missingFrom2.indexOf(d)+1 < missingFrom2.size()) { l = (int) (missingFrom2.get(missingFrom2.indexOf(d)+1) - d); } if(missingFrom2.indexOf(d) == missingFrom2.size() - 1 && (d - 122) < Vmap.get(a1+obj).size()) { l = (int) (Vmap.get(a1+obj).size() + 122 - d); } for (int i = 0; i < l; i++) { if(filter.contains(d + i)) { continue; } //System.out.print( Vmap.get(a1+obj).get((int)(d + i - 122))+"\n"); System.out.print(obj.equals("Response Time.rtf")? Math.log10(Vmap.get(a1+obj).get((int)(d + i - 122))*1000) +"\n" : Math.log10(Vmap.get(a1+obj).get((int)(d + i - 122)))+"\n"); total *= Vmap.get(a1+obj).get((int)(d + i - 122)); count++; filter.add(d + i); } } System.out.print("Total " + Math.pow(total, 1.0/count) + " : " + count + "\n"); filter.clear(); total = 1.0; count = 0; System.out.print(a2 + "\n"); for(Double d : missingFrom2) { int l = -1; for (int k = 0; k < AdaMap.get(name2).size();k++) { //System.out.print("AdaMap.get(name1).get(k) " + AdaMap.get(name1).get(k) + " d " + d + "\n"); if(AdaMap.get(name2).get(k) > d ) { l = (int) (AdaMap.get(name2).get(k) - d); //System.out.print(AdaMap.get(name2).get(k) + ":" + d +"start\n"); break; } } if (l == -1 && missingFrom2.indexOf(d)+1 < missingFrom2.size()) { l = (int) (missingFrom2.get(missingFrom2.indexOf(d)+1) - d); } if(missingFrom2.indexOf(d) == missingFrom2.size() - 1 && (d - 122) < Vmap.get(a2+obj).size()) { l = (int) (Vmap.get(a2+obj).size() + 122 - d); } for (int i = 0; i < l; i++) { if(filter.contains(d + i)) { continue; } if (Vmap.get(a2+obj).size() <= (int)(d + i - 122)) { continue; } //System.out.print( Vmap.get(a2+obj).get((int)(d + i - 122))+"\n"); System.out.print(obj.equals("Response Time.rtf")? Math.log10(Vmap.get(a2+obj).get((int)(d + i - 122))*1000) +"\n" : Math.log10(Vmap.get(a2+obj).get((int)(d + i - 122)))+"\n"); total *= Vmap.get(a2+obj).get((int)(d + i - 122)); count++; filter.add(d + i); } } System.out.print("Total " + Math.pow(total, 1.0/count) + " : " + count + "\n"); } private static double readAdaptation(String name) throws Throwable { BufferedReader reader = new BufferedReader(new FileReader(new File(name.replace("rubis_software/", "Executions.rtf")))); String line = null; double total = 0; int i = 0; int no = 0; List<Double> list = new ArrayList<Double>(); if(!AdaMap.containsKey(name)) { AdaMap.put(name, list); } while((line = reader.readLine()) != null) { if(line.startsWith(" list.add(Double.parseDouble(line.split(" System.out.print("Adaptation Step: " + name +"="+Double.parseDouble(line.split(" } } reader.close(); return total/no; } private static double readTime(String name) throws Throwable { BufferedReader reader = new BufferedReader(new FileReader(new File(obj[0].equals("Response Time.rtf")?name.replace("rubis_software/", "Execution-time.rtf") : name + "/Execution-time.rtf"))); String line = null; double total = 0; int i = 0; int no = 0; List<Double> list = new ArrayList<Double>(); if(!AdaTimeMap.containsKey(name)) { AdaTimeMap.put(name, list); } while((line = reader.readLine()) != null) { if(i < startIndex) { i++; continue; } //if(Double.parseDouble(line) != 0) { total += Double.parseDouble(line); list.add(Double.parseDouble(line)); i++; no++; } reader.close(); System.out.print("Adaptation Time: " + name +"="+no+"\n"); return total/no; } private static double readDependency(String name) throws Throwable { BufferedReader reader = new BufferedReader(new FileReader(new File(obj[0].equals("Response Time.rtf")?name.replace("rubis_software/", "Dependency.rtf") : name + "/Dependency.rtf"))); String line = null; double total = 0; int i = 0; int no = 0; List<Double> list = new ArrayList<Double>(); while((line = reader.readLine()) != null) { if(i < startIndex) { i++; continue; } //if(Double.parseDouble(line) != 0) { total += Double.parseDouble(line) ; i++; no++; } reader.close(); return total/no; } private static double readGSD(Double[] values, double geoMean) { double gsd = 0.0; for (int i = 0; i < values.length; i++) { //System.out.print(Math.log10(values[i])+"\n"); //if (values[i] > 0 && geoMean > 0) { gsd = gsd + (Math.log10(values[i]) - Math.log10(geoMean) * (Math.log10(values[i]) - Math.log10(geoMean))); } gsd = gsd / (values.length); gsd = Math.sqrt(gsd); gsd = Math.exp(gsd); return gsd; } private static Double[] log(Double[] values) { double gsd = 0.0; String d = ""; String n = ""; Double[] newValues = new Double[values.length]; for (int i = 0; i < values.length; i++) { newValues[i] = Math.log10(values[i]); } for (int i = 0; i < newValues.length; i++) { //System.out.print(values[i] + "\n"); //System.out.print("("+i+","+newValues[i] + ")\n"); d = d + newValues[i] + ","; n = n + (i + 1) + ","; gsd += newValues[i]; } //System.out.print("Mean " + gsd/newValues.length + "\n"); double mean = gsd/newValues.length; double var = 0.0; for (int i = 0; i < newValues.length; i++) { var += Math.pow((newValues[i] - mean), 2); } //System.out.print("Var "+var/newValues.length + "\n"); //System.out.print(d + "\n"); //System.out.print(n + "\n"); return newValues; } private static double readGmean(String name, String approach, String obj) throws Throwable { BufferedReader reader = new BufferedReader(new FileReader(new File(name))); String line = null; double total = 1; int i = 0; int no = 0; BigDecimal bd = new BigDecimal(1); double htotal = 0; List<Double> list = new ArrayList<Double>(); Vmap.put(approach+obj, new ArrayList<Double>()); double mean_total = 0.0; while((line = reader.readLine()) != null) { if(Double.parseDouble(line) != 0 && i < startIndex) { i++; continue; } if(Double.parseDouble(line) != 0) { if(obj.equals("Response Time.rtf")) { list.add(Double.parseDouble(line)*1000); bd = bd.multiply(new BigDecimal(Double.parseDouble(line))).multiply(new BigDecimal(1000)); Vmap.get(approach+obj).add(Double.parseDouble(line)); mean_total += Double.parseDouble(line)*1000; } else { list.add(Double.parseDouble(line)*1); bd = bd.multiply(new BigDecimal(Double.parseDouble(line))).multiply(new BigDecimal(1)); Vmap.get(approach+obj).add(Double.parseDouble(line)); mean_total += Double.parseDouble(line); } double d = (obj.equals("Response Time.rtf")? price[0] : price[1]) * (Double.parseDouble(line) - (obj.equals("Response Time.rtf")? requirements[0] : requirements[1])); if(!debt.containsKey(approach)) { debt.put(approach, new LinkedHashMap<Integer, Double>()); } if(!debt.get(approach).containsKey(i)) { debt.get(approach).put(i, d); } else { d = debt.get(approach).get(i) + d; debt.get(approach).put(i, d); } total = total * (Double.parseDouble(line)) ; htotal = htotal + 1 / Double.parseDouble(line) ; i++; no++; } } reader.close(); //System.out.print("t"+total+"\n"); // if(obj.equals("Response Time.rtf")) { // return (Math.pow(total, 1.0/no) - 0.05814646509491475) / (0.1185653677302746-0.05814646509491475); // } else { // return (Math.pow(total, 1.0/no) - 4.129254192004044) / (4.808091886417567-4.129254192004044); if(obj.equals("Response Time.rtf") || obj.equals("Throughput.rtf") ) { double t = obj.equals("Throughput.rtf")? 1/total : total; if(Math.pow(t, 1.0/no) > RTmax) { RTmax = Math.pow(t, 1.0/no); } if(Math.pow(t, 1.0/no) < RTmin) { RTmin = Math.pow(t, 1.0/no); } RTmap.put(approach, Math.pow(t, 1.0/no)); } else { if(Math.pow(total, 1.0/no) > Emax) { Emax = Math.pow(total, 1.0/no); } if(Math.pow(total, 1.0/no) < Emin) { Emin = Math.pow(total, 1.0/no); } Emap.put(approach, Math.pow(total, 1.0/no)); } double mean_no = no; double mean = mean_total/mean_no; double std = 0.0; for (double l : list) { std += Math.pow(l - mean, 2); } std = Math.pow(std, 0.5); double gsd = readGSD(list.toArray(new Double[list.size()]),Math.pow(bd.doubleValue(), 1.0/no)); System.out.print("New Gmean: " + approach +", "+obj+"="+Math.pow(bd.doubleValue(), 1.0/no)+ ", G-SD="+gsd+"\n"); System.out.print("Mean: " + approach +", "+obj+"="+(mean_total/mean_no)+ ", STD=" + std+ "\n"); //System.out.print("GSD: " + approach +", "+obj+"="+gsd+"\n"); //System.out.print("CI: " + approach +", "+obj+"=["+(Math.pow(total, 1.0/no)-1.96*gsd/Math.sqrt(list.size())) + // ", " + (Math.pow(total, 1.0/no)+1.96*gsd/Math.sqrt(list.size())) +"]\n"); //System.out.print("GVAR: " + approach +", "+obj+"="+(gsd*gsd)+"\n"); if(obj.equals("Energy.rtf")) { Double[] v = log(list.toArray(new Double[list.size()])); //Double[] v = list.toArray(new Double[list.size()]); double[] l = new double[v.length]; for (int k = 0 ; k < v.length;k++) { l[k] = v[k]; //System.out.print(l[k]+"\n"); } log_values.put(approach, l); values.put(approach, list.toArray(new Double[list.size()])); } // if(obj.equals("Throughput.rtf")) { // Double[] v = list.toArray(new Double[list.size()]); // //Double[] v = list.toArray(new Double[list.size()]); // double[] l = new double[v.length]; // for (int k = 0 ; k < v.length;k++) { // l[k] = 1/v[k]; // //System.out.print(l[k]+"\n"); // log_values.put(approach, l); // if(obj.equals("Cost.rtf")) { // Double[] v = list.toArray(new Double[list.size()]); // //Double[] v = list.toArray(new Double[list.size()]); // double[] l = new double[v.length]; // for (int k = 0 ; k < v.length;k++) { // l[k] = v[k]; // //System.out.print(l[k]+"\n"); // log_values_add.put(approach, l); htotal = no / htotal; if(!surface.containsKey(approach+obj)) { surface.put(approach+obj, list); } return Math.pow(total, 1.0/no); } private static double IGD(String approach) { double rt = (RTmap.get(approach) - RTmin) / (RTmax - RTmin); double e = (Emap.get(approach) - Emin) / (Emax - Emin); // double toN = Math.pow(Math.pow((rt - 1),2) + Math.pow((e - 1),2), 0.5)/2; // double toI = Math.pow(Math.pow((rt - 0),2) + Math.pow((e - 0),2), 0.5)/2; // return toN - toI; return Math.pow(Math.pow((rt - 0),2) + Math.pow((e - 0),2), 0.5)/2; } private static double HV(String approach) { double rt = (RTmap.get(approach) - RTmin) / (RTmax - RTmin); double e = (Emap.get(approach) - Emin) / (Emax - Emin); //System.out.print((1 - rt) + "*"+(1 - e)+"\n"); return (1 - rt) * (1 - e); } private static double readP(String name, double dp) throws Throwable { BufferedReader reader = new BufferedReader(new FileReader(new File(name))); String line = null; int i = 0; int no = 0; List<Double> list = new ArrayList<Double>(); while((line = reader.readLine()) != null) { if(Double.parseDouble(line) != 0 && i < startIndex) { i++; continue; } if(Double.parseDouble(line) != 0) { list.add(Double.parseDouble(line)) ; i++; no++; } } int p = (int)Math.round(dp * no); reader.close(); Collections.sort(list); return list.get(p); } private static final int SCALE = 10; private static final int ROUNDING_MODE = BigDecimal.ROUND_HALF_DOWN; private static BigDecimal nthRoot(final int n, final BigDecimal a, final BigDecimal p) { if (a.compareTo(BigDecimal.ZERO) < 0) { throw new <API key>("nth root can only be calculated for positive numbers"); } if (a.equals(BigDecimal.ZERO)) { return BigDecimal.ZERO; } BigDecimal xPrev = a; BigDecimal x = a.divide(new BigDecimal(n), SCALE, ROUNDING_MODE); // starting "guessed" value... while (x.subtract(xPrev).abs().compareTo(p) > 0) { xPrev = x; x = BigDecimal.valueOf(n - 1.0) .multiply(x) .add(a.divide(x.pow(n - 1), SCALE, ROUNDING_MODE)) .divide(new BigDecimal(n), SCALE, ROUNDING_MODE); } return x; } }
[![werdlists/http-security](https://img.shields.io/badge/<API key>.svg?logo=github&style=popout&longCache=true)](# "werdlists/http-security") |&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_Folder&nbsp;&nbsp;Name_&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| _Description of Contents_ |: | [<API key>](<API key>.txt) | Abnormal HTTP traffic including [SQL injection](https://wikipedia.org/wiki/SQL_injection) attacks | [abnormal-uri-rfc](abnormal-uri-rfc.txt) | Abnormal URI's from [RFC3986 Section 5.4.2](https://tools.ietf.org/html/rfc3986#section-5.4.2) | [all-multiproxy-list](all-multiproxy-list.txt) | [anonymous and non-anonymous proxy list](http://multiproxy.org/txt_all/proxy.txt) | [apache-pfs-crypto](apache-pfs-crypto.conf) | Apache [Perfect Forward Secrecy](https: | [<API key>](<API key>.txt) | [anonymous proxy list](http://multiproxy.org/txt_anon/proxy.txt) | [<API key>](<API key>.txt) | Content Security Policy directives from HTTP replies | [<API key>](<API key>.txt) | Content Security Policy directives via [CSP.com](https://<API key>.com) | [<API key>](<API key>.txt) | Content Security Policy HTTP response headers via [CSP.com](https://<API key>.com) | [<API key>](<API key>.txt) | Content Security Policy sources via [CSP.com](https://<API key>.com) | [csp-header-apache](csp-header-apache.conf) | `<API key>` HTTP response header [Apache](https://httpd.apache.org) config | [csp-header-iis](csp-header-iis.conf) | `<API key>` HTTP response header [IIS](https://iis.net) config | [csp-header-nginx](csp-header-nginx.conf) | `<API key>` HTTP response header [NGINX](https://nginx.com) config | [<API key>](<API key>.txt) | <https://danwin1210.me/onions.php?format=text> | [<API key>](<API key>.txt) | words parsed from the [Go implementation of dirsearch](https: | [example-uri-refs](example-uri-refs.txt) | Example URI's from the [RFC3986](https://tools.ietf.org/html/rfc3986 "Uniform Resource Identifier (URI): Generic Syntax") URI specification issues list | [<API key>](<API key>.csv) | Info and PEM's on Certificate Authorities used by Mozilla | [ocsp-urls-list](ocsp-urls-list.txt) | list of [OCSP](https://wikipedia.org/wiki/<API key>) URL's | [onion-cab-list](onion-cab-list.txt) | list of TOR sites that used to be hosted on `onion.cab` via <https://web.archive.org/web/*/onion.cab/list.php> | [onion-links-list](onion-links-list.txt) | List of [.onion](https://wikipedia.org/wiki/.onion) sites verified in 2017 left on `pastebin.com` | [proc-model-defs](proc-model-defs.txt) | [https://html.spec.whatwg.org/multipage/webappapis.html#definitions-2]("") | [rails-secret-tokens](rails-secret-tokens.txt) | [Ruby on Rails](http://rubyonrails.org) secret authorization token string values | [<API key>](<API key>.txt) | [Referrer Policy](https://w3.org/TR/referrer-policy/) directives | [<API key>](<API key>.txt) | [RFC1918](https://tools.ietf.org/html/rfc1918 "Address Allocations for Private Internets") based [IPv4 private network address spaces](https://wikipedia.org/wiki/Private_network [<API key>](<API key>.txt) | list of web scripting media types | [snort-http-inspect](snort-http-inspect.txt) | Snort HTTP inspect module global configuration variables | [<API key>](<API key>.json.xz) | [HSTS](https: | [uri-spec-issues](uri-spec-issues.html) | Messages to the URI-WG mailing list about ambiguous URI syntax | [<API key>](<API key>.txt) | Commonly lucrative HTTP GET query variable names | [<API key>](<API key>.txt) | Typical HTTP GET query variable values | [<API key>](<API key>.md) | A web developer security checklist from <https: | [<API key>](<API key>.csv) | Examples in (URL Standard)[https://url.spec.whatwg.org] * * *
webpackHotUpdate(3,[ function(module, exports, __webpack_require__) { var React = __webpack_require__(2); var ReactDOM = __webpack_require__(158); var bootstrap = __webpack_require__(159); var formStyle = { marginTop: '20%' }; var buttonStyle = { width: '100%' }; var smallFont = { fontSize: '0.8em' }; var LoginBox = React.createClass({displayName: "LoginBox", render: function(){ return( React.createElement(bootstrap.Grid, null, React.createElement(LoginForm, null) ) ); } }); var LoginForm = React.createClass({displayName: "LoginForm", render: function(){ return( React.createElement("form", {method: "post", action: "#", style: formStyle}, React.createElement(bootstrap.Row, {className: "show-grid"}, React.createElement(bootstrap.Col, {xs: 10, xsOffset: 1, md: 6, mdOffset: 3}, React.createElement("h3", null, React.createElement("center", null, React.createElement("strong", null, ""))), React.createElement("hr", null), React.createElement(bootstrap.Input, {type: "text", name: "username", placeholder: "", required: true}), React.createElement(bootstrap.Input, {type: "password", name: "password", placeholder: "", required: true}), React.createElement(bootstrap.Button, {bsStyle: "primary", style: buttonStyle, type: "submit"}, ""), React.createElement("h5", null, React.createElement("center", null, React.createElement("a", {href: "#", style: smallFont}, ""))), React.createElement("h5", null, React.createElement("center", null, React.createElement("a", {href: "#", style: smallFont}, ""))) ) ) ) ); } }); ReactDOM.render(React.createElement(LoginBox, null), document.getElementById("content")); } ])
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="fr"> <head> <!-- Generated by javadoc (1.8.0_25) on Fri Jul 24 14:21:34 CEST 2015 --> <title>Uses of Package com.robocorp2.API</title> <meta name="date" content="2015-07-24"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><! try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package com.robocorp2.API"; } } catch(err) { } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar.top"> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../com/robocorp2/API/package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/robocorp2/API/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.top"> </a></div> <div class="header"> <h1 title="Uses of Package com.robocorp2.API" class="title">Uses of Package<br>com.robocorp2.API</h1> </div> <div class="contentContainer">No usage of com.robocorp2.API</div> <div class="bottomNav"><a name="navbar.bottom"> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../com/robocorp2/API/package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/robocorp2/API/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip.navbar.bottom"> </a></div> </body> </html>
#include "envoy/config/core/v3/base.pb.h" #include "common/network/address_impl.h" #include "common/network/listener_impl.h" #include "common/network/utility.h" #include "test/common/network/<API key>.h" #include "test/mocks/network/mocks.h" #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using testing::_; using testing::Invoke; using testing::Return; namespace Envoy { namespace Network { namespace { static void errorCallbackTest(Address::IpVersion version) { // Force the error callback to fire by closing the socket under the listener. We run this entire // test in the forked process to avoid confusion when the fork happens. Api::ApiPtr api = Api::createApiForTest(); Event::DispatcherPtr dispatcher(api->allocateDispatcher()); auto socket = std::make_shared<Network::TcpListenSocket>( Network::Test::<API key>(version), nullptr, true); Network::<API key> listener_callbacks; Network::<API key> connection_handler; Network::ListenerPtr listener = dispatcher->createListener(socket, listener_callbacks, true); Network::ClientConnectionPtr client_connection = dispatcher-><API key>( socket->localAddress(), Network::Address::<API key>(), Network::Test::<API key>(), nullptr); client_connection->connect(); StreamInfo::StreamInfoImpl stream_info(dispatcher->timeSource()); EXPECT_CALL(listener_callbacks, onAccept_(_)) .WillOnce(Invoke([&](Network::ConnectionSocketPtr& accepted_socket) -> void { Network::ConnectionPtr conn = dispatcher-><API key>( std::move(accepted_socket), Network::Test::<API key>(), stream_info); client_connection->close(ConnectionCloseType::NoFlush); conn->close(ConnectionCloseType::NoFlush); socket->close(); })); dispatcher->run(Event::Dispatcher::RunType::Block); } class <API key> : public testing::TestWithParam<Address::IpVersion> {}; <API key>(IpVersions, <API key>, testing::ValuesIn(TestEnvironment::<API key>()), TestUtility::<API key>); TEST_P(<API key>, ErrorCallback) { <API key>(errorCallbackTest(GetParam()), ".*listener accept failure.*"); } class TestListenerImpl : public ListenerImpl { public: TestListenerImpl(Event::DispatcherImpl& dispatcher, SocketSharedPtr socket, ListenerCallbacks& cb, bool bind_to_port) : ListenerImpl(dispatcher, std::move(socket), cb, bind_to_port) {} MOCK_METHOD(Address::<API key>, getLocalAddress, (os_fd_t fd)); }; using ListenerImplTest = <API key>; <API key>(IpVersions, ListenerImplTest, testing::ValuesIn(TestEnvironment::<API key>()), TestUtility::<API key>); // Test that socket options are set after the listener is setup. TEST_P(ListenerImplTest, <API key>) { Network::<API key> listener_callbacks; Network::<API key> connection_handler; auto socket = std::make_shared<TcpListenSocket>( Network::Test::<API key>(version_), nullptr, true); std::shared_ptr<MockSocketOption> option = std::make_shared<MockSocketOption>(); socket->addOption(option); EXPECT_CALL(*option, setOption(_, envoy::config::core::v3::SocketOption::STATE_LISTENING)) .WillOnce(Return(true)); TestListenerImpl listener(dispatcherImpl(), socket, listener_callbacks, true); } // Test that an exception is thrown if there is an error setting socket options. TEST_P(ListenerImplTest, <API key>) { Network::<API key> listener_callbacks; Network::<API key> connection_handler; auto socket = std::make_shared<TcpListenSocket>( Network::Test::<API key>(version_), nullptr, true); std::shared_ptr<MockSocketOption> option = std::make_shared<MockSocketOption>(); socket->addOption(option); EXPECT_CALL(*option, setOption(_, envoy::config::core::v3::SocketOption::STATE_LISTENING)) .WillOnce(Return(false)); <API key>(TestListenerImpl(dispatcherImpl(), socket, listener_callbacks, true), <API key>, fmt::format("cannot set post-listen socket option on socket: {}", socket->localAddress()->asString())); } TEST_P(ListenerImplTest, UseActualDst) { auto socket = std::make_shared<TcpListenSocket>( Network::Test::<API key>(version_), nullptr, true); auto socketDst = std::make_shared<TcpListenSocket>(alt_address_, nullptr, false); Network::<API key> listener_callbacks1; Network::<API key> connection_handler; // Do not redirect since use_original_dst is false. Network::TestListenerImpl listener(dispatcherImpl(), socket, listener_callbacks1, true); Network::<API key> listener_callbacks2; Network::TestListenerImpl listenerDst(dispatcherImpl(), socketDst, listener_callbacks2, false); Network::ClientConnectionPtr client_connection = dispatcher_-><API key>( socket->localAddress(), Network::Address::<API key>(), Network::Test::<API key>(), nullptr); client_connection->connect(); EXPECT_CALL(listener, getLocalAddress(_)).Times(0); StreamInfo::StreamInfoImpl stream_info(dispatcher_->timeSource()); EXPECT_CALL(listener_callbacks2, onAccept_(_)).Times(0); EXPECT_CALL(listener_callbacks1, onAccept_(_)) .WillOnce(Invoke([&](Network::ConnectionSocketPtr& accepted_socket) -> void { Network::ConnectionPtr conn = dispatcher_-><API key>( std::move(accepted_socket), Network::Test::<API key>(), stream_info); EXPECT_EQ(*conn->localAddress(), *socket->localAddress()); client_connection->close(ConnectionCloseType::NoFlush); conn->close(ConnectionCloseType::NoFlush); dispatcher_->exit(); })); dispatcher_->run(Event::Dispatcher::RunType::Block); } TEST_P(ListenerImplTest, <API key>) { auto socket = std::make_shared<TcpListenSocket>(Network::Test::getAnyAddress(version_), nullptr, true); Network::<API key> listener_callbacks; Network::<API key> connection_handler; // Do not redirect since use_original_dst is false. Network::TestListenerImpl listener(dispatcherImpl(), socket, listener_callbacks, true); auto local_dst_address = Network::Utility::getAddressWithPort( *Network::Test::<API key>(version_), socket->localAddress()->ip()->port()); Network::ClientConnectionPtr client_connection = dispatcher_-><API key>( local_dst_address, Network::Address::<API key>(), Network::Test::<API key>(), nullptr); client_connection->connect(); EXPECT_CALL(listener, getLocalAddress(_)).WillOnce(Return(local_dst_address)); StreamInfo::StreamInfoImpl stream_info(dispatcher_->timeSource()); EXPECT_CALL(listener_callbacks, onAccept_(_)) .WillOnce(Invoke([&](Network::ConnectionSocketPtr& socket) -> void { Network::ConnectionPtr conn = dispatcher_-><API key>( std::move(socket), Network::Test::<API key>(), stream_info); EXPECT_EQ(*conn->localAddress(), *local_dst_address); client_connection->close(ConnectionCloseType::NoFlush); conn->close(ConnectionCloseType::NoFlush); dispatcher_->exit(); })); dispatcher_->run(Event::Dispatcher::RunType::Block); } // Test for the correct behavior when a listener is configured with an ANY address that allows // receiving IPv4 connections on an IPv6 socket. In this case the address instances of both // local and remote addresses of the connection should be IPv4 instances, as the connection really // is an IPv4 connection. TEST_P(ListenerImplTest, <API key>) { auto option = std::make_unique<MockSocketOption>(); auto options = std::make_shared<std::vector<Network::Socket::<API key>>>(); EXPECT_CALL(*option, setOption(_, envoy::config::core::v3::SocketOption::STATE_PREBIND)) .WillOnce(Return(true)); options->emplace_back(std::move(option)); auto socket = std::make_shared<TcpListenSocket>(Network::Test::getAnyAddress(version_, true), options, true); Network::<API key> listener_callbacks; Network::<API key> connection_handler; ASSERT_TRUE(socket->localAddress()->ip()->isAnyAddress()); // Do not redirect since use_original_dst is false. Network::TestListenerImpl listener(dispatcherImpl(), socket, listener_callbacks, true); auto listener_address = Network::Utility::getAddressWithPort( *Network::Test::<API key>(version_), socket->localAddress()->ip()->port()); auto local_dst_address = Network::Utility::getAddressWithPort( *Network::Utility::<API key>(), socket->localAddress()->ip()->port()); Network::ClientConnectionPtr client_connection = dispatcher_-><API key>( local_dst_address, Network::Address::<API key>(), Network::Test::<API key>(), nullptr); client_connection->connect(); EXPECT_CALL(listener, getLocalAddress(_)) .WillOnce(Invoke([](os_fd_t fd) -> Address::<API key> { return Address::addressFromFd(fd); })); StreamInfo::StreamInfoImpl stream_info(dispatcher_->timeSource()); EXPECT_CALL(listener_callbacks, onAccept_(_)) .WillOnce(Invoke([&](Network::ConnectionSocketPtr& socket) -> void { Network::ConnectionPtr conn = dispatcher_-><API key>( std::move(socket), Network::Test::<API key>(), stream_info); EXPECT_EQ(conn->localAddress()->ip()->version(), conn->remoteAddress()->ip()->version()); EXPECT_EQ(conn->localAddress()->asString(), local_dst_address->asString()); EXPECT_EQ(*conn->localAddress(), *local_dst_address); client_connection->close(ConnectionCloseType::NoFlush); conn->close(ConnectionCloseType::NoFlush); dispatcher_->exit(); })); dispatcher_->run(Event::Dispatcher::RunType::Block); } TEST_P(ListenerImplTest, <API key>) { testing::InSequence s1; auto socket = std::make_shared<TcpListenSocket>(Network::Test::getAnyAddress(version_), nullptr, true); <API key> listener_callbacks; <API key> <API key>; TestListenerImpl listener(dispatcherImpl(), socket, listener_callbacks, true); // When listener is disabled, the timer should fire before any connection is accepted. listener.disable(); ClientConnectionPtr client_connection = dispatcher_-><API key>(socket->localAddress(), Address::<API key>(), Network::Test::<API key>(), nullptr); client_connection-><API key>(<API key>); client_connection->connect(); EXPECT_CALL(listener_callbacks, onAccept_(_)).Times(0); EXPECT_CALL(<API key>, onEvent(_)) .WillOnce(Invoke([&](Network::ConnectionEvent event) -> void { EXPECT_EQ(event, Network::ConnectionEvent::Connected); dispatcher_->exit(); })); dispatcher_->run(Event::Dispatcher::RunType::Block); // When the listener is re-enabled, the pending connection should be accepted. listener.enable(); EXPECT_CALL(listener, getLocalAddress(_)) .WillOnce(Invoke([](os_fd_t fd) -> Address::<API key> { return Address::addressFromFd(fd); })); EXPECT_CALL(listener_callbacks, onAccept_(_)).WillOnce(Invoke([&](ConnectionSocketPtr&) -> void { client_connection->close(ConnectionCloseType::NoFlush); })); EXPECT_CALL(<API key>, onEvent(_)) .WillOnce(Invoke([&](Network::ConnectionEvent event) -> void { EXPECT_NE(event, Network::ConnectionEvent::Connected); dispatcher_->exit(); })); dispatcher_->run(Event::Dispatcher::RunType::Block); } } // namespace } // namespace Network } // namespace Envoy
package org.openestate.io.is24_xml.xml; import javax.xml.bind.annotation.adapters.XmlAdapter; public class Adapter23 extends XmlAdapter<String, Long> { public Long unmarshal(String value) { return (org.openestate.io.is24_xml.Is24XmlUtils.parseZahl5(value)); } public String marshal(Long value) { return (org.openestate.io.is24_xml.Is24XmlUtils.printZahl5(value)); } }
import React, { Component } from 'react'; import { CardDeck, Card, CardText, CardBlock, CardTitle} from 'reactstrap'; class About extends Component { render() { return ( <div> <CardDeck> <Card> <CardBlock> <CardTitle>Mission</CardTitle> <CardText>Natural Goodness Co-op is a place where people can access cheaper food products for their families, the focus is on organic products.</CardText> </CardBlock> </Card> <Card> <CardBlock> <CardTitle>Now</CardTitle> <CardText>Orders are currently handled by sending out an email with an excel order form to each participant, they fill it out and return it completed. These spreadsheets are then collated and fill requests are sent on the facebook group page.</CardText> </CardBlock> </Card> <Card> <CardBlock> <CardTitle>Future</CardTitle> <CardText>This website aims to provide an application that greatly streamlines the process and provides better visibility of order quantities to all participants.</CardText> </CardBlock> </Card> <Card> <CardBlock> <CardTitle>Contribute</CardTitle> <CardText>The application is being developed as an open source project, if you wish to help contribute please request at the <a href="https://github.com/danielemery/natural-goodness" target="_blank" rel="noopener noreferrer">GitHub Repository</a>.</CardText> </CardBlock> </Card> </CardDeck> </div> ); } } export default About;
package de.visorapp.visor.threads; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.util.Log; import de.visorapp.visor.BitmapRenderer; import de.visorapp.visor.NativeYuvDecoder; public class BitmapCreateThread implements Runnable { /** * too many simultan instances will end up in a huge memory leak * set to 0 to disable limitations. * * Old Info: * It seems that it would cause unexpected behaviour if we disable the max * instances, because the rendered images get drawed unordered. * If your device is slow, it is better to have only one single thread rendering the image * in the background, wait for it and then render the next one. * * New Info: * On my new telephone LG G4 it works much better with a higher instances value. */ private static final int MAX_INSTANCES = 3; /** * count all instances. */ private static int instanceCounter = 0; private int previewWidth; private int previewHeight; private int targetWidth; private int targetHeight; private int jpegQuality; private BitmapRenderer renderer; private byte[] yuvDataArray; private boolean useRgb; private int[] rgbArray; private boolean mirror; private Bitmap renderedBitmap; /** * returns an instance of the task * * @param yuvDataArray * @param renderer * @return */ public static BitmapCreateThread getInstance(int[] rgb, byte[] yuvDataArray, BitmapRenderer renderer, int previewWidth, int previewHeight, int targetWidth, int targetHeight, int jpegQuality, boolean useRgb, boolean mirror) { if (instanceCounter >= MAX_INSTANCES) { Log.d("BitmapCreateThread", "Thread Creation blocked, because we reached our MAX_INSTANCES."); return null; } BitmapCreateThread instance = new BitmapCreateThread(); instanceCounter++; // Log.d("BitmapCreateThread", "BitmapCreateThreads: " + instanceCounter); instance.setYuvDataArray(yuvDataArray); instance.setPreviewWidth(previewWidth); instance.setPreviewHeight(previewHeight); instance.setTargetWidth(targetWidth); instance.setTargetHeight(targetHeight); instance.setJpegQuality(jpegQuality); instance.setRenderer(renderer); instance.setUseRgb(useRgb); instance.setRgbArray(rgb); instance.setMirror(mirror); return instance; } public void setJpegQuality(int jpegQuality) { this.jpegQuality = jpegQuality; } public void setPreviewHeight(int previewHeight) { this.previewHeight = previewHeight; } public void setPreviewWidth(int previewWidth) { this.previewWidth = previewWidth; } public void setRenderer(BitmapRenderer renderer) { this.renderer = renderer; } public void setYuvDataArray(byte[] yuvDataArray) { this.yuvDataArray = yuvDataArray; } public void setMirror(boolean mirror) { this.mirror = mirror; } /** * the actual hard work. * @param yuvData */ protected void createBitmap(byte[] yuvData) { // YuvImage yuvImage = new YuvImage(yuvData, ImageFormat.NV21, previewWidth, previewHeight, null); // greyscale bitmap rendering is a bit faster than yuv-to-rgb convert. //int[] rgbData; // different strategies (for performance): use greyscale in preview mode and rgb in picture mode. //if(!useRgb) rgbData = this.<API key>(yuvData, previewWidth, previewHeight); if(!useRgb) this.<API key>(rgbArray, yuvData, previewWidth, previewHeight); else this.decodeYuvToRgb(rgbArray, yuvData, previewWidth, previewHeight); if(renderedBitmap == null) { renderedBitmap = Bitmap.createBitmap(previewWidth, previewHeight, android.graphics.Bitmap.Config.ARGB_8888); } renderedBitmap.setPixels(rgbArray, 0, previewWidth, 0, 0, previewWidth, previewHeight); if (mirror) { renderedBitmap = <API key>(renderedBitmap); } // scaling (costs a lot of memory) // renderedBitmap = Bitmap.createScaledBitmap(renderedBitmap, targetWidth, targetHeight, true); } /** * custom scaling function. replaces createScaledBitmap. * * DO NOT USE. the bitmap gets scaled in "onDraw" via a Matrix. * * @param bitmap * @param newWidth * @param newHeight * @return */ public static Bitmap scaleBitmap(Bitmap bitmap, int newWidth, int newHeight) { Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight, android.graphics.Bitmap.Config.ARGB_8888); float scaleX = newWidth / (float) bitmap.getWidth(); float scaleY = newHeight / (float) bitmap.getHeight(); float pivotX = 0; float pivotY = 0; Matrix scaleMatrix = new Matrix(); scaleMatrix.setScale(scaleX, scaleY, pivotX, pivotY); Canvas canvas = new Canvas(scaledBitmap); canvas.setMatrix(scaleMatrix); canvas.drawBitmap(bitmap, 0, 0, new Paint(Paint.FILTER_BITMAP_FLAG)); return scaledBitmap; } public static Bitmap <API key>(Bitmap bitmap) { Matrix m = new Matrix(); m.preScale(-1, 1); return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, false); } private void <API key>(int[] rgb, byte[] yuvData, int width, int height) { //int pixelCount = width * height; //)//int[] out = new int[pixelCount]; NativeYuvDecoder.YUVtoRGBGreyscale(yuvData, width, height, rgb); //return out; } // NOTE does change the colors private void <API key>(int[] rgb, byte[] yuvData, int width, int height) { //int pixelCount = width * height; // int[] out = new int[pixelCount]; NativeYuvDecoder.YUVtoRBGA(yuvData, width, height, rgb); //return out; } private void decodeYuvToRgb(int[] rgb, byte[] nv21, int width, int height) { int frameSize = width * height; //int[] rgba = new int[frameSize + 1]; // Convert YUV to RGB for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) { int y = (0xff & ((int) nv21[i * width + j])); int u = (0xff & ((int) nv21[frameSize + (i >> 1) * width + (j & ~1) + 0])); int v = (0xff & ((int) nv21[frameSize + (i >> 1) * width + (j & ~1) + 1])); y = y < 16 ? 16 : y; int a0 = 1192 * (y - 16); int a1 = 1634 * (v - 128); int a2 = 832 * (v - 128); int a3 = 400 * (u - 128); int a4 = 2066 * (u - 128); int r = (a0 + a1) >> 10; int g = (a0 - a2 - a3) >> 10; int b = (a0 + a4) >> 10; /*int r = Math.round(1.164f * (y - 16) + 1.596f * (v - 128)); int g = Math.round(1.164f * (y - 16) - 0.813f * (v - 128) - 0.391f * (u - 128)); int b = Math.round(1.164f * (y - 16) + 2.018f * (u - 128));*/ r = r < 0 ? 0 : (r > 255 ? 255 : r); g = g < 0 ? 0 : (g > 255 ? 255 : g); b = b < 0 ? 0 : (b > 255 ? 255 : b); rgb[i * width + j] = 0xff000000 + (b << 16) + (g << 8) + r; } //return rgba; } /** * do the hard stuff. * @param yuvDataArray * @return */ protected void doInBackground(byte[] yuvDataArray) { this.createBitmap(yuvDataArray); } /** * after the hard stuff is done. */ protected void onPostExecute() { renderer.renderBitmap(renderedBitmap); instanceCounter } @Override public void run() { doInBackground(yuvDataArray); onPostExecute(); } public void setTargetWidth(int targetWidth) { this.targetWidth = targetWidth; } public void setTargetHeight(int targetHeight) { this.targetHeight = targetHeight; } public void setUseRgb(boolean useRgb) { this.useRgb = useRgb; } public void setRgbArray(int[] rgbArray) { this.rgbArray = rgbArray; } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (version 1.7.0_11) on Mon Apr 07 19:10:16 CEST 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class at.irian.ankor.ref.match.pattern.<API key> (Ankor - Project 0.2-SNAPSHOT API)</title> <meta name="date" content="2014-04-07"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class at.irian.ankor.ref.match.pattern.<API key> (Ankor - Project 0.2-SNAPSHOT API)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../at/irian/ankor/ref/match/pattern/<API key>.html" title="class in at.irian.ankor.ref.match.pattern">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?at/irian/ankor/ref/match/pattern/class-use/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class at.irian.ankor.ref.match.pattern.<API key>" class="title">Uses of Class<br>at.irian.ankor.ref.match.pattern.<API key></h2> </div> <div class="classUseContainer">No usage of at.irian.ankor.ref.match.pattern.<API key></div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../at/irian/ankor/ref/match/pattern/<API key>.html" title="class in at.irian.ankor.ref.match.pattern">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?at/irian/ankor/ref/match/pattern/class-use/<API key>.html" target="_top">Frames</a></li> <li><a href="<API key>.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small>Copyright & </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Practice.Leetcode.Array { class <API key> { public static void Main(string[] args) { int[] nums = { 4, 5, 6, 7, 0, 1, 2 }; <API key> a = new <API key>(); int result = a.Search(nums, 0); result = a.Search2(nums, 0); } public int Search(int[] nums, int target) { int start = 0; int end = nums.Length - 1; int point = 0; while (end > start && point == 0) { int mid = (start + end) / 2; if (nums[mid] < nums[mid - 1] && nums[mid] < nums[mid + 1]) point = mid; if (nums[mid] < nums[0]) { end = mid - 1; start = 0; } else { start = mid + 1; end = nums.Length - 1; } } int attempt1 = SearchHelper(nums, 0, point - 1, target); int attempt2 = SearchHelper(nums, point, nums.Length-1, target); return attempt1 != -1 ? attempt1 : attempt2; } public int SearchHelper(int[] nums, int start, int end, int target) { while (end >= start) { int mid = (start + end) / 2; if (nums[mid] == target) return mid; if (nums[mid] < target) start = mid + 1; if (nums[mid] > target) end = mid - 1; } return -1; } //Attempt 2: //Find inflextion point public int Search2(int[] nums, int target) { int start = 0; int end = nums.Length - 1; int point = -1; while(end > start && point == -1) { int mid = (start + end) / 2; //7,1,2,3,4,5,6 // 4, 5, 6, 7, 0, 1, 2 //Find the inflexion point if (nums[mid] < nums[mid-1] && nums[mid] < nums[mid+1]) { point = mid; } if(nums[mid] < nums[0]) { start = 0; end = mid - 1; } else { start = mid + 1; end = nums.Length - 1; } } int part1 = BinarySearch2(nums, target, 0, point - 1); int part2 = BinarySearch2(nums, target, point, nums.Length - 1); return part1 != -1 ? part1 : part2; } public int BinarySearch2(int[] nums, int target, int start, int end) { while(end>=start) { int mid = (start + end) / 2; if (nums[mid] == target) return mid; else if (nums[mid] > target) end = mid - 1; else if (nums[mid] < target) start = mid + 1; } return -1; } } }
<?php /** * Register a PHP function to resource method matching method_name * * @phpstub * * @param resource $server * @param string $method_name * @param string $function * * @return bool */ function <API key>($server, $method_name, $function) { }
using System; namespace Talifun.Commander.Command.Video { public static class GravityExtensions { public static string GetOverlayPosition(this Gravity gravity) { switch (gravity) { case Gravity.NorthWest: return "{0}:{1}"; case Gravity.North: return "(main_w/2)-(overlay_w/2):{1}"; case Gravity.NorthEast: return "main_w-overlay_w-{0}:{1}"; case Gravity.East: return "main_w-overlay_w-{0}:(main_h/2)-(overlay_h/2)"; case Gravity.SouthEast: return "main_w-overlay_w-{0}:main_h-overlay_h-{1}"; case Gravity.South: return "(main_w/2)-(overlay_w/2):main_h-overlay_h-{1}"; case Gravity.SouthWest: return "{0}:main_h-overlay_h-{1}"; case Gravity.West: return "{0}:(main_h/2)-(overlay_h/2)"; case Gravity.Center: return "(main_w/2)-(overlay_w/2):(main_h/2)-(overlay_h/2)"; default: throw new Exception(); } } } }
# <API key> Instructions: 1. For linux Install Mono -> bash rpm --import "http://keyserver.ubuntu.com/pks/lookup?op=get&search=<API key>" bash yum-config-manager --add-repo http://download.mono-project.com/repo/centos/ bash yum -y install mono-complete-5.8.0.127-0.xamarin.3.epel7.x86_64 1. If python 3 not installed, install python 3. For RHEL instructions are below-> cat <<'EOT' >> /etc/yum.repos.d/python34.repo [centos-sclo-rh] name=CentOS-7 - SCLo rh baseurl=http://mirror.centos.org/centos/7/sclo/$basearch/rh/ gpgcheck=0 enabled=1 gpgkey=file:///etc/pki/rpm-gpg/<API key> EOT # install python34 scl package bash yum -y install rh-python34 <API key> # cleanup python 34 repo file bash rm -f /etc/yum.repos.d/python34.repo 1. Enable python34 -> `scl enable rh-python34 bash` 1. Make sure Valkyrie2544.exe is present in the current folder (formerly Xena2544.exe) 1. Copy your x2544 config file to the script folder 1. Arguments to run this script * `-f <path_to_config_file>` : saved from Valkyrie2544.exe GUI with your config. * `[-s]` : enable smart search, if verify fails will resume the search at the half way point between the last verify attempt and the minimum search value. Otherwise it will just resume at the last verify attempt value minus the value threshhold. * `[-l <<API key>>]` : > Default : 7200 (2 hours) * `[-r <retry_attempts>]` : Maximum number of verify attempts for giving up > Default : 10 * `[-d]` : Enable debug mode * `[-p]` : Output PDF file. By default output of PDF report is disabled. Will cause a crash on linux usually as a pdf renderer is not installed. * `[-w]` : Enable windows mode. By default it will use the mono package to run the exe file. If running on windows this is not necessary. * `[-t <<API key>>]` : Modify original config to use the duration specified. > Default : 0 * `[-k <packet_size>+]` : Customize packet sizes for throughput testing * `[-a <acceptable_loss>]` : Specify number of packages which can be lost as a percentage ([0 - 100]) * `[-v <save_file_name>]` : Save config file which was created with the new arguments passed to this command. > Default : `./2bUsed.x2544` * `[-i <initial_tput>]` : Specify initial rate for throughput test * `[-M <max_tput>]` : Specify maximum rate for throughput test * `[-m <min_tput>]` : Specify minimum rate for throughput test * `[-o <resolution_tput>]` : Specify resolution for throughput testing * `[-n <mac_address> [<mac_address>]]` : First MAC address becomes source of first active entity and destination for second (if two exist). Vice versa for the optional second argument. * `[-c <connection_ip> [<connection_ip>]]` : First IP address becomes source of first active entity and destination for second (if two exist). Vice versa for the optional second argument. * `[-u {1|1k|4k|10k|100k|1M}]` : Specify hardware modifier flows. Default behavior is to apply this to source and destination IP addresses * `[-b]` : Apply flows to both MAC and IP addresses (overrides `[-e]`) * `[-e]` : Apply flows to MAC addresses only 1. Sample execution: > Runs a 60 second trial with a 600 second verify using the myconfig.x2544 configuration file. bash python XenaVerify.py -f myconfig.x2544 -s -l 600 -t 60 # Improvements to be done * Add debug logging * Add more customized options for modifying the running config
var assert = require('assert'); var BaseStrategy = require('../..').restartStrategies.BaseStrategy; var Supervisor = require('../..').Supervisor; describe('BaseStrategy', function() { describe('process()', function() { it('should error emit an error to the sup', function(done) { var sup = new Supervisor(BaseStrategy); var strat = sup.getRestartStrategy(); sup.on('error', function(err) { assert.ok(err); done(); }); strat.process(1); }); }); describe('mark()', function() { it('should work with all the same stamps', function() { var sup = new Supervisor(BaseStrategy, 3, 1); var strat = sup.getRestartStrategy(); assert.ok(strat.mark(1, 1000)); assert.ok(strat.mark(1, 1000)); assert.ok(!strat.mark(1, 1000)); //1,1,1 assert.strictEqual(strat.log[1].length, 3); }); it('should work with different stamps', function() { var sup = new Supervisor(BaseStrategy, 3, 1); var strat = sup.getRestartStrategy(); assert.ok(strat.mark(1, 1000)); assert.ok(strat.mark(1, 1000)); assert.ok(!strat.mark(1, 2000)); //1,1,2 assert.ok(strat.mark(1, 3000)); //1,2,3 assert.ok(!strat.mark(1, 3000)); //2,3,3 assert.strictEqual(strat.log[1].length, 3); }); it('emits the down event if not restart worthy', function(done) { //OneForOne, 3, 1 var sup = new Supervisor(); sup.on('down', function(ref) { assert.equal(ref.id, 'NOOP'); assert.strictEqual(ref.idx, 0); done(); }); sup.startChild({ id: 'NOOP', path: 'NOOP' }); }); }); });
type: post97 title: Processing Units categories: XAP97NET parent: <API key>.html weight: 300 {{<wbr>}} The processing unit is the unit of packaging and deployment in the GigaSpaces XAP platform. This section details the anatomy and details of the processing unit. It describes the various processing unit types, explains its directory structure, deployment descriptor, SLA attributes and how you can debug, run and deploy it on to the GigaSpaces XAP runtime environment. <hr/> - [Processing Unit Container](./<API key>.html){{<wbr>}} Describing the .NET Processing Unit Container and how to create and deploy it. - [Basic Processing Unit Container](./<API key>.html){{<wbr>}} Describing the built-in <API key> which is an extension of the <API key> class. - [Detailed Processing Unit Container](./<API key>.html){{<wbr>}} Describing the built-in <API key> which is an extension of the <API key> class. - [Interoperability Processing Unit Container](./<API key>.html){{<wbr>}} Creating and deploying a multi language processing unit. <hr/>
package com.snowplowanalytics.iglu.schemaddl.jsonschema.json4s // json4s import org.json4s._ import org.json4s.jackson.JsonMethods.parse import com.snowplowanalytics.iglu.schemaddl.jsonschema.Schema import com.snowplowanalytics.iglu.schemaddl.jsonschema.ToSchema import com.snowplowanalytics.iglu.schemaddl.jsonschema.properties.StringProperty.{Format, MaxLength, MinLength} import com.snowplowanalytics.iglu.schemaddl.jsonschema.json4s.implicits._ // specs2 import org.specs2.Specification class StringSpec extends Specification { def is = s2""" Check JSON Schema string specification parse correct minLength $e1 parse maxLength with ipv4 format $e2 parse unknown format $e3 """ def e1 = { val schema = parse( """ |{"minLength": 32} """.stripMargin) Schema.parse(schema) must beSome(Schema(minLength = Some(MinLength(32)))) } def e2 = { val schema = parse( """ |{"maxLength": 32, "format": "ipv4"} """.stripMargin) Schema.parse(schema) must beSome(Schema(maxLength = Some(MaxLength(32)), format = Some(Format.Ipv4Format))) } def e3 = { implicitly[ToSchema[JValue]] val schema = parse( """ |{"maxLength": 32, "format": "unknown"} """.stripMargin) Schema.parse(schema) must beSome(Schema(maxLength = Some(MaxLength(32)), format = Some(Format.CustomFormat("unknown")))) } }
# encoding: utf-8 require 'nokogumbo' require 'minitest/autorun' def parse_test(test_data) test = { script: :both } index = /(?:^#errors\n|\n#errors\n)/ =~ test_data abort "Expected #errors in\n#{test_data}" if index.nil? skip_amount = $~[0].length # Omit the final new line test[:data] = test_data[0...index] # Process the rest line by line lines = test_data[index+skip_amount..-1].split("\n") index = lines.find_index do |line| line == '#document-fragment' || line == '#document' || line == '#script-off' || line == '#script-on' || line == '#new-errors' end abort 'Expected #document' if index.nil? test[:errors] = lines[0...index] test[:new_errors] = [] if lines[index] == '#new-errors' index += 1 while !%w[#document-fragment #document #script-off #script-on].include?(lines[index]) test[:new_errors] << lines[index] index += 1 end end if lines[index] == '#document-fragment' test[:context] = lines[index+1].chomp.split(' ', 2) index += 2 end abort "failed to find fragment: #{index}: #{lines[index]}" if test_data.include?("#document-fragment") && test[:context].nil? if lines[index] =~ /#script-(on|off)/ test[:script] = $~[1].to_sym index += 1 end abort "Expected #document, got #{lines[index]}" unless lines[index] == '#document' index += 1 document = { type: test[:context] ? :fragment : :document, children: [] } open_nodes = [document] while index < lines.length abort "Expected '| ' but got #{lines[index]}" unless /^\| ( *)([^ ].*$)/ =~ lines[index] depth = $~[1].length if depth.odd? abort "Invalid nesting depth" else depth = depth / 2 end abort "Too deep" if depth >= open_nodes.length node = {} node_text = $~[2] if node_text[0] == '"' if node_text == '"' || node_text[-1] != '"' loop do index += 1 node_text << "\n" + lines[index] break if node_text[-1] == '"' end end node[:type] = :text node[:contents] = node_text[1..-2] elsif /^<!DOCTYPE ([^ >]*)(?: "([^"]*)" "(.*)")?>$/ =~ node_text node[:type] = :doctype node[:name] = $~[1] node[:public_id] = $~[2].nil? || $~[2].empty? ? nil : $~[2] node[:system_id] = $~[3].nil? || $~[3].empty? ? nil : $~[3] elsif /^$/ =~ node_text node[:type] = :comment node[:contents] = $~[1] elsif /^<(svg |math )?(.+)>$/ =~ node_text node[:type] = :element node[:ns] = $~[1].nil? ? nil : $~[1].rstrip node[:tag] = $~[2] node[:attributes] = [] node[:children] = [] elsif /^([^ ]+ )?([^=]+)="(.*)"$/ =~ node_text node[:type] = :attribute node[:ns] = $~[1].nil? ? nil : $~[1].rstrip node[:name] = $~[2] node[:value] = $~[3] elsif node_text == 'content' node[:type] = :template else abort "Unexpected node_text: #{node_text}" end if node[:type] == :attribute abort "depth #{depth} != #{open_nodes.length}" unless depth == open_nodes.length - 1 abort "type :#{open_nodes[-1][:type]} != :element" unless open_nodes[-1][:type] == :element abort "element has children" unless open_nodes[-1][:children].empty? open_nodes[-1][:attributes] << node elsif node[:type] == :template abort "depth #{depth} != #{open_nodes.length}" unless depth == open_nodes.length - 1 abort "type :#{open_nodes[-1][:type]} != :element" unless open_nodes[-1][:type] == :element abort "tag :#{open_nodes[-1][:tag]} != template" unless open_nodes[-1][:tag] == 'template' abort "template has children before the 'content'" unless open_nodes[-1][:children].empty? # Hack. We want the children of this template node to be reparented as # children of the template element. # XXX: Template contents are _not_ supposed to be children of the # template, but we currently mishandle this. open_nodes << open_nodes[-1] else open_nodes[depth][:children] << node open_nodes[depth+1..-1] = [] if node[:type] == :element open_nodes << node end end index += 1 end test[:document] = document test end class <API key> < Minitest::Test def assert_equal_or_nil(exp, act) if exp.nil? assert_nil act else assert_equal exp, act end end def compare_nodes(node, ng_node) case ng_node.type when Nokogiri::XML::Node::ELEMENT_NODE assert_equal node[:type], :element if node[:ns] refute_nil ng_node.namespace assert_equal node[:ns], ng_node.namespace.prefix end assert_equal node[:tag], ng_node.name attributes = ng_node.attributes assert_equal node[:attributes].length, attributes.length node[:attributes].each do |attr| if attr[:ns] value = ng_node["#{attr[:ns]}:#{attr[:name]}"] else value = attributes[attr[:name]].value end assert_equal attr[:value], value end assert_equal node[:children].length, ng_node.children.length, "Element <#{node[:tag]}> has wrong number of children: #{ng_node.children.map { |c| c.name }}" when Nokogiri::XML::Node::TEXT_NODE, Nokogiri::XML::Node::CDATA_SECTION_NODE # We preserve the CDATA in the tree, but the tests represent it as text. assert_equal node[:type], :text assert_equal node[:contents], ng_node.content when Nokogiri::XML::Node::COMMENT_NODE assert_equal node[:type], :comment assert_equal node[:contents], ng_node.content when Nokogiri::XML::Node::HTML_DOCUMENT_NODE assert_equal node[:type], :document assert_equal node[:children].length, ng_node.children.length when Nokogiri::XML::Node::DOCUMENT_FRAG_NODE assert_equal node[:type], :fragment assert_equal node[:children].length, ng_node.children.length when Nokogiri::XML::Node::DTD_NODE assert_equal node[:type], :doctype assert_equal node[:name], ng_node.name assert_equal_or_nil node[:public_id], ng_node.external_id assert_equal_or_nil node[:system_id], ng_node.system_id else flunk "Unknown node type #{ng_node.type} (expected #{node[:type]})" end end def run_test if @test[:context] ctx = @test[:context].join(':') doc = Nokogiri::HTML5::Document.new doc = Nokogiri::HTML5::DocumentFragment.new(doc, @test[:data], ctx, max_errors: @test[:errors].length + 10) else doc = Nokogiri::HTML5.parse(@test[:data], max_errors: @test[:errors].length + 10) end # Walk the tree. exp_nodes = [@test[:document]] act_nodes = [doc] children = [0] compare_nodes(exp_nodes[0], doc) while children.any? child_index = children[-1] exp = exp_nodes[-1] act = act_nodes[-1] if child_index == exp[:children].length exp_nodes.pop act_nodes.pop children.pop next end exp_child = exp[:children][child_index] act_child = act.children[child_index] compare_nodes(exp_child, act_child) children[-1] = child_index + 1 if exp_child.has_key?(:children) exp_nodes << exp_child act_nodes << act_child children << 0 end end # Test the errors. assert_equal @test[:errors].length, doc.errors.length # The new, standardized tokenizer errors live in @test[:new_errors]. Let's # match each one to exactly one error in doc.errors. Unfortunately, the # tests specify the column the error is detected, _not_ the column of the # start of the problematic HTML (e.g., the start of a character reference # or <![CDATA[) the way gumbo does. So check that Gumbo's column is no # later than the error's column. errors = doc.errors.map { |err| { line: err.line, column: err.column, code: err.str1 } } errors.reject! { |err| err[:code] == 'generic-parser' } error_regex = /^\((?<line>\d+):(?<column>\d+)(?:-\d+:\d+)?\) (?<code>.*)$/ @test[:new_errors].each do |err| assert_match(error_regex, err) m = err.match(error_regex) line = m[:line].to_i column = m[:column].to_i code = m[:code] idx = errors.index do |e| e[:line] == line && e[:code] == code && e[:column] <= column end # This error should be the first error in the list. #refute_nil(idx, "Expected to find error #{code} at #{line}:#{column}") assert_equal(0, idx, "Expected to find error #{code} at #{line}:#{column}") errors.delete_at(idx) end end end tc_path = File.expand_path('../html5lib-tests/tree-construction', __FILE__) Dir[File.join(tc_path, '*.dat')].each do |path| test_name = "<API key>" + File.basename(path, '.dat') .split(/[_-]/) .map { |s| s.capitalize } .join('') tests = [] File.open(path, "r", encoding: 'UTF-8') do |f| f.each("\n\n#data\n") do |test_data| if test_data.start_with?("#data\n") test_data = test_data[6..-1] end if test_data.end_with?("\n\n#data\n") test_data = test_data[0..-9] end tests << parse_test(test_data) end end klass = Class.new(<API key>) do tests.each_with_index do |test, index| next if test[:script] == :on; define_method "test_#{index}".to_sym do @test = test @index = index run_test end end end Object.const_set test_name, klass end # vim: set sw=2 sts=2 ts=8 et:
play2-doma-sample ============== bundle/sbt-doma-plugin.zipScala-2.10sbt-0.13<br> <br> See also: https://github.com/hina0118/sbt-doma-plugin
package org.granite.rest.handler; import java.util.List; public class SubListResponse<V> { private final int totalCount; private final List<V> responseValues; public SubListResponse(int totalCount, List<V> responseValues) { this.totalCount = totalCount; this.responseValues = responseValues; } public int getTotalCount() { return totalCount; } public List<V> getResponseValues() { return responseValues; } }
#!/bin/bash ## <API key>: Apache-2.0 set -e KW_SERVER_PATH=$KW_PATH/server KW_CLIENT_PATH=$KW_PATH/client export KLOCWORK_LTOKEN=/tmp/ltoken echo "$KW_SERVER_IP;$KW_SERVER_PORT;$KW_USER;$KW_LTOKEN" > $KLOCWORK_LTOKEN mkdir -p $CI_PROJECT_DIR/klocwork log_file=$CI_PROJECT_DIR/klocwork/build.log make clean > /dev/null $KW_CLIENT_PATH/bin/kwinject -w -o buildspec.txt make -j 8 | tee -a $log_file $KW_SERVER_PATH/bin/kwbuildproject --classic --force --url http://$KW_SERVER_IP:$KW_SERVER_PORT/embree buildspec.txt --tables-directory $CI_PROJECT_DIR/kw_tables | tee -a $log_file $KW_SERVER_PATH/bin/kwadmin --url http://$KW_SERVER_IP:$KW_SERVER_PORT/ load --force --name build-$CI_JOB_ID $KW_PROJECT_NAME $CI_PROJECT_DIR/kw_tables | tee -a $log_file # Store kw build name for check status later echo "build-$CI_JOB_ID" > $CI_PROJECT_DIR/klocwork/build_name
namespace RefAndPointer._NullRef { using System; using System.Runtime.CompilerServices; unsafe static class NullReference { public static ref T Null<T>() => ref Unsafe.AsRef<T>((void*)0); public static bool IsNull<T>(ref T x) => Unsafe.AsPointer(ref x) == (void*)0; } class Program { static void Main() { ref var x = ref NullReference.Null<int>(); Console.WriteLine(NullReference.IsNull(ref x)); // true Console.WriteLine(x); // <API key> } } }
package com.tim.smartparking; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.widget.Button; public class Chistopolskaya extends Activity implements OnClickListener { Button button1; Button button2; public static final String EXTRAS_BEACON = "extrasBeacon"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chistopolskaya); if (Build.VERSION.SDK_INT >= 21) { // Set the status bar to <API key> getWindow().setFlags(WindowManager.LayoutParams.<API key>, WindowManager.LayoutParams.<API key>); // Set paddingTop of toolbar to height of status bar. // Fixes statusbar covers toolbar issue } button1 = (Button) findViewById(R.id.button1); button2 = (Button) findViewById(R.id.button2); button1.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.chistopolskaya, menu); return true; } public void onClick(View v) { if(v.getId() == R.id.button1) { Intent intent = new Intent(); intent.setClass(this, BeaconMap.class); startActivity(intent); finish(); } } }
/** * * @file writer * @author chosen0ne(louzhenlin86@126.com) * @date 2015/01/19 17:08:01 */ #include "protos/Sample.pb.h" #include <string> #include <iostream> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> int main(int argc, char* argv[]) { int fd, count; char buf[1024]; count = atoi(argv[1]); std::cout << "count: " << count << std::endl; fd = open("buf", O_RDWR | O_CREAT, 0644); if (fd == -1) { std::cout << "failed to open file" << std::endl; return -1; } Sample::Sample sample; for (int i = 0; i < count; i++) { sample.set_id(i); sample.set_ip(i + 100); sample.set_name("kobe"); sample.clear_addr_list(); for (int j = i; j < i + 100; j++) { sample.add_addr_list(j); } int size = sample.ByteSize(); int nwritten = write(fd, &size, sizeof(size)); if (nwritten == -1) { std::cout << "failed to write" << std::endl; return -1; } if (!sample.SerializeToArray(buf, 1024)) { std::cout << "failed to serialize" << std::endl; return -1; } nwritten = write(fd, buf, size); if (nwritten == -1) { std::cout << "failed to write" << std::endl; return -1; } } return 0; }
import ClipboardJS from "clipboard"; import {add, formatISO, set} from "date-fns"; import ConfirmDatePlugin from "flatpickr/dist/plugins/confirmDate/confirmDate"; import $ from "jquery"; import tippy, {hideAll} from "tippy.js"; import <API key> from "../templates/<API key>.hbs"; import <API key> from "../templates/no_arrow_popover.hbs"; import <API key> from "../templates/<API key>.hbs"; import <API key> from "../templates/<API key>.hbs"; import <API key> from "../templates/<API key>.hbs"; import <API key> from "../templates/<API key>.hbs"; import <API key> from "../templates/<API key>.hbs"; import <API key> from "../templates/<API key>.hbs"; import * as blueslip from "./blueslip"; import * as buddy_data from "./buddy_data"; import * as compose_actions from "./compose_actions"; import * as compose_state from "./compose_state"; import * as compose_ui from "./compose_ui"; import * as condense from "./condense"; import * as emoji_picker from "./emoji_picker"; import * as feature_flags from "./feature_flags"; import * as giphy from "./giphy"; import * as hash_util from "./hash_util"; import {$t} from "./i18n"; import * as message_edit from "./message_edit"; import * as <API key> from "./<API key>"; import * as message_lists from "./message_lists"; import * as message_viewport from "./message_viewport"; import * as muted_topics from "./muted_topics"; import * as muted_topics_ui from "./muted_topics_ui"; import * as muted_users from "./muted_users"; import * as muted_users_ui from "./muted_users_ui"; import * as narrow from "./narrow"; import * as narrow_state from "./narrow_state"; import * as overlays from "./overlays"; import {page_params} from "./page_params"; import * as people from "./people"; import * as popover_menus from "./popover_menus"; import * as realm_playground from "./realm_playground"; import * as reminder from "./reminder"; import * as resize from "./resize"; import * as rows from "./rows"; import * as settings_data from "./settings_data"; import * as stream_popover from "./stream_popover"; import * as user_groups from "./user_groups"; import * as user_status from "./user_status"; import * as user_status_ui from "./user_status_ui"; import * as util from "./util"; let <API key>; let <API key>; let <API key>; let <API key>; let <API key>; let userlist_placement = "right"; let list_of_popovers = []; export function clear_for_testing() { <API key> = undefined; <API key> = undefined; <API key> = undefined; <API key> = undefined; <API key> = undefined; list_of_popovers.length = 0; userlist_placement = "right"; } export function clipboard_enable(arg) { // arg is a selector or element // We extract this function for testing purpose. return new ClipboardJS(arg); } export function elem_to_user_id(elem) { return Number.parseInt(elem.attr("data-user-id"), 10); } // this utilizes the proxy pattern to intercept all calls to $.fn.popover // and push the $.fn.data($o, "popover") results to an array. // this is needed so that when we try to unload popovers, we can kill all dead // ones that no longer have valid parents in the DOM. const old_popover = $.fn.popover; $.fn.popover = Object.assign(function (...args) { // apply the jQuery object as `this`, and popover function arguments. old_popover.apply(this, args); // if there is a valid "popover" key in the jQuery data object then // push it to the array. if (this.data("popover")) { list_of_popovers.push(this.data("popover")); } }, old_popover); function copy_email_handler(e) { const email_el = $(e.trigger.parentElement); const copy_icon = email_el.find("i"); // only change the parent element's text back to email // and not overwrite the tooltip. const email_textnode = email_el[0].childNodes[2]; email_el.addClass("email_copied"); email_textnode.nodeValue = $t({defaultMessage: "Email copied"}); setTimeout(() => { email_el.removeClass("email_copied"); email_textnode.nodeValue = copy_icon.attr("data-clipboard-text"); }, 1500); e.clearSelection(); } function <API key>() { /* This shows (and enables) the copy-text icon for folks who have names that would overflow past the right edge of our user mention popup. */ $(".user_popover_email").each(function () { if (this.clientWidth < this.scrollWidth) { const email_el = $(this); const copy_email_icon = email_el.find("i"); /* For deactivated users, the copy-email icon will not even be present in the HTML, so we don't do anything. We don't reveal emails for deactivated users. */ if (copy_email_icon[0]) { copy_email_icon.removeClass("hide_copy_icon"); const <API key> = clipboard_enable(copy_email_icon[0]); <API key>.on("success", copy_email_handler); } } }); } function init_email_tooltip(user) { /* This displays the email tooltip for folks who have names that would overflow past the right edge of our user mention popup. */ $(".user_popover_email").each(function () { if (this.clientWidth < this.scrollWidth) { tippy(this, { placement: "bottom", content: people.get_visible_email(user), interactive: true, }); } }); } function load_medium_avatar(user, elt) { const avatar_path = "avatar/" + user.user_id + "/medium?v=" + user.avatar_version; const user_avatar_url = new URL(avatar_path, window.location.href); const <API key> = new Image(); <API key>.src = user_avatar_url; $(<API key>).on("load", function () { elt.css("background-image", "url(" + $(this).attr("src") + ")"); }); } function <API key>(size, elt) { const ypos = elt.offset().top; if (!(ypos + size / 2 < message_viewport.height() && ypos > size / 2)) { if (ypos + size < message_viewport.height()) { return "bottom"; } else if (ypos > size) { return "top"; } } return undefined; } function <API key>( user, popover_element, is_sender_popover, has_message_context, private_msg_class, template_class, popover_placement, ) { const is_me = people.is_my_user_id(user.user_id); let can_set_away = false; let can_revoke_away = false; if (is_me) { if (user_status.is_away(user.user_id)) { can_revoke_away = true; } else { can_set_away = true; } } const muting_allowed = !is_me && !user.is_bot; const is_muted = muted_users.is_user_muted(user.user_id); const args = { can_revoke_away, can_set_away, can_mute: muting_allowed && !is_muted, can_unmute: muting_allowed && is_muted, has_message_context, is_active: people.<API key>(user.user_id), is_bot: user.is_bot, is_me, is_sender_popover, pm_with_uri: hash_util.pm_with_uri(user.email), user_circle_class: buddy_data.<API key>(user.user_id), <API key>: private_msg_class, sent_by_uri: hash_util.by_sender_uri(user.email), show_email: settings_data.show_email(), show_user_profile: !user.is_bot, user_email: people.get_visible_email(user), user_full_name: user.full_name, user_id: user.user_id, <API key>: buddy_data.<API key>(user.user_id), user_time: people.get_user_time(user.user_id), user_type: people.get_user_type(user.user_id), status_text: user_status.get_status_text(user.user_id), user_mention_syntax: people.get_mention_syntax(user.full_name, user.user_id), }; if (user.is_bot) { const is_cross_realm_bot = user.is_cross_realm_bot; const bot_owner_id = user.bot_owner_id; if (is_cross_realm_bot) { args.is_cross_realm_bot = is_cross_realm_bot; } else if (bot_owner_id) { const bot_owner = people.get_by_user_id(bot_owner_id); args.bot_owner = bot_owner; } } popover_element.popover({ content: <API key>(args), // TODO: Determine whether `fixed` should be applied // unconditionally. Right now, we only do it for the user // sidebar version of the popover. fixed: template_class === "user_popover", placement: popover_placement, template: <API key>({class: template_class}), title: <API key>({ user_avatar: "avatar/" + user.email, user_is_guest: user.is_guest, }), html: true, trigger: "manual", top_offset: $("#userlist-title").offset().top + 15, fix_positions: true, }); popover_element.popover("show"); <API key>(); init_email_tooltip(user); load_medium_avatar(user, $(".popover-avatar")); } // exporting for testability export const <API key> = <API key>; // element is the target element to pop off of // user is the user whose profile to show // message is the message containing it, which should be selected function <API key>(element, user, message) { const last_popover_elem = <API key>; hide_all(); if (last_popover_elem !== undefined && last_popover_elem.get()[0] === element) { // We want it to be the case that a user can dismiss a popover // by clicking on the same element that caused the popover. return; } message_lists.current.select_id(message.id); const elt = $(element); if (elt.data("popover") === undefined) { if (user === undefined) { // This is never supposed to happen, not even for deactivated // users, so we'll need to debug this error if it occurs. blueslip.error("Bad sender in message" + message.sender_id); return; } const is_sender_popover = message.sender_id === user.user_id; <API key>( user, elt, is_sender_popover, true, "<API key>", "<API key>", "right", ); <API key> = elt; } } export function <API key>(element, user) { const last_popover_elem = <API key>; hide_all(); if (last_popover_elem !== undefined && last_popover_elem.get()[0] === element) { return; } const elt = $(element); <API key>( user, elt, false, false, "<API key>", "user-info-popover", "right", ); <API key> = elt; } function <API key>() { if (!<API key>) { blueslip.error("Trying to get menu items when action popover is closed."); return undefined; } const popover_data = <API key>.data("popover"); if (!popover_data) { blueslip.error("Cannot find popover data for actions menu."); return undefined; } return $("li:not(.divider):visible a", popover_data.$tip); } function <API key>() { const popover_elt = $("div.user-info-popover"); if (!<API key> || !popover_elt.length) { blueslip.error("Trying to get menu items when action popover is closed."); return undefined; } if (popover_elt.length >= 2) { blueslip.error("More than one user info popovers cannot be opened at same time."); return undefined; } return $("li:not(.divider):visible a", popover_elt); } function fetch_group_members(member_ids) { return member_ids .map((m) => people.get_by_user_id(m)) .filter((m) => m !== undefined) .map((p) => ({ p, user_circle_class: buddy_data.<API key>(p.user_id), is_active: people.<API key>(p.user_id), <API key>: buddy_data.<API key>(p.user_id), })); } function sort_group_members(members) { return members.sort((a, b) => util.strcmp(a.full_name, b.fullname)); } // exporting these functions for testing purposes export const <API key> = fetch_group_members; export const <API key> = sort_group_members; // element is the target element to pop off of // user is the user whose profile to show // message is the message containing it, which should be selected function <API key>(element, group, message) { const last_popover_elem = <API key>; // hardcoded pixel height of the popover // note that the actual size varies (in group size), but this is about as big as it gets const popover_size = 390; hide_all(); if (last_popover_elem !== undefined && last_popover_elem.get()[0] === element) { // We want it to be the case that a user can dismiss a popover // by clicking on the same element that caused the popover. return; } message_lists.current.select_id(message.id); const elt = $(element); if (elt.data("popover") === undefined) { const args = { group_name: group.name, group_description: group.description, members: sort_group_members(fetch_group_members(Array.from(group.members))), }; elt.popover({ placement: <API key>(popover_size, elt), template: <API key>({class: "<API key>"}), content: <API key>(args), html: true, trigger: "manual", }); elt.popover("show"); <API key> = elt; } } export function <API key>(element, id) { const last_popover_elem = <API key>; hide_all(); if (last_popover_elem !== undefined && last_popover_elem.get()[0] === element) { // We want it to be the case that a user can dismiss a popover // by clicking on the same element that caused the popover. return; } $(element).closest(".message_row").toggleClass("has_popover has_actions_popover"); message_lists.current.select_id(id); const not_spectator = !page_params.is_spectator; const elt = $(element); if (elt.data("popover") === undefined) { const message = message_lists.current.get(id); const message_container = message_lists.current.view.message_containers.get(message.id); const <API key> = muted_users.is_user_muted(message.sender_id) && !message_container.is_hidden && not_spectator; const editability = message_edit.get_editability(message); let use_edit_icon; let <API key>; if (editability === message_edit.editability_types.FULL) { use_edit_icon = true; <API key> = $t({defaultMessage: "Edit"}); } else if (editability === message_edit.editability_types.TOPIC_ONLY) { use_edit_icon = false; <API key> = $t({defaultMessage: "View source / Edit topic"}); } else { use_edit_icon = false; <API key> = $t({defaultMessage: "View source"}); } const topic = message.topic; const can_mute_topic = message.stream && topic && !muted_topics.is_topic_muted(message.stream_id, topic) && not_spectator; const can_unmute_topic = message.stream && topic && muted_topics.is_topic_muted(message.stream_id, topic); const <API key> = message.edit_history && message.edit_history.some( (entry) => entry.prev_content !== undefined || util.<API key>(entry) !== undefined, ) && page_params.<API key> && not_spectator; // Disabling this for /me messages is a temporary workaround // for the fact that we don't have a styling for how that // should look. See also condense.js. const <API key> = !message.locally_echoed && !message.is_me_message && !message.collapsed && not_spectator; const <API key> = !message.locally_echoed && !message.is_me_message && message.collapsed; const <API key> = (message.content !== "<p>(deleted)</p>" || editability === message_edit.editability_types.FULL || editability === message_edit.editability_types.TOPIC_ONLY) && not_spectator; const <API key> = message.content !== "<p>(deleted)</p>" && not_spectator; const <API key> = hash_util.<API key>(message); const <API key> = message_edit.get_deletability(message) && not_spectator; const args = { message_id: message.id, historical: message.historical, stream_id: message.stream_id, topic, use_edit_icon, <API key>, can_mute_topic, can_unmute_topic, <API key>, <API key>, <API key>: message.sent_by_me, <API key>, <API key>, <API key>, narrowed: narrow_state.active(), <API key>, <API key>: feature_flags.<API key>, <API key>, <API key>, }; const ypos = elt.offset().top; elt.popover({ // Popover height with 7 items in it is ~190 px placement: message_viewport.height() - ypos < 220 ? "top" : "bottom", title: "", content: <API key>(args), html: true, trigger: "manual", }); elt.popover("show"); <API key> = elt; } } export function <API key>(element, id) { hide_all(); $(element).closest(".message_row").toggleClass("has_popover has_actions_popover"); message_lists.current.select_id(id); const elt = $(element); if (elt.data("popover") === undefined) { const message = message_lists.current.get(id); const args = { message, }; const ypos = elt.offset().top; elt.popover({ // Popover height with 7 items in it is ~190 px placement: message_viewport.height() - ypos < 220 ? "top" : "bottom", title: "", content: <API key>(args), html: true, trigger: "manual", }); elt.popover("show"); <API key> = $( `.remind.custom[data-message-id="${CSS.escape(message.id)}"]`, ).flatpickr({ enableTime: true, clickOpens: false, defaultDate: "today", minDate: "today", plugins: [new ConfirmDatePlugin({})], }); <API key> = elt; } } function <API key>() { if (!<API key>) { blueslip.error("Trying to get menu items when action popover is closed."); return undefined; } const popover_data = <API key>.data("popover"); if (!popover_data) { blueslip.error("Cannot find popover data for actions menu."); return undefined; } return $("li:not(.divider):visible a", popover_data.$tip); } export function <API key>(items) { if (!items) { return; } items.eq(0).expectOne().trigger("focus"); } export function <API key>(key, items) { if (!items) { return; } let index = items.index(items.filter(":focus")); if (key === "enter" && index >= 0 && index < items.length) { items[index].click(); return; } if (index === -1) { index = 0; } else if ((key === "down_arrow" || key === "vim_down") && index < items.length - 1) { index += 1; } else if ((key === "up_arrow" || key === "vim_up") && index > 0) { index -= 1; } items.eq(index).trigger("focus"); } function <API key>() { // For now I recommend only calling this when the user opens the menu with a hotkey. // Our popup menus act kind of funny when you mix keyboard and mouse. const items = <API key>(); <API key>(items); } export function open_message_menu(message) { if (message.locally_echoed) { // Don't open the popup for locally echoed messages for now. // It creates bugs with things like keyboard handlers when // we get the server response. return true; } const message_id = message.id; <API key>($(".selected_message .actions_hover")[0], message_id); if (<API key>) { <API key>(); } return true; } export function <API key>(key) { const items = <API key>(); <API key>(key, items); } export function actions_popped() { return <API key> !== undefined; } export function <API key>() { if (actions_popped()) { $(".has_popover").removeClass("has_popover has_actions_popover"); <API key>.popover("destroy"); <API key> = undefined; } if (<API key> !== undefined) { <API key>.destroy(); <API key> = undefined; } } export function message_info_popped() { return <API key> !== undefined; } export function <API key>() { if (message_info_popped()) { <API key>.popover("destroy"); <API key> = undefined; } } export function user_info_popped() { return <API key> !== undefined; } export function <API key>() { if (user_info_popped()) { <API key>.popover("destroy"); <API key> = undefined; } } export function <API key>() { $(".app-main .column-right").removeClass("expanded"); } export function <API key>() { $(".app-main .column-left").removeClass("expanded"); } export function <API key>() { $(".app-main .column-right").addClass("expanded"); resize.<API key>(); } export function <API key>() { $(".app-main .column-left").addClass("expanded"); resize.<API key>(); } let <API key>; let <API key>; export function user_sidebar_popped() { return <API key> !== undefined; } export function <API key>() { if (user_sidebar_popped()) { // this hide_* method looks different from all the others since // the presence list may be redrawn. Due to funkiness with jquery's .data() // this would confuse $.popover("destroy"), which looks at the .data() attached // to a certain element. We thus save off the .data("popover") in the // <API key> and inject it here before calling destroy. $("#user_presences").data("popover", <API key>); $("#user_presences").popover("destroy"); <API key> = undefined; <API key> = undefined; } } function <API key>() { // For now I recommend only calling this when the user opens the menu with a hotkey. // Our popup menus act kind of funny when you mix keyboard and mouse. const items = <API key>(); <API key>(items); } function <API key>() { if (!<API key>) { blueslip.error("Trying to get menu items when user sidebar popover is closed."); return undefined; } return $("li:not(.divider):visible > a", <API key>.$tip); } export function <API key>(key) { const items = <API key>(); <API key>(key, items); } export function <API key>(key) { const items = <API key>(); <API key>(key, items); } export function <API key>(key) { const items = <API key>(); <API key>(key, items); } export function show_sender_info() { const $message = $(".selected_message"); const $sender = $message.find(".sender_info_hover"); const message = message_lists.current.get(rows.id($message)); const user = people.get_by_user_id(message.sender_id); <API key>($sender[0], user, message); if (<API key>) { <API key>(); } } // On mobile web, opening the keyboard can trigger a resize event // (which in turn can trigger a scroll event). This will have the // side effect of closing popovers, which we don't want. So we // suppress the first hide from scrolling after a resize using this // variable. let <API key> = false; export function <API key>() { <API key> = true; } // Playground_info contains all the data we need to generate a popover of // playground links for each code block. The element is the target element // to pop off of. export function <API key>(element, playground_info) { const last_popover_elem = <API key>; hide_all(); if (last_popover_elem !== undefined && last_popover_elem.get()[0] === element) { // We want it to be the case that a user can dismiss a popover // by clicking on the same element that caused the popover. return; } const elt = $(element); if (elt.data("popover") === undefined) { const ypos = elt.offset().top; elt.popover({ // It's unlikely we'll have more than 3-4 playground links // for one language, so it should be OK to hardcode 120 here. placement: message_viewport.height() - ypos < 120 ? "top" : "bottom", title: "", content: <API key>({playground_info}), html: true, trigger: "manual", }); elt.popover("show"); <API key> = elt; } } export function <API key>() { if (<API key> !== undefined) { <API key>.popover("destroy"); <API key> = undefined; } } export function <API key>() { $("#main_div").on("click", ".actions_hover", function (e) { const row = $(this).closest(".message_row"); e.stopPropagation(); <API key>(this, rows.id(row)); }); $("#main_div").on( "click", ".sender_name, .<API key>, .<API key>", function (e) { const row = $(this).closest(".message_row"); e.stopPropagation(); const message = message_lists.current.get(rows.id(row)); const user = people.get_by_user_id(message.sender_id); <API key>(this, user, message); }, ); $("#main_div").on("click", ".user-mention", function (e) { const id_string = $(this).attr("data-user-id"); // We fallback to email to handle legacy Markdown that was rendered // before we cut over to using data-user-id const email = $(this).attr("data-user-email"); if (id_string === "*" || email === "*") { return; } const row = $(this).closest(".message_row"); e.stopPropagation(); const message = message_lists.current.get(rows.id(row)); let user; if (id_string) { const user_id = Number.parseInt(id_string, 10); user = people.get_by_user_id(user_id); } else { user = people.get_by_email(email); } <API key>(this, user, message); }); $("#main_div").on("click", ".user-group-mention", function (e) { const user_group_id = Number.parseInt($(this).attr("data-user-group-id"), 10); const row = $(this).closest(".message_row"); e.stopPropagation(); const message = message_lists.current.get(rows.id(row)); const group = user_groups.<API key>(user_group_id, true); if (group === undefined) { // This user group has likely been deleted. blueslip.info("Unable to find user group in message" + message.sender_id); } else { <API key>(this, group, message); } }); $("#main_div, #compose .preview_content").on("click", ".code_external_link", function (e) { const <API key> = $(this); const codehilite_div = $(this).closest(".codehilite"); e.stopPropagation(); const playground_info = realm_playground.<API key>( codehilite_div.data("code-language"), ); // We do the code extraction here and set the target href combining the url_prefix // and the extracted code. Depending on whether the language has multiple playground // links configured, a popover is show. const extracted_code = codehilite_div.find("code").text(); if (playground_info.length === 1) { const url_prefix = playground_info[0].url_prefix; <API key>.attr("href", url_prefix + encodeURIComponent(extracted_code)); } else { for (const $playground of playground_info) { $playground.playground_url = $playground.url_prefix + encodeURIComponent(extracted_code); } <API key>(this, playground_info); } }); $("body").on("click", ".<API key>", (e) => { <API key>(); e.stopPropagation(); }); $("body").on("click", ".<API key> .<API key>", (e) => { const user_id = elem_to_user_id($(e.target).parents("ul")); const email = people.get_by_user_id(user_id).email; hide_all(); if (overlays.settings_open()) { overlays.close_overlay("settings"); } narrow.by("pm-with", email, {trigger: "user sidebar popover"}); e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".<API key> .<API key>", (e) => { const user_id = elem_to_user_id($(e.target).parents("ul")); const email = people.get_by_user_id(user_id).email; hide_all(); if (overlays.settings_open()) { overlays.close_overlay("settings"); } narrow.by("sender", email, {trigger: "user sidebar popover"}); e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".user_popover .mention_user", (e) => { if (!compose_state.composing()) { compose_actions.start("stream", {trigger: "sidebar user actions"}); } const user_id = elem_to_user_id($(e.target).parents("ul")); const name = people.get_by_user_id(user_id).full_name; const mention = people.get_mention_syntax(name, user_id); compose_ui.<API key>(mention); <API key>(); <API key>(); e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".<API key> .mention_user", (e) => { if (!compose_state.composing()) { compose_actions.respond_to_message({trigger: "user sidebar popover"}); } const user_id = elem_to_user_id($(e.target).parents("ul")); const name = people.get_by_user_id(user_id).full_name; const mention = people.get_mention_syntax(name, user_id); compose_ui.<API key>(mention); <API key>(); e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".<API key> .clear_status", (e) => { e.preventDefault(); const me = elem_to_user_id($(e.target).parents("ul")); user_status.server_update({ user_id: me, status_text: "", success() { $(".<API key> #status_message").html(""); }, }); }); $("body").on("click", ".view_user_profile", (e) => { const user_id = Number.parseInt($(e.target).attr("data-user-id"), 10); const user = people.get_by_user_id(user_id); <API key>(e.target, user); e.stopPropagation(); e.preventDefault(); }); /* These click handlers are implemented as just deep links to the * relevant part of the Zulip UI, so we don't want preventDefault, * but we do want to close the modal when you click them. */ $("body").on("click", ".set_away_status", (e) => { hide_all(); user_status.server_set_away(); e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".revoke_away_status", (e) => { hide_all(); user_status.server_revoke_away(); e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".update_status_text", (e) => { hide_all(); user_status_ui.<API key>(); e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".<API key> .<API key>", (e) => { const user_id = elem_to_user_id($(e.target).parents("ul")); <API key>(); <API key>(); e.stopPropagation(); e.preventDefault(); muted_users_ui.confirm_mute_user(user_id); }); $("body").on("click", ".<API key> .<API key>", (e) => { const user_id = elem_to_user_id($(e.target).parents("ul")); <API key>(); <API key>(); muted_users_ui.unmute_user(user_id); e.stopPropagation(); e.preventDefault(); }); $("#user_presences").on("click", ".<API key>", function (e) { e.stopPropagation(); // use email of currently selected user, rather than some elem comparison, // as the presence list may be redrawn with new elements. const target = $(this).closest("li"); const user_id = elem_to_user_id(target.find("a")); if (<API key> === user_id) { // If the popover is already shown, clicking again should toggle it. // We don't want to hide the sidebars on smaller browser windows. <API key>(); return; } hide_all(); if (userlist_placement === "right") { <API key>(); } else { // Maintain the same behavior when displaying with the streamlist. stream_popover.<API key>(); } const user = people.get_by_user_id(user_id); const popover_placement = userlist_placement === "left" ? "right" : "left"; <API key>( user, target, false, false, "<API key>", "user_popover", popover_placement, ); <API key> = user.user_id; <API key> = target.data("popover"); }); $("body").on("click", ".respond_button", (e) => { // Arguably, we should fetch the message ID to respond to from // e.target, but that should always be the current selected // message in the current message list (and // compose_actions.respond_to_message doesn't take a message // argument). compose_actions.quote_and_reply({trigger: "popover respond"}); <API key>(); e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".reminder_button", (e) => { const message_id = $(e.currentTarget).data("message-id"); <API key>($(".selected_message .actions_hover")[0], message_id); e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".remind.custom", (e) => { $(e.currentTarget)[0]._flatpickr.toggle(); e.stopPropagation(); e.preventDefault(); }); function <API key>(datestr, e) { const message_id = $(".remind.custom").data("message-id"); reminder.<API key>(message_id, datestr); hide_all(); e.stopPropagation(); e.preventDefault(); } $("body").on("click", ".remind.in_20m", (e) => { const datestr = formatISO(add(new Date(), {minutes: 20})); <API key>(datestr, e); }); $("body").on("click", ".remind.in_1h", (e) => { const datestr = formatISO(add(new Date(), {hours: 1})); <API key>(datestr, e); }); $("body").on("click", ".remind.in_3h", (e) => { const datestr = formatISO(add(new Date(), {hours: 3})); <API key>(datestr, e); }); $("body").on("click", ".remind.tomo", (e) => { const datestr = formatISO( set(add(new Date(), {days: 1}), {hours: 9, minutes: 0, seconds: 0}), ); <API key>(datestr, e); }); $("body").on("click", ".remind.nxtw", (e) => { const datestr = formatISO( set(add(new Date(), {weeks: 1}), {hours: 9, minutes: 0, seconds: 0}), ); <API key>(datestr, e); }); $("body").on("click", ".flatpickr-calendar", (e) => { e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".flatpickr-confirm", (e) => { const datestr = $(".remind.custom")[0].value; <API key>(datestr, e); }); $("body").on("click", ".<API key>, .<API key>", (e) => { const user_id = elem_to_user_id($(e.target).parents("ul")); const email = people.get_by_user_id(user_id).email; compose_actions.start("private", { trigger: "popover send private", <API key>: email, }); hide_all(); if (overlays.settings_open()) { overlays.close_overlay("settings"); } e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".<API key>", (e) => { const message_id = $(e.currentTarget).data("message-id"); const row = message_lists.current.get_row(message_id); const message = message_lists.current.get(rows.id(row)); <API key>(); if (row) { if (message.collapsed) { condense.uncollapse(row); } else { condense.collapse(row); } } e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".<API key>", (e) => { const message_id = $(e.currentTarget).data("message-id"); const row = message_lists.current.get_row(message_id); <API key>(); message_edit.start(row); e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".<API key>", (e) => { const message_id = $(e.currentTarget).data("message-id"); const row = message_lists.current.get_row(message_id); const message = message_lists.current.get(rows.id(row)); const message_container = message_lists.current.view.message_containers.get(message.id); <API key>(); if (row && !message_container.is_hidden) { message_lists.current.view.<API key>(message_id); } e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".view_edit_history", (e) => { const message_id = $(e.currentTarget).data("message-id"); const row = message_lists.current.get_row(message_id); const message = message_lists.current.get(rows.id(row)); <API key>(); <API key>.show_history(message); $("#<API key>").trigger("focus"); e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".popover_mute_topic", (e) => { const stream_id = Number.parseInt($(e.currentTarget).attr("data-msg-stream-id"), 10); const topic = $(e.currentTarget).attr("data-msg-topic"); <API key>(); muted_topics_ui.mute_topic(stream_id, topic); e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".<API key>", (e) => { const stream_id = Number.parseInt($(e.currentTarget).attr("data-msg-stream-id"), 10); const topic = $(e.currentTarget).attr("data-msg-topic"); <API key>(); muted_topics_ui.unmute_topic(stream_id, topic); e.stopPropagation(); e.preventDefault(); }); $("body").on("click", ".delete_message", (e) => { const message_id = $(e.currentTarget).data("message-id"); <API key>(); message_edit.delete_message(message_id); e.stopPropagation(); e.preventDefault(); }); clipboard_enable(".copy_link").on("success", (e) => { <API key>(); // e.trigger returns the DOM element triggering the copy action const message_id = e.trigger.getAttribute("data-message-id"); const row = $(`[zid='${CSS.escape(message_id)}']`); row.find(".alert-msg") .text($t({defaultMessage: "Copied!"})) .css("display", "block") .delay(1000) .fadeOut(300); setTimeout(() => { // The Cliboard library works by focusing to a hidden textarea. // We unfocus this so keyboard shortcuts, etc., will work again. $(":focus").trigger("blur"); }, 0); }); clipboard_enable(".copy_mention_syntax"); $("body").on("click", ".copy_mention_syntax", (e) => { hide_all(); e.stopPropagation(); e.preventDefault(); }); { let last_scroll = 0; $(".app").on("scroll", () => { if (<API key>) { <API key> = false; return; } const date = Date.now(); // only run `popovers.hide_all()` if the last scroll was more // than 250ms ago. if (date - last_scroll > 250) { hide_all(); } // update the scroll time on every event to make sure it doesn't // retrigger `hide_all` while still scrolling. last_scroll = date; }); } } export function any_active() { // True if any popover (that this module manages) is currently shown. // Expanded sidebars on mobile view count as popovers as well. return ( popover_menus.<API key>() || popover_menus.<API key>() || actions_popped() || user_sidebar_popped() || stream_popover.stream_popped() || stream_popover.topic_popped() || message_info_popped() || user_info_popped() || emoji_picker.reactions_popped() || $("[class^='column-'].expanded").length ); } // This function will hide all true popovers (the streamlist and // userlist sidebars use the popover infrastructure, but doesn't work // like a popover structurally). export function <API key>(opts) { $(".has_popover").removeClass("has_popover has_actions_popover has_emoji_popover"); if (!opts || !opts.<API key>) { hideAll(); } else if (opts.<API key>) { hideAll({exclude: opts.<API key>}); } <API key>(); <API key>(); emoji_picker.hide_emoji_popover(); giphy.hide_giphy_popover(); stream_popover.hide_stream_popover(); stream_popover.hide_topic_popover(); stream_popover.<API key>(); stream_popover.<API key>(); <API key>(); <API key>(); <API key>(); // look through all the popovers that have been added and removed. for (const $o of list_of_popovers) { if (!document.body.contains($o.$element[0]) && $o.$tip) { $o.$tip.remove(); } } list_of_popovers = []; } // This function will hide all the popovers, including the mobile web // or narrow window sidebars. export function hide_all(<API key>) { <API key>(); stream_popover.<API key>(); <API key>({ <API key>: undefined, <API key>, }); } export function <API key>(placement) { userlist_placement = placement || "right"; } export function compute_placement(elt, popover_height, popover_width, <API key>) { const client_rect = elt.get(0).<API key>(); const distance_from_top = client_rect.top; const <API key> = message_viewport.height() - client_rect.bottom; const distance_from_left = client_rect.left; const distance_from_right = message_viewport.width() - client_rect.right; const <API key> = distance_from_left + elt.width() / 2 > popover_width / 2 && distance_from_right + elt.width() / 2 > popover_width / 2; const <API key> = <API key> + elt.height() / 2 > popover_height / 2 && distance_from_top + elt.height() / 2 > popover_height / 2; // default to placing the popover in the center of the screen let placement = "viewport_center"; // prioritize left/right over top/bottom if (distance_from_top > popover_height && <API key>) { placement = "top"; } if (<API key> > popover_height && <API key>) { placement = "bottom"; } if (<API key> && placement !== "viewport_center") { // If vertical positioning is preferred and the popover fits in // either top or bottom position then return. return placement; } if (distance_from_left > popover_width && <API key>) { placement = "left"; } if (distance_from_right > popover_width && <API key>) { placement = "right"; } return placement; }
package jet.bpm.engine.model; public class EndEvent extends AbstractElement { private final String errorRef; public EndEvent(String id) { this(id, null); } public EndEvent(String id, String errorRef) { super(id); this.errorRef = errorRef; } public String getErrorRef() { return errorRef; } }
/** * @desc * @date 201685 */ package tk.cpusoft.common.util.response.AppManage; import java.util.HashMap; import java.util.Map; import tk.cpusoft.common.base.BaseModel; /** * @desc * @date 201685-10:07:41 */ public class AppReply extends BaseModel{ /** * @desc * @date 201685-10:10:19 */ private static final long serialVersionUID = 1L; private Opt opt; private Map data = new HashMap(); public AppReply(){ } /** * @desc * @date 201685-10:15:10 */ public AppReply(Opt opt2, Map<String, Object> map) { this.setOpt(opt2); this.setData(map); } public Opt getOpt() { return opt; } public void setOpt(Opt opt) { this.opt = opt; } public Map getData() { return data; } public void setData(Map data) { this.data = data; } }
/** * @fileoverview Class representing inputs with connections on a rendered block. */ /** * Class representing inputs with connections on a rendered block. * @class */ goog.module('Blockly.blockRendering.InputConnection'); const object = goog.require('Blockly.utils.object'); const {Connection} = goog.require('Blockly.blockRendering.Connection'); /* <API key> no-unused-vars */ const {ConstantProvider} = goog.requireType('Blockly.blockRendering.ConstantProvider'); /* <API key> no-unused-vars */ const {Input} = goog.requireType('Blockly.Input'); const {Types} = goog.require('Blockly.blockRendering.Types'); /** * The base class to represent an input that takes up space on a block * during rendering * @param {!ConstantProvider} constants The rendering * constants provider. * @param {!Input} input The input to measure and store information for. * @package * @constructor * @extends {Connection} * @alias Blockly.blockRendering.InputConnection */ const InputConnection = function(constants, input) { InputConnection.superClass_.constructor.call( this, constants, input.connection); this.type |= Types.INPUT; this.input = input; this.align = input.align; this.connectedBlock = input.connection && input.connection.targetBlock() ? input.connection.targetBlock() : null; if (this.connectedBlock) { const bBox = this.connectedBlock.getHeightWidth(); this.connectedBlockWidth = bBox.width; this.<API key> = bBox.height; } else { this.connectedBlockWidth = 0; this.<API key> = 0; } this.connectionOffsetX = 0; this.connectionOffsetY = 0; }; object.inherits(InputConnection, Connection); exports.InputConnection = InputConnection;
package org.swtk.commons.dict.wordnet.indexbyid.instance.p0.p6; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.IndexNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class <API key> { private static Map<String, Collection<IndexNoun>> map = new TreeMap<String, Collection<IndexNoun>>(); static { add("06330022", "{\"term\":\"adjective\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"06330022\", \"06332695\"]}"); add("06330150", "{\"term\":\"adverb\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"06334605\", \"06330150\"]}"); add("06330286", "{\"term\":\"noun\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"06328855\", \"06330286\"]}"); add("06330568", "{\"term\":\"collective noun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06330568\"]}"); add("06330703", "{\"term\":\"mass noun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06330703\"]}"); add("06330792", "{\"term\":\"count noun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06330792\"]}"); add("06330874", "{\"term\":\"generic noun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06330874\"]}"); add("06330997", "{\"term\":\"proper name\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06330997\"]}"); add("06330997", "{\"term\":\"proper noun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06330997\"]}"); add("06331146", "{\"term\":\"common noun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06331146\"]}"); add("06331307", "{\"term\":\"deverbal noun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06331307\"]}"); add("06331307", "{\"term\":\"verbal noun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06331307\"]}"); add("06331433", "{\"term\":\"adnoun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06331433\"]}"); add("06331562", "{\"term\":\"verb\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"06331562\", \"06329055\"]}"); add("06331794", "{\"term\":\"modifier\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"05446862\", \"09632901\", \"10346442\", \"06331794\"]}"); add("06331794", "{\"term\":\"qualifier\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"06331794\", \"10517781\"]}"); add("06332047", "{\"term\":\"intensifier\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06332047\"]}"); add("06332047", "{\"term\":\"intensive\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06332047\"]}"); add("06332695", "{\"term\":\"adjective\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"06330022\", \"06332695\"]}"); add("06332925", "{\"term\":\"descriptive adjective\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06332925\"]}"); add("06332925", "{\"term\":\"qualifying adjective\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06332925\"]}"); add("06333150", "{\"term\":\"classifying adjective\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06333150\"]}"); add("06333150", "{\"term\":\"relational adjective\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06333150\"]}"); add("06333350", "{\"term\":\"pertainym\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06333350\"]}"); add("06333461", "{\"term\":\"positive\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"03993867\", \"06333461\"]}"); add("06333461", "{\"term\":\"positive degree\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06333461\"]}"); add("06333686", "{\"term\":\"comparative\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06333686\"]}"); add("06333686", "{\"term\":\"comparative degree\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06333686\"]}"); add("06334277", "{\"term\":\"superlative\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"06334277\", \"13963489\", \"06706615\"]}"); add("06334277", "{\"term\":\"superlative degree\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06334277\"]}"); add("06334605", "{\"term\":\"adverb\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"06334605\", \"06330150\"]}"); add("06334815", "{\"term\":\"dangling modifier\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06334815\"]}"); add("06334815", "{\"term\":\"misplaced modifier\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06334815\"]}"); add("06335079", "{\"term\":\"dangling participle\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06335079\"]}"); add("06335348", "{\"term\":\"adverbial\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06335348\"]}"); add("06335468", "{\"term\":\"determinative\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05700384\", \"06335468\"]}"); add("06335468", "{\"term\":\"determiner\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"05700384\", \"06335468\", \"06662312\"]}"); add("06335662", "{\"term\":\"article\", \"synsetCount\":4, \"upperType\":\"NOUN\", \"ids\":[\"06335662\", \"06404578\", \"00023083\", \"06278749\"]}"); add("06335857", "{\"term\":\"definite article\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06335857\"]}"); add("06335994", "{\"term\":\"indefinite article\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06335994\"]}"); add("06336138", "{\"term\":\"preposition\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"06495681\", \"06336138\"]}"); add("06336363", "{\"term\":\"pronoun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06336363\"]}"); add("06336569", "{\"term\":\"anaphoric pronoun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06336569\"]}"); add("06336671", "{\"term\":\"demonstrative\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06336671\"]}"); add("06336671", "{\"term\":\"demonstrative pronoun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06336671\"]}"); add("06336819", "{\"term\":\"conjunction\", \"synsetCount\":6, \"upperType\":\"NOUN\", \"ids\":[\"03611128\", \"07429767\", \"13821604\", \"06336819\", \"14444358\", \"05055452\"]}"); add("06336819", "{\"term\":\"conjunctive\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06336819\"]}"); add("06336819", "{\"term\":\"connective\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"03095830\", \"06336819\"]}"); add("06336819", "{\"term\":\"continuative\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06336819\"]}"); add("06337047", "{\"term\":\"coordinating conjunction\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"06337047\", \"13821867\"]}"); add("06337219", "{\"term\":\"subordinate conjunction\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06337219\"]}"); add("06337219", "{\"term\":\"subordinating conjunction\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"06337219\", \"13822008\"]}"); add("06337399", "{\"term\":\"particle\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"06337399\", \"09409315\", \"14609699\"]}"); add("06337519", "{\"term\":\"number\", \"synsetCount\":12, \"upperType\":\"NOUN\", \"ids\":[\"03840952\", \"06337519\", \"06609408\", \"05103556\", \"06436708\", \"08497523\", \"06609182\", \"06820056\", \"06437781\", \"06905066\", \"13603216\", \"05128718\"]}"); add("06337790", "{\"term\":\"person\", \"synsetCount\":3, \"upperType\":\"NOUN\", \"ids\":[\"06337790\", \"05224944\", \"00007846\"]}"); add("06338129", "{\"term\":\"personal pronoun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06338129\"]}"); add("06338254", "{\"term\":\"reciprocal pronoun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06338254\"]}"); add("06338544", "{\"term\":\"relative pronoun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06338544\"]}"); add("06338711", "{\"term\":\"first person\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06338711\"]}"); add("06338863", "{\"term\":\"second person\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06338863\"]}"); add("06339015", "{\"term\":\"third person\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06339015\"]}"); add("06339200", "{\"term\":\"reflexive\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06339200\"]}"); add("06339200", "{\"term\":\"reflexive pronoun\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06339200\"]}"); add("06339379", "{\"term\":\"reflexive verb\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06339379\"]}"); add("06339636", "{\"term\":\"gender\", \"synsetCount\":2, \"upperType\":\"NOUN\", \"ids\":[\"05014082\", \"06339636\"]}"); add("06339636", "{\"term\":\"grammatical gender\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06339636\"]}"); add("06339989", "{\"term\":\"feminine\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"06339989\"]}"); } private static void add(final String ID, final String JSON) { IndexNoun indexNoun = GsonUtils.toObject(JSON, IndexNoun.class); Collection<IndexNoun> list = (map.containsKey(ID)) ? map.get(ID) : new ArrayList<IndexNoun>(); list.add(indexNoun); map.put(ID, list); } public static Collection<IndexNoun> get(final String TERM) { return map.get(TERM); } public static boolean has(final String TERM) { return map.containsKey(TERM); } public static Collection<String> ids() { return map.keySet(); } }
package com.wgt.umeng.activity; import com.umeng.message.UmengRegistrar; import com.wgt.umeng.R; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.EditText; public class MainActivity extends BascActivity { private final String TAG = "MainActivity"; private String DeviceToken; private EditText ed; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DeviceToken = UmengRegistrar.getRegistrationId(this); initUI(); } private void initUI() { ed =(EditText) findViewById(R.id.ed_device_token); ed.setText(DeviceToken); } }
using FlatBuffers; using Nostradamus.Networking; using System.Collections.Generic; using System.Linq; namespace Nostradamus { public sealed class SimulatorSnapshot : ISnapshotArgs { public List<ActorSnapshot> Actors = new List<ActorSnapshot>(); #region ISnapshotArgs ISnapshotArgs ISnapshotArgs.Clone() { return new SimulatorSnapshot() { Actors = new List<ActorSnapshot>(from a in Actors select new ActorSnapshot(a.Desc, a.Args.Clone())) }; } ISnapshotArgs ISnapshotArgs.Extrapolate(int deltaTime) { return new SimulatorSnapshot() { Actors = new List<ActorSnapshot>(from a in Actors select new ActorSnapshot(a.Desc, a.Args.Extrapolate(deltaTime))) }; } ISnapshotArgs ISnapshotArgs.Interpolate(ISnapshotArgs snapshot, float factor) { var otherSnapshot = (SimulatorSnapshot)snapshot; var newSnapshot = new SimulatorSnapshot(); foreach (var selfActor in Actors) { var otherActor = otherSnapshot.Actors.Find(a => a.Desc.Id == selfActor.Desc.Id); if (otherActor != null) { var newActor = selfActor.Args.Interpolate(otherActor.Args, factor); newSnapshot.Actors.Add(new ActorSnapshot(selfActor.Desc, newActor)); } else { newSnapshot.Actors.Add(new ActorSnapshot(selfActor.Desc, selfActor.Args.Clone())); } } return newSnapshot; } bool ISnapshotArgs.IsApproximate(ISnapshotArgs snapshot) { var otherSnapshot = (SimulatorSnapshot)snapshot; if (Actors.Count != otherSnapshot.Actors.Count) return false; Actors.Sort(SortByActorId); otherSnapshot.Actors.Sort(SortByActorId); for (int i = 0; i < Actors.Count; i++) { var selfActor = Actors[i]; var otherActor = otherSnapshot.Actors[i]; if (selfActor.Desc.Id != otherActor.Desc.Id) return false; if (!selfActor.Args.IsApproximate(otherActor.Args)) return false; } return true; } private int SortByActorId(ActorSnapshot x, ActorSnapshot y) { return x.Desc.Id.CompareTo(y.Desc.Id); } #endregion } class <API key> : Serializer<SimulatorSnapshot, Schema.SimulatorSnapshot> { public static readonly <API key> Instance = new <API key>(); public override Offset<Schema.SimulatorSnapshot> Serialize(FlatBufferBuilder fbb, SimulatorSnapshot snapshot) { var oActors = new Offset<Schema.ActorSnapshot>[snapshot.Actors.Count]; for (int i = 0; i < snapshot.Actors.Count; i++) { var oActor = <API key>.Instance.Serialize(fbb, snapshot.Actors[i]); oActors[i] = oActor; } var voActors = Schema.SimulatorSnapshot.CreateActorsVector(fbb, oActors); return Schema.SimulatorSnapshot.<API key>(fbb, voActors); } public override SimulatorSnapshot Deserialize(Schema.SimulatorSnapshot snapshot) { var actors = new List<ActorSnapshot>(); for (int i = 0; i < snapshot.ActorsLength; i++) { var actor = snapshot.Actors(i).Value; actors.Add(<API key>.Instance.Deserialize(actor)); } return new SimulatorSnapshot() { Actors = actors }; } public override Schema.SimulatorSnapshot ToFlatBufferObject(ByteBuffer buffer) { return Schema.SimulatorSnapshot.<API key>(buffer); } } }
namespace Aggregator.ConsoleApp { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.TeamFoundation.Server; using Microsoft.TeamFoundation.WorkItemTracking.Client; internal class QueryRunner { public class QueryResult { private IDictionary<int, WorkItem> workItems; private IList<WorkItemLinkInfo> links; // this is interesting when reasoning on links private QueryType queryType; public IDictionary<int, WorkItem> WorkItems { get => this.workItems; set => this.workItems = value; } public IList<WorkItemLinkInfo> Links { get => this.links; set => this.links = value; } public QueryType QueryType { get => this.queryType; set => this.queryType = value; } } public WorkItemStore WorkItemStore { get; private set; } public string TeamProjectName { get; private set; } public string <API key> { get; private set; } public QueryRunner(WorkItemStore workItemStore, string teamProjectName) { this.WorkItemStore = workItemStore; this.TeamProjectName = teamProjectName; } public QueryResult RunQuery(string queryPathOrText) { string queryText; #pragma warning disable S1854 // Dead stores should be removed var queryType = QueryType.Invalid; #pragma warning restore S1854 // Dead stores should be removed if (queryPathOrText.StartsWith("SELECT ", StringComparison.<API key>)) { // explicit query queryText = queryPathOrText; queryType = QueryType.List; } else { // name of existing query definition var rootQueryFolder = this.WorkItemStore.Projects[this.TeamProjectName].QueryHierarchy as QueryFolder; var queryDef = FindQuery(queryPathOrText, rootQueryFolder); // query not found if (queryDef == null) { return null; } queryText = queryDef.QueryText; queryType = queryDef.QueryType; } // get the query var query = new Query(this.WorkItemStore, queryText, this.GetParamsDictionary()); // run the query var dict = new Dictionary<int, WorkItem>(); var list = new List<WorkItemLinkInfo>(); if (queryType == QueryType.List) { foreach (WorkItem wi in query.RunQuery()) { dict.Add(wi.Id, wi); } } else { list.AddRange(query.RunLinkQuery()); foreach (var k in list) { if (k.SourceId != 0 && !dict.ContainsKey(k.SourceId)) { dict.Add(k.SourceId, this.WorkItemStore.GetWorkItem(k.SourceId)); } if (!dict.ContainsKey(k.TargetId)) { dict.Add(k.TargetId, this.WorkItemStore.GetWorkItem(k.TargetId)); } } } return new QueryResult() { WorkItems = dict, Links = list, QueryType = queryType }; } private static QueryDefinition FindQuery(string queryPath, QueryFolder queryFolder) { var parts = queryPath.Split('\\'); for (int i = 0; i < parts.Length - 1; i++) { queryFolder = queryFolder[parts[i]] as QueryFolder; } string queryName = parts[parts.Length - 1]; if (!queryFolder.Contains(queryName)) { return null; } var queryDef = queryFolder[queryName] as QueryDefinition; return queryDef; } private IDictionary GetParamsDictionary() { return new Dictionary<string, string>() { { "project", this.TeamProjectName }, { "me", this.<API key> } }; } } }
using System.Collections.Generic; using System.Linq; using System.Windows; using QuickGraph; using System; using System.Diagnostics.Contracts; using Windows.UI.Xaml; using Windows.Foundation; namespace GraphSharp.Algorithms.Layout.Compound.FDP { public partial class <API key><TVertex, TEdge, TGraph> where TVertex : class where TEdge : IEdge<TVertex> where TGraph : IBidirectionalGraph<TVertex, TEdge> { private static void RemoveAll<T>(ICollection<T> set, IEnumerable<T> elements) { foreach (var e in elements) { set.Remove(e); } } <summary> <list type="ul"> <listheader> Initializes the algorithm, and the following things: </listheader> <item>the nodes sizes (of the compound vertices)</item> <item>the thresholds for the convergence</item> <item>random initial positions (if the position is not null)</item> <item>remove the 'tree-nodes' from the root graph (level 0)</item> </list> </summary> <param name="vertexSizes">The dictionary of the inner canvas sizes of the compound vertices.</param> <param name="vertexBorders">The dictionary of the border thickness of the compound vertices.</param> <param name="layoutTypes">The dictionary of the layout types of the compound vertices.</param> private void Init(IDictionary<TVertex, Size> vertexSizes, IDictionary<TVertex, Thickness> vertexBorders, IDictionary<TVertex, <API key>> layoutTypes) { <API key>(100, 100); var <API key> = new Queue<TVertex>(); _rootCompoundVertex.Children = new HashSet<VertexData>(); InitialLevels(); InitSimpleVertices(vertexSizes); <API key>(vertexBorders, vertexSizes, layoutTypes, /*out*/ <API key>); SetLevelIndices(); //TODO do we need this? <API key>(<API key>); <API key>(); <API key>(); } private void <API key>() { //get the average width and height double sumWidth = 0, sumHeight = 0; foreach (var vertex in _levels[0]) { var v = _vertexDatas[vertex]; sumWidth += v.Size.Width; sumHeight += v.Size.Height; } if (_levels[0].Count > 0) <API key> = Math.Min(sumWidth, sumHeight) / _levels[0].Count; } private void <API key>() { bool removed = true; for (int i = 0; removed; i++) { removed = false; foreach (var vertex in _levels[0]) { if (_compoundGraph.Degree(vertex) != 1 || _compoundGraph.IsCompoundVertex(vertex)) continue; TEdge edge = default(TEdge); if (_compoundGraph.InDegree(vertex) > 0) edge = _compoundGraph.InEdge(vertex, 0); else edge = _compoundGraph.OutEdge(vertex, 0); if (<API key>.Contains(edge)) continue; //the vertex is a leaf tree node removed = true; while (<API key>.Count <= i) <API key>.Push(new List<RemovedTreeNodeData>()); //add to the removed vertices <API key>.Peek().Add(new RemovedTreeNodeData(vertex, edge)); <API key>.Add(vertex); <API key>.Add(edge); } if (removed && <API key>.Count > 0) //remove from the level foreach (var tnd in <API key>.Peek()) { _levels[0].Remove(tnd.Vertex); //remove the vertex from the graph _compoundGraph.RemoveEdge(tnd.Edge); _compoundGraph.RemoveVertex(tnd.Vertex); } } } private void <API key>(Queue<TVertex> <API key>) { while (<API key>.Count > 0) { //geth the compound vertex with the fixed layout var <API key> = <API key>.Dequeue(); //find the not fixed predecessor TVertex movableVertex = <API key>; for (; ; ) { //if the vertex hasn't parent if (movableVertex == null) break; TVertex parent = _compoundGraph.GetParent(movableVertex); if (parent == null) break; //if the parent's layout type is fixed if (<API key>[parent].<API key> != <API key>.Fixed) break; movableVertex = parent; } //the movable vertex is the ancestor of the children of the vertex //that could be moved //fix the child vertices and set the movable parent foreach (var childVertex in _compoundGraph.GetChildrenVertices(<API key>)) { var data = _vertexDatas[childVertex]; data.IsFixedToParent = true; data.MovableParent = _vertexDatas[movableVertex]; } } } <summary> Initializes the data of the simple vertices. </summary> <param name="vertexSizes">Dictionary of the vertex sizes.</param> private void InitSimpleVertices(IDictionary<TVertex, Size> vertexSizes) { foreach (var vertex in _compoundGraph.SimpleVertices) { Size vertexSize; vertexSizes.TryGetValue(vertex, out vertexSize); var position = new Point(); VertexPositions.TryGetValue(vertex, out position); //create the information container for this simple vertex var dataContainer = new SimpleVertexData(vertex, _rootCompoundVertex, false, position, vertexSize); dataContainer.Parent = _rootCompoundVertex; _simpleVertexDatas[vertex] = dataContainer; _vertexDatas[vertex] = dataContainer; _rootCompoundVertex.Children.Add(dataContainer); } } <summary> Initializes the data of the compound vertices. </summary> <param name="vertexBorders">Dictionary of the border thicknesses.</param> <param name="vertexSizes">Dictionary of the vertex sizes.</param> <param name="layoutTypes">Dictionary of the layout types.</param> <param name="<API key>">The compound vertices with fixed layout should be added to this queue.</param> private void <API key>( IDictionary<TVertex, Thickness> vertexBorders, IDictionary<TVertex, Size> vertexSizes, IDictionary<TVertex, <API key>> layoutTypes, Queue<TVertex> <API key>) { for (int i = _levels.Count - 1; i >= 0; i { foreach (var vertex in _levels[i]) { if (!_compoundGraph.IsCompoundVertex(vertex)) continue; //get the data of the vertex Thickness border; vertexBorders.TryGetValue(vertex, out border); Size vertexSize; vertexSizes.TryGetValue(vertex, out vertexSize); var layoutType = <API key>.Automatic; layoutTypes.TryGetValue(vertex, out layoutType); if (layoutType == <API key>.Fixed) { <API key>.Enqueue(vertex); } var position = new Point(); VertexPositions.TryGetValue(vertex, out position); //create the information container for this compound vertex var dataContainer = new CompoundVertexData(vertex, _rootCompoundVertex, false, position, vertexSize, border, layoutType); if (i == 0) { dataContainer.Parent = _rootCompoundVertex; _rootCompoundVertex.Children.Add(dataContainer); } <API key>[vertex] = dataContainer; _vertexDatas[vertex] = dataContainer; //add the datas of the childrens var children = _compoundGraph.GetChildrenVertices(vertex); var childrenData = children.Select(v => _vertexDatas[v]).ToList(); dataContainer.Children = childrenData; foreach (var child in dataContainer.Children) { _rootCompoundVertex.Children.Remove(child); child.Parent = dataContainer; } } } } private void InitialLevels() { var verticesLeft = new HashSet<TVertex>(VisitedGraph.Vertices); //initial 0th level _levels.Add(new HashSet<TVertex>(VisitedGraph.Vertices.Where(v => _compoundGraph.GetParent(v) == default(TVertex)))); RemoveAll(verticesLeft, _levels[0]); //other layers for (int i = 1; verticesLeft.Count > 0; i++) { var nextLevel = new HashSet<TVertex>(); foreach (var parent in _levels[i - 1]) { if (_compoundGraph.GetChildrenCount(parent) <= 0) continue; foreach (var children in _compoundGraph.GetChildrenVertices(parent)) nextLevel.Add(children); } _levels.Add(nextLevel); RemoveAll(verticesLeft, nextLevel); } } private void SetLevelIndices() { //set the level indexes in the vertex datas for (int i = 0; i < _levels.Count; i++) { foreach (var v in _levels[i]) _vertexDatas[v].Level = i; } } } }
// <API key>.h // KeyBoard #import <UIKit/UIKit.h> @interface <API key> : <API key> @end
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict //EN"> <html> <head> <title>Save/Delete in Ebean</title> <link rel="shortcut icon" href="/image/favicon.ico" > <link rel="stylesheet" type="text/css" href="/static/v2style.css" > <! <link rel="stylesheet" type="text/css" href="/css/100/basestyle|syntaxhighlighter" > <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" href="/doc/ie.css" media="screen"> <![endif] <meta name="description" content="Save/Delete in Ebean"> <script type="text/javascript" src="/doc/jslib.js" ></script> <! <script type="text/javascript" src="/jsl/jquery|jquery.corner|mygoo|app|shCore|shBrushJava|shBrushProperty|shBrushSql" ></script> <script type="text/javascript"> $(document).ready(function(){ $(".topic").corner("12px"); $("a.action").corner("8px hover"); $("div.example").corner("5px"); $(".reqrlogin").hide(); //dp.SyntaxHighlighter.ClipboardSwf = '/flash/clipboard.swf'; dp.SyntaxHighlighter.HighlightAll('code'); }); </script> <!-- component('cn=app.comp.LoginEnable') --> </head> <body> <form action='/ebean/introsavedelete.html' method="post" id="GLOBAL_ACTION"> <input type='hidden' name='_WOGA_CONTROLLER' > <input type='hidden' name='_WOGA_METHOD' > <input type='hidden' name='_WOGA_PARAM' > <input type='hidden' name='_WOGA_RENDER' > <a id="top"></a> <div id="headwrap"> <div id="headmax"> <div id="menuuser"> <!-- component('cn=app.comp.UserStatus') --> </div> <img id="logo" src="/image/logo-avaje.gif" width="127" height="50" alt="avaje logo"> <div style="clear:both;"></div> </div> </div><!-- end of headwrap --> <div id="head2wrap"> <div id="head2max"> <table summary="layout"> <tr> <td align="center"> <div id="menutab" style=""> <a id="m0" href="/" class="popmenu"><span>home</span></a> <a id="m1" href="/ebean/documentation.html" class="popmenu"><span>documentation</span></a> <a id="m4" href="/download.html" class="popmenu"><span>downloads</span></a> <a id="m6" href="http://groups.google.com/group/ebean" class="popmenu"><span>google group</span></a> <a id="m2" href="/forum.html" class="popmenu"><span>forums<img src="/image/menuDownH6_3.gif" width="11" height="11" alt=""></span></a> <a id="m3" href="/bug.html" class="popmenu"><span>bugs<img src="/image/menuDownH6_3.gif" width="11" height="11" alt=""></span></a> <a id="m5" href="/feedback.html" class="popmenu"><span>feedback</span></a> </div> </td> </tr> </table> </div> </div> <div id="bodywrap"> <div id="bodymax"> <div id="content"> <div id="pageBody"> <div id="breadcrumb"> <img src="/image/smallhome.gif"> <a href="/">Home</a> &raquo; <a href="/ebean/introduction.html">Ebean</a> &raquo; <a href="/ebean/documentation.html">Docs</a> &raquo; <span>Save/Delete</span> </div> <div class="columnlayout"> <h3>Save/Delete</h3> <div class="example">example</div> <div class="col70"> <p> Save will either insert or update the bean depending on its state. </p> </div> <div class="col70"> <pre class="java:nogutter:nocontrols"> Order order = new Order(); order.setOrderDate(new Date()); // insert the order Ebean.save(order); </pre> <p> If the bean was fetched it will be updated... </p> </div> <div class="col70"> <pre class="java:nogutter:nocontrols"> Order order = Ebean.find(Order.class, 12); order.setStatus("SHIPPED"); // update the order Ebean.save(order); </pre> </div> <div class="colend"></div> <div class="example">example</div> <div class="col70"> <p> Save and Delete will CASCADE based on the CascadeType specificed on the associated @OneToMany, @OneToOne etc annotation. </p> <p> By default save and delete will not cascade so you need to specify a cascade type (such as the one on details below) for save() or delete() to cascade. </p> </div> <div class="col70"> <pre class="java:nogutter:nocontrols"> // the Entity bean with its Mapping Annotations @Entity @Table(name="or_order") public class Order { // no cascading @ManyToOne Customer customer; // save and delete cascaded @OneToMany(cascade=CascadeType.ALL) List&lt;OrderDetail&gt; details; </pre> </div> <div class="col70"> <p> Note the <em>@OneToMany(cascade=CascadeType.ALL)</em> on the details property. This means save() and delete() will both casade from order to its order details. </p> </div> <div class="col70"> <pre class="java:nogutter:nocontrols"> // save the order ... will cascade also saving the order details Ebean.save(order); </pre> </div> <div class="colend"></div> <div class="example">example</div> <div class="col70"> <p> Delete is very similar to save. Just call Ebean.delete(); </p> </div> <div class="col70"> <pre class="java:nogutter:nocontrols"> Order order = Ebean.find(Order.class, 12); // delete the order // ... this will cascade also deleting the order details // ... with either CascadeType.ALL or CascadeType.REMOVE Ebean.delete(order); </pre> </div> <div class="colend"></div> <div class="col70"> <p> Go <a href="introtrans.html">here</a> to see how <a href="introtrans.html">Transaction demarcation</a> is done. </p> </div> <div class="colend"></div> <div class="col70 colnext"> <a class="h3" href="/ebean/introduction.html">Back: to Ebean Introduction</a> </div> <div class="colend"></div> </div> </div> </div> </div> </div><!-- end of bodywrap --> <div id="footwrap"> <div id="footmax"> <div id="foot"> <a href="/">home</a> | <a href="#top">back to top</a> </div> </div> </div><!-- end of footwrap --> <!-- layers --> <div id="m1popxxx" class="popmenuchild"> <a href="/ebean/introduction.html">Introduction</a> <a href="/doc/ebean-userguide.pdf">User Guide (pdf)</a> <a href="/configure.html">Install/Configure</a> <a href="/static/javadoc/pub/index.html">Public JavaDoc</a> <a href="/whitepaper.html">Whitepapers</a> </div> <div id="m2pop" class="popmenuchild"> <a href="/forumdetail-1.html">General</a> <a href="/forumdetail-2.html">Database Specific</a> <a href="/forumdetail-3.html">Byte Code</a> <a href="/forumdetail-4.html">Deployment Annotations</a> <a href="/forumdetail-5.html">Features</a> </div> <div id="m3pop" class="popmenuchild"> <a href="/bug.html">Top Bugs</a> <a href="/enh.html">Top Enhancements</a> </div> <div id="woResponse">woResponse</div> </form> <div id="woFocusDelay"></div> </body> </html>
package com.sxj.SeeWeather.modules.ui.about; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceFragment; import com.sxj.SeeWeather.R; public class AboutFragment extends PreferenceFragment implements Preference.<API key> { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); <API key>(R.xml.about); } @Override public boolean onPreferenceClick(Preference preference) { return false; } }
package me.tatarka.lens.autovalue.sample; import com.google.auto.value.AutoValue; import me.tatarka.lens.IntLens; import me.tatarka.lens.autovalue.AutoValueLenses; @AutoValue public abstract class Person { public static Person create(int age) { return new AutoValue_Person(age); } public static Lenses lenses() { return AutoValue_Person.Lenses.instance; } public abstract int age(); @AutoValueLenses public interface Lenses { IntLens<Person> age(); } }
package my.work.stock.system.shiro; import my.work.stock.system.domain.entity.UserInfo; import my.work.stock.system.domain.service.UserInfoService; import org.apache.shiro.authc.<API key>; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.<API key>; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.<API key>; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; public class MyShiroRealm extends AuthorizingRealm { private static final Logger logger = LoggerFactory.getLogger(MyShiroRealm.class); @Autowired private UserInfoService userInfoService; @Override protected AuthorizationInfo <API key>(PrincipalCollection principalCollection) { return null; } @Override protected AuthenticationInfo <API key>(Authentication<API key>) throws <API key> { String userName = (String) authenticationToken.getPrincipal(); UserInfo userInfo = userInfoService.findByUserName(userName); if (userInfo == null) { return null; } <API key> authenticationInfo = new <API key>( userInfo, userInfo.getPassword(), getName() //realm name ); return authenticationInfo; } }
(function() { 'use strict'; angular .module('facilitymgmtApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig($stateProvider) { $stateProvider.state('account', { abstract: true, parent: 'app' }); } })();
## Treebank Statistics (UD_Chinese) This relation is universal. There are 4 language-specific subtypes of `case`: [case:aspect](), [case:dec](), [case:pref](), [case:suff](). 3218 nodes (3%) are attached to their parents as `case`. 3201 instances of `case` (99%) are right-to-left (child precedes parent). Average distance between parent and child is 3.2119328775637. The following 13 pairs of parts of speech are connected with `case`: [zh-pos/NOUN]()-[zh-pos/ADP]() (1897; 59% instances), [zh-pos/VERB]()-[zh-pos/ADP]() (588; 18% instances), [zh-pos/PART]()-[zh-pos/ADP]() (244; 8% instances), [zh-pos/PROPN]()-[zh-pos/ADP]() (208; 6% instances), [zh-pos/PRON]()-[zh-pos/ADP]() (164; 5% instances), [zh-pos/ADJ]()-[zh-pos/ADP]() (59; 2% instances), [zh-pos/X]()-[zh-pos/ADP]() (26; 1% instances), [zh-pos/ADV]()-[zh-pos/ADP]() (12; 0% instances), [zh-pos/NUM]()-[zh-pos/ADP]() (10; 0% instances), [zh-pos/ADP]()-[zh-pos/ADP]() (6; 0% instances), [zh-pos/PUNCT]()-[zh-pos/ADP]() (2; 0% instances), [zh-pos/AUX]()-[zh-pos/ADP]() (1; 0% instances), [zh-pos/DET]()-[zh-pos/ADP]() (1; 0% instances). conllu # visual-style 18 bgColor:blue # visual-style 18 fgColor:white # visual-style 22 bgColor:blue # visual-style 22 fgColor:white # visual-style 22 18 case color:blue 1 VERB VV _ 12 acl _ SpaceAfter=No 2 NOUN NN _ 1 obj _ SpaceAfter=No 3 PUNCT EC _ 4 punct _ SpaceAfter=No 4 NOUN NN _ 2 conj _ SpaceAfter=No 5 PUNCT EC _ 6 punct _ SpaceAfter=No 6 NOUN NN _ 2 conj _ SpaceAfter=No 7 PUNCT EC _ 8 punct _ SpaceAfter=No 8 NOUN NN _ 2 conj _ SpaceAfter=No 9 CCONJ CC _ 10 cc _ SpaceAfter=No 10 NOUN NN _ 2 conj _ SpaceAfter=No 11 NOUN NN _ 2 acl _ SpaceAfter=No 12 VERB VV _ 23 acl _ SpaceAfter=No 13 ADP IN _ 12 mark _ SpaceAfter=No 14 , , PUNCT , _ 23 punct _ SpaceAfter=No 15 NOUN NN _ 23 nsubj _ SpaceAfter=No 16 ADV RB _ 23 advmod _ SpaceAfter=No 17 AUX MD _ 23 aux _ SpaceAfter=No 18 ADP IN _ 22 case _ SpaceAfter=No 19 ADV RB _ 20 advmod _ SpaceAfter=No 20 VERB VV _ 22 acl:relcl _ SpaceAfter=No 21 PART DEC _ 20 mark:relcl _ SpaceAfter=No 22 NOUN NN _ 23 obl _ SpaceAfter=No 23 VERB VV _ 0 root _ SpaceAfter=No 24 . . PUNCT . _ 23 punct _ SpaceAfter=No conllu # visual-style 3 bgColor:blue # visual-style 3 fgColor:white # visual-style 4 bgColor:blue # visual-style 4 fgColor:white # visual-style 4 3 case color:blue 1 DET DT _ 2 det _ SpaceAfter=No 2 NOUN NN _ 10 nsubj _ SpaceAfter=No 3 ADP IN _ 4 case _ SpaceAfter=No 4 VERB VV _ 10 xcomp _ SpaceAfter=No 5 NOUN NN _ 6 nsubj _ SpaceAfter=No 6 VERB VV _ 4 ccomp _ SpaceAfter=No 7 , , PUNCT , _ 10 punct _ SpaceAfter=No 8 ADV RB _ 10 advmod _ SpaceAfter=No 9 AUX MD _ 10 aux _ SpaceAfter=No 10 VERB VV _ 0 root _ SpaceAfter=No 11 ADJ JJ _ 14 amod _ SpaceAfter=No 12 PART DEC _ 11 mark:relcl _ SpaceAfter=No 13 NOUN NN _ 14 nmod _ SpaceAfter=No 14 NOUN NN _ 10 obj _ SpaceAfter=No 15 PUNCT EC _ 17 punct _ SpaceAfter=No 16 NOUN NN _ 17 case:suff _ SpaceAfter=No 17 PART SFN _ 14 conj _ SpaceAfter=No 18 PUNCT EC _ 20 punct _ SpaceAfter=No 19 NOUN NN _ 20 case:suff _ SpaceAfter=No 20 PART SFN _ 14 conj _ SpaceAfter=No 21 , , PUNCT , _ 23 punct _ SpaceAfter=No 22 CCONJ CC _ 23 cc _ SpaceAfter=No 23 NOUN NN _ 14 conj _ SpaceAfter=No 24 CCONJ CC _ 25 cc _ SpaceAfter=No 25 NOUN NN _ 23 conj _ SpaceAfter=No 26 . . PUNCT . _ 10 punct _ SpaceAfter=No conllu # visual-style 2 bgColor:blue # visual-style 2 fgColor:white # visual-style 4 bgColor:blue # visual-style 4 fgColor:white # visual-style 4 2 case color:blue 1 NOUN NN _ 19 nsubj _ SpaceAfter=No 2 ADP IN _ 4 case _ SpaceAfter=No 3 PROPN NNP _ 4 case:suff _ SpaceAfter=No 4 PART SFN _ 5 obl _ SpaceAfter=No 5 VERB VV _ 9 acl _ SpaceAfter=No 6 PROPN NNP _ 7 nmod _ SpaceAfter=No 7 NOUN NN _ 5 obj _ SpaceAfter=No 8 ADP IN _ 5 mark _ SpaceAfter=No 9 VERB VV _ 19 acl _ SpaceAfter=No 10 ADP IN _ 11 case _ SpaceAfter=No 11 NOUN NN _ 12 obl _ SpaceAfter=No 12 VERB VV _ 9 xcomp _ SpaceAfter=No 13 , , PUNCT , _ 19 punct _ SpaceAfter=No 14 VERB VV _ 19 acl _ SpaceAfter=No 15 PROPN NNP _ 17 nmod _ SpaceAfter=No 16 PROPN NNP _ 17 nmod _ SpaceAfter=No 17 NOUN NN _ 14 obj _ SpaceAfter=No 18 ADP IN _ 14 mark _ SpaceAfter=No 19 VERB VV _ 0 root _ SpaceAfter=No 20 PROPN NNP _ 23 nmod _ SpaceAfter=No 21 PROPN NNP _ 23 nmod _ SpaceAfter=No 22 NOUN NN _ 23 nmod _ SpaceAfter=No 23 NOUN NN _ 19 obj _ SpaceAfter=No 24 . . PUNCT . _ 19 punct _ SpaceAfter=No
package org.openecard.sal.protocol.genericcryptography; import iso.std.iso_iec._24727.tech.schema.<API key>; import iso.std.iso_iec._24727.tech.schema.<API key>; import iso.std.iso_iec._24727.tech.schema.DIDScopeType; import iso.std.iso_iec._24727.tech.schema.DIDStructureType; import iso.std.iso_iec._24727.tech.schema.Sign; import iso.std.iso_iec._24727.tech.schema.SignResponse; import iso.std.iso_iec._24727.tech.schema.TransmitResponse; import java.util.Collections; import java.util.Map; import org.openecard.addon.sal.FunctionType; import org.openecard.addon.sal.ProtocolStep; import org.openecard.bouncycastle.util.Arrays; import org.openecard.common.ECardException; import org.openecard.common.WSHelper; import org.openecard.common.apdu.<API key>; import org.openecard.common.apdu.<API key>; import org.openecard.common.apdu.common.CardCommandAPDU; import org.openecard.common.apdu.common.CardResponseAPDU; import org.openecard.common.interfaces.Dispatcher; import org.openecard.common.sal.Assert; import org.openecard.common.sal.anytype.CryptoMarkerType; import org.openecard.common.sal.exception.<API key>; import org.openecard.common.sal.state.CardStateEntry; import org.openecard.common.sal.util.SALUtils; import org.openecard.common.tlv.TLV; import org.openecard.common.util.ByteUtils; import org.openecard.sal.protocol.genericcryptography.apdu.<API key>; import org.openecard.sal.protocol.genericcryptography.apdu.PSOHash; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implements the Sign step of the Generic cryptography protocol. * See TR-03112, version 1.1.2, part 7, section 4.9.9. * * @author Dirk Petrautzki <petrautzki@hs-coburg.de> */ public class SignStep implements ProtocolStep<Sign, SignResponse> { private static final Logger logger = LoggerFactory.getLogger(SignStep.class); //TODO extract the blocksize from somewhere private static final byte BLOCKSIZE = (byte) 256; private static final byte SET_COMPUTATION = (byte) 0x41; private static final byte <API key> = (byte) 0x84; private final Dispatcher dispatcher; /** * Creates a new SignStep. * * @param dispatcher Dispatcher */ public SignStep(Dispatcher dispatcher) { this.dispatcher = dispatcher; } @Override public FunctionType getFunctionType() { return FunctionType.Sign; } @Override public SignResponse perform(Sign sign, Map<String, Object> internalData) { SignResponse response = WSHelper.makeResponse(SignResponse.class, WSHelper.makeResultOK()); try { <API key> connectionHandle = SALUtils.getConnectionHandle(sign); String didName = SALUtils.getDIDName(sign); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(internalData, connectionHandle); DIDStructureType didStructure = SALUtils.getDIDStructure(sign, didName, cardStateEntry, connectionHandle); CryptoMarkerType cryptoMarker = new CryptoMarkerType(didStructure.getDIDMarker()); byte[] slotHandle = connectionHandle.getSlotHandle(); byte[] applicationID = connectionHandle.getCardApplication(); Assert.<API key>(cardStateEntry, applicationID, didName, <API key>.SIGN); byte[] keyReference = cryptoMarker.getCryptoKeyInfo().getKeyRef().getKeyRef(); byte[] algorithmIdentifier = cryptoMarker.getAlgorithmInfo().getCardAlgRef(); if (didStructure.getDIDScope().equals(DIDScopeType.LOCAL)) { keyReference[0] = (byte) (0x80 | keyReference[0]); } byte[] message = sign.getMessage(); byte[] signature = new byte[0]; TLV <API key> = new TLV(); <API key>.setTagNumWithClass(0x80); <API key>.setValue(algorithmIdentifier); CardCommandAPDU cmdAPDU = null; CardResponseAPDU responseAPDU = null; String[] <API key> = cryptoMarker.<API key>(); for (int i = 0; i < <API key>.length; i++) { String command = <API key>[i]; String nextCmd = ""; if (i < <API key>.length - 1) { nextCmd = <API key>[i + 1]; } if (command.equals("MSE_KEY")) { TLV tagKeyReference = new TLV(); tagKeyReference.setTagNumWithClass(<API key>); tagKeyReference.setValue(keyReference); if (nextCmd.equals("PSO_CDS")) { byte[] mseData = ByteUtils.concatenate(tagKeyReference.toBER(), <API key>.toBER()); cmdAPDU = new <API key>(SET_COMPUTATION, <API key>.DST, mseData); } else if (nextCmd.equals("INT_AUTH")) { byte[] mseData = ByteUtils.concatenate(tagKeyReference.toBER(), <API key>.toBER()); cmdAPDU = new <API key>(SET_COMPUTATION, <API key>.AT, mseData); } else { String msg = "The command 'MSE_KEY' followed by '" + nextCmd + "' is currently not supported."; logger.error(msg); throw new <API key>(msg); } } else if (command.equals("PSO_CDS")) { cmdAPDU = new <API key>(message, BLOCKSIZE); } else if (command.equals("INT_AUTH")) { cmdAPDU = new <API key>(message, BLOCKSIZE); } else if (command.equals("MSE_RESTORE")) { cmdAPDU = new <API key>.Restore(<API key>.DST); } else if (command.equals("MSE_HASH")) { cmdAPDU = new <API key>.Set(SET_COMPUTATION, <API key>.HT); } else if (command.equals("PSO_HASH")) { cmdAPDU = new PSOHash(signature); } else if (command.equals("MSE_DS")) { cmdAPDU = new <API key>.Set(SET_COMPUTATION, <API key>.DST); } else if (command.equals("MSE_KEY_DS")) { cmdAPDU = new <API key>.Set(SET_COMPUTATION, <API key>.DST); } else { String msg = "The signature generation command '" + command + "' is unknown."; throw new <API key>(msg); } responseAPDU = cmdAPDU.transmit(dispatcher, slotHandle, Collections.<byte[]>emptyList()); } byte[] signedMessage = responseAPDU.getData(); // check if further response data is available while (responseAPDU.getTrailer()[0] == (byte) 0x61) { CardCommandAPDU getResponseData = new CardCommandAPDU((byte) 0x00, (byte) 0xC0, (byte) 0x00, (byte) 0x00, responseAPDU.getTrailer()[1]); responseAPDU = getResponseData.transmit(dispatcher, slotHandle, Collections.<byte[]>emptyList()); signedMessage = Arrays.concatenate(signedMessage, responseAPDU.getData()); } if (! Arrays.areEqual(responseAPDU.getTrailer(), new byte[] {(byte) 0x90, (byte) 0x00})) { TransmitResponse tr = new TransmitResponse(); tr.getOutputAPDU().add(responseAPDU.toByteArray()); WSHelper.checkResult(response); } response.setSignature(signedMessage); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.warn(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } }
__author__ = 'Dzmitry' def test_login(app): app.session.login("administrator", "root") assert app.session.is_logged_in_as("administrator")
// <API key>.h // CustomCell #import <UIKit/UIKit.h> @interface <API key> : <API key> @end
/*global define*/ define([ '../Core/Color', '../Core/defined', '../Core/destroyObject', '../Core/PixelFormat', '../Renderer/ClearCommand', '../Renderer/PixelDatatype', '../Renderer/RenderState', '../Renderer/ShaderSource', '../Shaders/AdjustTranslucentFS', '../Shaders/CompositeOITFS', './BlendEquation', './BlendFunction' ], function( Color, defined, destroyObject, PixelFormat, ClearCommand, PixelDatatype, RenderState, ShaderSource, AdjustTranslucentFS, CompositeOITFS, BlendEquation, BlendFunction) { "use strict"; /*global <API key>*/ /** * @private */ var OIT = function(context) { // We support multipass for the Chrome D3D9 backend and ES 2.0 on mobile. this.<API key> = false; this.<API key> = false; var extensionsSupported = context.<API key> && context.depthTexture; this.<API key> = context.drawBuffers && extensionsSupported; this.<API key> = !this.<API key> && extensionsSupported; this._opaqueFBO = undefined; this._opaqueTexture = undefined; this.<API key> = undefined; this.<API key> = undefined; this._translucentFBO = undefined; this._alphaFBO = undefined; this.<API key> = undefined; this._adjustAlphaFBO = undefined; this._opaqueClearCommand = new ClearCommand({ color : new Color(0.0, 0.0, 0.0, 0.0), owner : this }); this.<API key> = new ClearCommand({ color : new Color(0.0, 0.0, 0.0, 1.0), owner : this }); this.<API key> = new ClearCommand({ color : new Color(0.0, 0.0, 0.0, 0.0), owner : this }); this._alphaClearCommand = new ClearCommand({ color : new Color(1.0, 1.0, 1.0, 1.0), owner : this }); this.<API key> = {}; this.<API key> = {}; this.<API key> = {}; this._alphaShaderCache = {}; this._compositeCommand = undefined; this.<API key> = undefined; this._adjustAlphaCommand = undefined; }; function destroyTextures(oit) { oit.<API key> = oit.<API key> && !oit.<API key>.isDestroyed() && oit.<API key>.destroy(); oit._revealageTexture = oit._revealageTexture && !oit._revealageTexture.isDestroyed() && oit._revealageTexture.destroy(); } function destroyFramebuffers(oit) { oit._translucentFBO = oit._translucentFBO && !oit._translucentFBO.isDestroyed() && oit._translucentFBO.destroy(); oit._alphaFBO = oit._alphaFBO && !oit._alphaFBO.isDestroyed() && oit._alphaFBO.destroy(); oit.<API key> = oit.<API key> && !oit.<API key>.isDestroyed() && oit.<API key>.destroy(); oit._adjustAlphaFBO = oit._adjustAlphaFBO && !oit._adjustAlphaFBO.isDestroyed() && oit._adjustAlphaFBO.destroy(); } function destroyResources(oit) { destroyTextures(oit); destroyFramebuffers(oit); } function updateTextures(oit, context, width, height) { destroyTextures(oit); oit.<API key> = context.createTexture2D({ width : width, height : height, pixelFormat : PixelFormat.RGBA, pixelDatatype : PixelDatatype.FLOAT }); oit._revealageTexture = context.createTexture2D({ width : width, height : height, pixelFormat : PixelFormat.RGBA, pixelDatatype : PixelDatatype.FLOAT }); } function updateFramebuffers(oit, context) { destroyFramebuffers(oit); var completeFBO = <API key>.<API key>; var supported = true; // if MRT is supported, attempt to make an FBO with multiple color attachments if (oit.<API key>) { oit._translucentFBO = context.createFramebuffer({ colorTextures : [oit.<API key>, oit._revealageTexture], depthStencilTexture : oit.<API key>, destroyAttachments : false }); oit.<API key> = context.createFramebuffer({ colorTextures : [oit.<API key>, oit._revealageTexture], destroyAttachments : false }); if (oit._translucentFBO.status !== completeFBO || oit.<API key>.status !== completeFBO) { destroyFramebuffers(oit); oit.<API key> = false; } } // either MRT isn't supported or FBO creation failed, attempt multipass if (!oit.<API key>) { oit._translucentFBO = context.createFramebuffer({ colorTextures : [oit.<API key>], depthStencilTexture : oit.<API key>, destroyAttachments : false }); oit._alphaFBO = context.createFramebuffer({ colorTextures : [oit._revealageTexture], depthStencilTexture : oit.<API key>, destroyAttachments : false }); oit.<API key> = context.createFramebuffer({ colorTextures : [oit.<API key>], destroyAttachments : false }); oit._adjustAlphaFBO = context.createFramebuffer({ colorTextures : [oit._revealageTexture], destroyAttachments : false }); var translucentComplete = oit._translucentFBO.status === completeFBO; var alphaComplete = oit._alphaFBO.status === completeFBO; var <API key> = oit.<API key>.status === completeFBO; var adjustAlphaComplete = oit._adjustAlphaFBO.status === completeFBO; if (!translucentComplete || !alphaComplete || !<API key> || !adjustAlphaComplete) { destroyResources(oit); oit.<API key> = false; supported = false; } } return supported; } OIT.prototype.update = function(context, framebuffer) { if (!this.isSupported()) { return; } this._opaqueFBO = framebuffer; this._opaqueTexture = framebuffer.getColorTexture(0); this.<API key> = framebuffer.depthStencilTexture; var width = this._opaqueTexture.width; var height = this._opaqueTexture.height; var accumulationTexture = this.<API key>; var textureChanged = !defined(accumulationTexture) || accumulationTexture.width !== width || accumulationTexture.height !== height; if (textureChanged) { updateTextures(this, context, width, height); } if (!defined(this._translucentFBO) || textureChanged) { if (!updateFramebuffers(this, context)) { // framebuffer creation failed return; } } var that = this; var fs; var uniformMap; if (!defined(this._compositeCommand)) { fs = new ShaderSource({ sources : [CompositeOITFS] }); if (this.<API key>) { fs.defines.push('MRT'); } uniformMap = { u_opaque : function() { return that._opaqueTexture; }, u_accumulation : function() { return that.<API key>; }, u_revealage : function() { return that._revealageTexture; } }; this._compositeCommand = context.<API key>(fs, { renderState : context.createRenderState(), uniformMap : uniformMap, owner : this }); } if (!defined(this.<API key>)) { if (this.<API key>) { fs = new ShaderSource({ defines : ['MRT'], sources : [AdjustTranslucentFS] }); uniformMap = { u_bgColor : function() { return that.<API key>.color; }, u_depthTexture : function() { return that.<API key>; } }; this.<API key> = context.<API key>(fs, { renderState : context.createRenderState(), uniformMap : uniformMap, owner : this }); } else if (this.<API key>) { fs = new ShaderSource({ sources : [AdjustTranslucentFS] }); uniformMap = { u_bgColor : function() { return that.<API key>.color; }, u_depthTexture : function() { return that.<API key>; } }; this.<API key> = context.<API key>(fs, { renderState : context.createRenderState(), uniformMap : uniformMap, owner : this }); uniformMap = { u_bgColor : function() { return that._alphaClearCommand.color; }, u_depthTexture : function() { return that.<API key>; } }; this._adjustAlphaCommand = context.<API key>(fs, { renderState : context.createRenderState(), uniformMap : uniformMap, owner : this }); } } }; var translucentMRTBlend = { enabled : true, color : new Color(0.0, 0.0, 0.0, 0.0), equationRgb : BlendEquation.ADD, equationAlpha : BlendEquation.ADD, functionSourceRgb : BlendFunction.ONE, <API key> : BlendFunction.ONE, functionSourceAlpha : BlendFunction.ZERO, <API key> : BlendFunction.<API key> }; var <API key> = { enabled : true, color : new Color(0.0, 0.0, 0.0, 0.0), equationRgb : BlendEquation.ADD, equationAlpha : BlendEquation.ADD, functionSourceRgb : BlendFunction.ONE, <API key> : BlendFunction.ONE, functionSourceAlpha : BlendFunction.ONE, <API key> : BlendFunction.ONE }; var <API key> = { enabled : true, color : new Color(0.0, 0.0, 0.0, 0.0), equationRgb : BlendEquation.ADD, equationAlpha : BlendEquation.ADD, functionSourceRgb : BlendFunction.ZERO, <API key> : BlendFunction.<API key>, functionSourceAlpha : BlendFunction.ZERO, <API key> : BlendFunction.<API key> }; function <API key>(context, translucentBlending, cache, renderState) { var translucentState = cache[renderState.id]; if (!defined(translucentState)) { var rs = RenderState.clone(renderState); rs.depthMask = false; rs.blending = translucentBlending; translucentState = context.createRenderState(rs); cache[renderState.id] = translucentState; } return translucentState; } function <API key>(oit, context, renderState) { return <API key>(context, translucentMRTBlend, oit.<API key>, renderState); } function <API key>(oit, context, renderState) { return <API key>(context, <API key>, oit.<API key>, renderState); } function <API key>(oit, context, renderState) { return <API key>(context, <API key>, oit.<API key>, renderState); } var mrtShaderSource = ' vec3 Ci = czm_gl_FragColor.rgb * czm_gl_FragColor.a;\n' + ' float ai = czm_gl_FragColor.a;\n' + ' float wzi = czm_alphaWeight(ai);\n' + ' gl_FragData[0] = vec4(Ci * wzi, ai);\n' + ' gl_FragData[1] = vec4(ai * wzi);\n'; var colorShaderSource = ' vec3 Ci = czm_gl_FragColor.rgb * czm_gl_FragColor.a;\n' + ' float ai = czm_gl_FragColor.a;\n' + ' float wzi = czm_alphaWeight(ai);\n' + ' gl_FragColor = vec4(Ci, ai) * wzi;\n'; var alphaShaderSource = ' float ai = czm_gl_FragColor.a;\n' + ' gl_FragColor = vec4(ai);\n'; function <API key>(context, shaderProgram, cache, source) { var id = shaderProgram.id; var shader = cache[id]; if (!defined(shader)) { var attributeLocations = shaderProgram._attributeLocations; var fs = shaderProgram.<API key>.clone(); fs.sources = fs.sources.map(function(source) { source = source.replace(/void\s+main\s*\(\s*(?:void)?\s*\)/g, 'void <API key>()'); source = source.replace(/gl_FragColor/g, 'czm_gl_FragColor'); source = source.replace(/\bdiscard\b/g, 'czm_discard = true'); source = source.replace(/czm_phong/g, '<API key>'); return source; }); // Discarding the fragment in main is a workaround for ANGLE D3D9 // shader compilation errors. fs.sources.splice(0, 0, (source.indexOf('gl_FragData') !== -1 ? '#extension GL_EXT_draw_buffers : enable \n' : '') + 'vec4 czm_gl_FragColor;\n' + 'bool czm_discard = false;\n'); fs.sources.push( 'void main()\n' + '{\n' + ' <API key>();\n' + ' if (czm_discard)\n' + ' {\n' + ' discard;\n' + ' }\n' + source + '}\n'); shader = context.createShaderProgram(shaderProgram.vertexShaderSource, fs, attributeLocations); cache[id] = shader; } return shader; } function <API key>(oit, context, shaderProgram) { return <API key>(context, shaderProgram, oit.<API key>, mrtShaderSource); } function <API key>(oit, context, shaderProgram) { return <API key>(context, shaderProgram, oit.<API key>, colorShaderSource); } function <API key>(oit, context, shaderProgram) { return <API key>(context, shaderProgram, oit._alphaShaderCache, alphaShaderSource); } function <API key>(oit, scene, executeFunction, passState, commands) { var command; var renderState; var shaderProgram; var j; var context = scene.context; var framebuffer = passState.framebuffer; var length = commands.length; passState.framebuffer = oit.<API key>; oit.<API key>.execute(context, passState); passState.framebuffer = oit._adjustAlphaFBO; oit._adjustAlphaCommand.execute(context, passState); var debugFramebuffer = oit._opaqueFBO; passState.framebuffer = oit._translucentFBO; for (j = 0; j < length; ++j) { command = commands[j]; if (!defined(command.oit) || command.shaderProgram.id !== command.oit.shaderProgramId) { command.oit = { colorRenderState : <API key>(oit, context, command.renderState), alphaRenderState : <API key>(oit, context, command.renderState), colorShaderProgram : <API key>(oit, context, command.shaderProgram), alphaShaderProgram : <API key>(oit, context, command.shaderProgram), shaderProgramId : command.shaderProgram.id }; } renderState = command.oit.colorRenderState; shaderProgram = command.oit.colorShaderProgram; executeFunction(command, scene, context, passState, renderState, shaderProgram, debugFramebuffer); } passState.framebuffer = oit._alphaFBO; for (j = 0; j < length; ++j) { command = commands[j]; renderState = command.oit.alphaRenderState; shaderProgram = command.oit.alphaShaderProgram; executeFunction(command, scene, context, passState, renderState, shaderProgram, debugFramebuffer); } passState.framebuffer = framebuffer; } function <API key>(oit, scene, executeFunction, passState, commands) { var context = scene.context; var framebuffer = passState.framebuffer; var length = commands.length; passState.framebuffer = oit.<API key>; oit.<API key>.execute(context, passState); var debugFramebuffer = oit._opaqueFBO; passState.framebuffer = oit._translucentFBO; for (var j = 0; j < length; ++j) { var command = commands[j]; if (!defined(command.oit) || command.shaderProgram.id !== command.oit.shaderProgramId) { command.oit = { <API key> : <API key>(oit, context, command.renderState), <API key> : <API key>(oit, context, command.shaderProgram), shaderProgramId : command.shaderProgram.id }; } var renderState = command.oit.<API key>; var shaderProgram = command.oit.<API key>; executeFunction(command, scene, context, passState, renderState, shaderProgram, debugFramebuffer); } passState.framebuffer = framebuffer; } OIT.prototype.executeCommands = function(scene, executeFunction, passState, commands) { if (this.<API key>) { <API key>(this, scene, executeFunction, passState, commands); return; } <API key>(this, scene, executeFunction, passState, commands); }; OIT.prototype.execute = function(context, passState) { this._compositeCommand.execute(context, passState); }; OIT.prototype.clear = function(context, passState, clearColor) { var framebuffer = passState.framebuffer; passState.framebuffer = this._opaqueFBO; Color.clone(clearColor, this._opaqueClearCommand.color); this._opaqueClearCommand.execute(context, passState); passState.framebuffer = this._translucentFBO; var <API key> = this.<API key> ? this.<API key> : this.<API key>; <API key>.execute(context, passState); if (this.<API key>) { passState.framebuffer = this._alphaFBO; this._alphaClearCommand.execute(context, passState); } passState.framebuffer = framebuffer; }; OIT.prototype.isSupported = function() { return this.<API key> || this.<API key>; }; OIT.prototype.isDestroyed = function() { return false; }; OIT.prototype.destroy = function() { destroyResources(this); if (defined(this._compositeCommand)) { this._compositeCommand.shaderProgram = this._compositeCommand.shaderProgram && this._compositeCommand.shaderProgram.destroy(); } if (defined(this.<API key>)) { this.<API key>.shaderProgram = this.<API key>.shaderProgram && this.<API key>.shaderProgram.destroy(); } if (defined(this._adjustAlphaCommand)) { this._adjustAlphaCommand.shaderProgram = this._adjustAlphaCommand.shaderProgram && this._adjustAlphaCommand.shaderProgram.destroy(); } var name; var cache = this.<API key>; for (name in cache) { if (cache.hasOwnProperty(name) && defined(cache[name])) { cache[name].destroy(); } } this.<API key> = {}; cache = this._alphaShaderCache; for (name in cache) { if (cache.hasOwnProperty(name) && defined(cache[name])) { cache[name].destroy(); } } this._alphaShaderCache = {}; return destroyObject(this); }; return OIT; });
'use strict'; var util = require('util'); var path = require('path'); var fork = require('child_process').fork; var Configstore = require('configstore'); var request = require('request'); var chalk = require('chalk'); var semver = require('semver'); var proxyServer = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy; function UpdateNotifier(options) { this.options = options = options || {}; if (!options.packageName || !options.packageVersion) { this.packageFile = require( path.resolve(path.dirname(module.parent.filename), options.packagePath || 'package')); } if (options.callback) { this.hasCallback = true; } this.packageName = options.packageName || this.packageFile.name; this.packageVersion = options.packageVersion || this.packageFile.version; this.updateCheckInterval = typeof options.updateCheckInterval === 'number' ? options.updateCheckInterval : 1000 * 60 * 60 * 24; // 1 day this.updateCheckTimeout = typeof options.updateCheckTimeout === 'number' ? options.updateCheckTimeout : 20000; // 20 secs this.registryUrl = options.registryUrl || 'http://registry.npmjs.org/%s'; this.callback = options.callback || function () { }; if (!this.hasCallback) { this.config = new Configstore('update-notifier-' + this.packageName, { optOut: false }); } } UpdateNotifier.prototype.check = function () { if (this.hasCallback) { return this.checkNpm(this.callback); } var cp; if (this.config.get('optOut')) { return; } this.update = this.config.get('update'); if (this.update) { this.config.del('update'); } // Only check for updates on a set interval if (new Date() - this.config.get('lastUpdateCheck') < this.updateCheckInterval) { return; } this.config.set('lastUpdateCheck', +new Date()); this.config.del('update'); // Set some needed options before forking // This is needed because we can't infer the packagePath in the fork this.options.packageName = this.packageName; this.options.packageVersion = this.packageVersion; // Fork, passing the options as an environment property cp = fork(__dirname + '/check.js', [JSON.stringify(this.options)]); cp.unref(); cp.disconnect(); }; UpdateNotifier.prototype.checkNpm = function (cb) { var url = util.format(this.registryUrl, this.packageName); request({url: url, json: true, timeout: this.updateCheckTimeout, proxy: proxyServer}, function (error, response, body) { var currentVersion, latestVersion; if (error) { return cb(error); } if (body.error) { return cb(new Error('Package not found')); } currentVersion = this.packageVersion; latestVersion = body['dist-tags'].latest cb(null, { latest: latestVersion, current: currentVersion, type: this.updateType(currentVersion, latestVersion), date: body.time[latestVersion], name: this.packageName }); }.bind(this)); }; UpdateNotifier.prototype.notify = function (customMessage) { var message = chalk.blue(' '\nUpdate available: ' + chalk.green.bold(this.update.latest) + chalk.gray(' (current: ' + this.update.current + ')') + '\nRun ' + chalk.magenta('npm update -g ' + this.packageName) + ' to update\n' + chalk.blue(' if (customMessage) { process.on('exit', function () { console.log(typeof customMessage === 'string' ? customMessage : message); }); } else { console.log(message); } }; UpdateNotifier.prototype.updateType = function (currentVersion, latestVersion) { // Check if the current version is greater or equal than the latest npm version // Invalid versions should be ignored if (!semver.valid(currentVersion) || semver.gte(currentVersion, latestVersion)) { return 'latest'; } // Otherwise there's an update currentVersion = currentVersion.split('.'); latestVersion = latestVersion.split('.'); if (latestVersion[0] > currentVersion[0]) { return 'major'; } else if (latestVersion[1] > currentVersion[1]) { return 'minor'; } else if (latestVersion[2] > currentVersion[2]) { return 'patch'; } }; module.exports = function (options) { var updateNotifier = new UpdateNotifier(options); updateNotifier.check(); return updateNotifier; }; module.exports.UpdateNotifier = UpdateNotifier;
using System; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Threading.Tasks; using LtiLibrary.NetCore.Common; using LtiLibrary.NetCore.Lti.v1; using LtiLibrary.NetCore.OAuth; namespace LtiLibrary.NetCore.Clients { <summary> Base class for LTI client helpers that make secured requests. </summary> public static class SecuredClient { <summary> Add a signed authorization header to the client request using the signatureMethod. </summary> <param name="client">May need BaseAddress value from this</param> <param name="request">The request object that will be sent</param> <param name="consumerKey">The OAuth consumer key.</param> <param name="consumerSecret">The OAuth consumer secret.</param> <param name="signatureMethod">The SignatureMethod used to sign the request.</param> <returns></returns> public static async Task SignRequest(HttpClient client, HttpRequestMessage request, string consumerKey, string consumerSecret, SignatureMethod signatureMethod) { if (client == null) { throw new <API key>(nameof(client)); } if (request == null) { throw new <API key>(nameof(request)); } string serviceUrl = request.RequestUri.OriginalString; if (!request.RequestUri.IsAbsoluteUri) { if (!string.IsNullOrWhiteSpace(client.BaseAddress.PathAndQuery) && client.BaseAddress.PathAndQuery != "/") { // This is trying to replicate the behavior of httpclient combining base address with a relative path - // if a path is in the base address, it MUST have a trailing slash, and the relative url must NOT, // so this simple combination should work serviceUrl = client.BaseAddress.AbsoluteUri + serviceUrl; } else { serviceUrl = new Uri(client.BaseAddress, serviceUrl).AbsoluteUri; } } var ltiRequest = new LtiRequest(LtiConstants.LtiO<API key>) { ConsumerKey = consumerKey, HttpMethod = request.Method.Method, Url = new Uri(serviceUrl) }; <API key> authorizationHeader; // Determine hashing algorithm HashAlgorithm sha; switch(signatureMethod) { default: //HmacSha1 sha = SHA1.Create(); break; case SignatureMethod.HmacSha256: ltiRequest.SignatureMethod = "HMAC-SHA256"; sha = SHA256.Create(); break; case SignatureMethod.HmacSha384: ltiRequest.SignatureMethod = "HMAC-SHA384"; sha = SHA384.Create(); break; case SignatureMethod.HmacSha512: ltiRequest.SignatureMethod = "HMAC-SHA512"; sha = SHA512.Create(); break; } // Create an Authorization header using the body hash using (sha) { var hash = sha.ComputeHash(await (request.Content ?? new StringContent(string.Empty)).<API key>().ConfigureAwait(false)); authorizationHeader = ltiRequest.<API key>(hash, consumerSecret); } // Attach the header to the client request request.Headers.Authorization = authorizationHeader; } } }
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import Typography from 'material-ui/Typography'; const styleSheet = () => ({ base: { display: 'flex', width: '100', alignItems: 'center', backgroundColor: 'transparent', color: 'inherit', }, text: { marginLeft: 8, }, }); const IconWithText = (props) => { const { classes, icon, text } = props; return ( <div className={classes.base} > {icon} <Typography className={classes.text} color="inherit" >{text}</Typography> </div> ); }; IconWithText.propTypes = { classes: PropTypes.object, icon: PropTypes.component, text: PropTypes.string, }; export default withStyles(styleSheet, { name: 'IconWithText' })(IconWithText);
#include <stdio.h> #include <dlpack/dlpack.h> DLManagedTensor given; void display(DLManagedTensor a) { puts("On C side:"); int i; int ndim = a.dl_tensor.ndim; printf("data = %p\n", a.dl_tensor.data); printf("ctx = (device_type = %d, device_id = %d)\n", (int) a.dl_tensor.ctx.device_type, (int) a.dl_tensor.ctx.device_id); printf("dtype = (code = %d, bits = %d, lanes = %d)\n", (int) a.dl_tensor.dtype.code, (int) a.dl_tensor.dtype.bits, (int) a.dl_tensor.dtype.lanes); printf("ndim = %d\n", (int) a.dl_tensor.ndim); printf("shape = ("); for (i = 0; i < ndim; ++i) { if (i != 0) { printf(", "); } printf("%d", (int) a.dl_tensor.shape[i]); } printf(")\n"); printf("strides = ("); for (i = 0; i < ndim; ++i) { if (i != 0) { printf(", "); } printf("%d", (int) a.dl_tensor.strides[i]); } printf(")\n"); } void Give(DLManagedTensor dl_managed_tensor) { display(dl_managed_tensor); given = dl_managed_tensor; } void Finalize() { given.deleter(&given); }
package com.cabinetms.notice.web; import com.cabinetms.client.MediaCommand; import com.cabinetms.common.Constants; import com.cabinetms.notice.entity.CabinetmsNotice; import com.cabinetms.notice.service.<API key>; import com.cabinetms.terminal.entity.CabinetmsTerminal; import com.cabinetms.terminal.service.<API key>; import com.thinkgem.jeesite.common.config.Global; import com.thinkgem.jeesite.common.persistence.Page; import com.thinkgem.jeesite.common.utils.StringUtils; import com.thinkgem.jeesite.common.web.BaseController; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.simp.<API key>; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; /** * Controller * * @author houyi * @version 2016-10-11 */ @Controller @RequestMapping(value = "${adminPath}/notice/cabinetmsNotice") public class <API key> extends BaseController { @Autowired private <API key> <API key>; @Autowired private <API key> terminalService; @Autowired private <API key> template; @ModelAttribute public CabinetmsNotice get(@RequestParam(required = false) String id) { CabinetmsNotice entity = null; if (StringUtils.isNotBlank(id)) { entity = <API key>.get(id); } if (entity == null) { entity = new CabinetmsNotice(); } return entity; } @RequiresPermissions("notice:cabinetmsNotice:view") @RequestMapping(value = {"list", ""}) public String list(CabinetmsNotice cabinetmsNotice, HttpServletRequest request, HttpServletResponse response, Model model) { Page<CabinetmsNotice> page = <API key>.findPage(new Page<CabinetmsNotice>(request, response), cabinetmsNotice); model.addAttribute("page", page); return "cabinetms/notice/cabinetmsNoticeList"; } @RequiresPermissions("notice:cabinetmsNotice:view") @RequestMapping(value = "form") public String form(CabinetmsNotice cabinetmsNotice, Model model) { model.addAttribute("cabinetmsNotice", cabinetmsNotice); return "cabinetms/notice/cabinetmsNoticeForm"; } @RequiresPermissions("notice:cabinetmsNotice:edit") @RequestMapping(value = "save") public String save(CabinetmsNotice cabinetmsNotice, Model model, RedirectAttributes redirectAttributes) { if (!beanValidator(model, cabinetmsNotice)) { return form(cabinetmsNotice, model); } if(cabinetmsNotice.getStatus() == null){ cabinetmsNotice.setStatus(Constants.<API key>); } <API key>.save(cabinetmsNotice); addMessage(redirectAttributes, ""); return "redirect:" + Global.getAdminPath() + "/notice/cabinetmsNotice/?repage"; } @RequiresPermissions("notice:cabinetmsNotice:edit") @RequestMapping(value = "delete") public String delete(CabinetmsNotice cabinetmsNotice, RedirectAttributes redirectAttributes) { <API key>.delete(cabinetmsNotice); addMessage(redirectAttributes, ""); return "redirect:" + Global.getAdminPath() + "/notice/cabinetmsNotice/?repage"; } @RequiresPermissions("notice:cabinetmsNotice:edit") @RequestMapping(value = {"<API key>"}) public String <API key>(HttpServletRequest request, HttpServletResponse response, Model model) { List<CabinetmsTerminal> terminalList = terminalService.<API key>(new CabinetmsTerminal()); model.addAttribute("terminalList", terminalList); model.addAttribute("type", "edit"); return "cabinetms/notice/terminalListForm"; } @RequiresPermissions("notice:cabinetmsNotice:edit") @RequestMapping(value = {"<API key>"}) public String <API key>(CabinetmsNotice cabinetmsNotice, HttpServletRequest request, HttpServletResponse response, Model model) { CabinetmsTerminal param = new CabinetmsTerminal(); param.setNotice(cabinetmsNotice); List<CabinetmsTerminal> terminalList = terminalService.findList(param); model.addAttribute("terminalList", terminalList); model.addAttribute("type", "view"); model.addAttribute("notice", cabinetmsNotice); return "cabinetms/notice/terminalListForm"; } /** * * * @param cabinetmsNotice * @param model * @return */ @RequiresPermissions("notice:cabinetmsNotice:edit") @RequestMapping(value = "publish") public String publish(CabinetmsNotice cabinetmsNotice, Model model, RedirectAttributes redirectAttributes) { <API key>.publish(cabinetmsNotice, template); addMessage(redirectAttributes, ""); return "redirect:" + Global.getAdminPath() + "/notice/cabinetmsNotice/?repage"; } /** * * * @param cabinetmsNotice * @param model * @param redirectAttributes * @return */ @RequiresPermissions("notice:cabinetmsNotice:edit") @RequestMapping(value = "undoPublish") public String undoPublish(CabinetmsNotice cabinetmsNotice, Model model, RedirectAttributes redirectAttributes) { <API key>.undoPublish(cabinetmsNotice, template); addMessage(redirectAttributes, ""); return "redirect:" + Global.getAdminPath() + "/notice/cabinetmsNotice/?repage"; } }
package com.cognizant.cognizantits.qcconnection.qcupdation; import com4j.Com4jObject; import com4j.DISPID; import com4j.GUID; import com4j.IID; import com4j.NativeType; import com4j.ReturnValue; import com4j.VTID; @IID("{<API key>}") public abstract interface IFactoryProvider extends Com4jObject { @DISPID(24) @VTID(7) @ReturnValue(type=NativeType.Dispatch) public abstract Com4jObject getFactory(GUID paramGUID); }
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="popup.css"/> </head> <body style="min-width:300px"> INSTRUCTIONS: <br> - To set preferences, right click on this icon, and select "options". <br> - To scan an element in the DOM manually, right click on the element and select "scan this element" </body> </html>
{{template "layout/head.html" .}} {{template "layout/top.html" .}} <div class="clearfix" style="height:40px;"></div> <div class="main-sm"> <h1></h1> <h3></h3> <div id="error-span"></div> <div class="clearfix" style="height:10px;"></div> <div class="green-box" style="width:400px;"> <div class="well-lg"> <form id="loginForm" class="form-horizontal validate" method="post" role="form"> <input type="hidden" name="originURL" value="{{.originURL}}"/> <div class="form-group"> <div class="col-xs-11"> <label class="control-label"></label> <input type="text" class="form-control" id="userName" name="userName" placeholder="" required="*" validateChar="true"> </div> <div class="col-xs-1"> <br/> <span class="error"></span> </div> </div> <div class="form-group"> <div class="col-xs-11"> <label class="control-label"> </label> <input type="password" class="form-control" name="loginPwd" placeholder="" required="*" onkeypress="javascript:autoSubmit(event);"> </div> <div class="col-xs-1"> <br/> <span class="error"></span> </div> </div> <div class="form-group"> <div class="col-xs-11"> <button type="button" class="btn btn-primary btn-lg" style="width:100%" onclick="login();"> </button> </div> </div> <div class="form-group"> <div class="col-xs-11"> <a href="user/findPassword" target="_blank" tabindex="7"></a> &nbsp; &nbsp; &nbsp; <! <a href="user/register" tabindex="6"></a> </div> </div> </form> </div> </div> </div> {{template "layout/scripts.html" .}} <script type="text/javascript"> $(document).ready(function(){ $("#userName").focus(); }); function login(){ var form = $("#loginForm"); var validator = $(form).validate({meta:"validate"}); if(validator.form()){ $(form).goAjax({ semantic: false, url: 'user/login', data:{}, success: function(jsonData) { if(true == jsonData.success){ window.location.href = jsonData.message; } else { $("#error-span").alert({type: "alert-danger", text: jsonData.message}); } } }); } } function autoSubmit(event){ if(event.keyCode==13){ login(); } } </script> {{template "layout/foot.html" .}}
var styleImpassable = new ol.style.Style({ text: new ol.style.Text({ font: '12px Calibri,sans-serif', fill: new ol.style.Fill({color: "#000000"}), stroke: new ol.style.Stroke({color: "#ffff00", width: 2}) }), image: new ol.style.Icon({ scale: 1, anchor: [0.5, 0.5], anchorXUnits: 'fraction', anchorYUnits: 'fraction', opacity: 1, src: 'http://h-crisis.niph.go.jp/assistant/wp-content/uploads/sites/4/test/img/X.png' }) }); var urlP = 'http://h-crisis.niph.go.jp/assistant/wp-content/uploads/data/road_info/latest/road_info.geojson'; // urlCustomRoadevent.js //var urlCustomRoad = '../practice/geojson/custom_road_info.geojson' var ImpassableLayer = new ol.layer.Vector({ source: new ol.source.Vector({ url: urlP, format: new ol.format.GeoJSON() }), style: function(feature) { styleImpassable.getText().setText(feature.get('name') + ":" + feature.get('') + "(:" +feature.get('') + ")"); return styleImpassable; } }); var ImpassableLayerAdd = new ol.layer.Vector({ source: new ol.source.Vector({ url: urlCustomRoad, format: new ol.format.GeoJSON() }), style: function(feature) { styleImpassable.getText().setText(feature.get('name') + ":" + feature.get('') + "(:" +feature.get('') + ")"); return styleImpassable; } }); function visPassButton() { if (ImpassableLayer.getVisible()) { ImpassableLayer.setVisible(false); ImpassableLayerAdd.setVisible(false); this.style.backgroundColor = ""; this.style.color = ""; } else { ImpassableLayer.setVisible(true); ImpassableLayerAdd.setVisible(true); this.style.backgroundColor = "#eeeeee"; this.style.color = "#000000"; } }; function createHtmlPass() { document.getElementById('info').innerHTML = ""; DetailHtml = ""; if (window.innerWidth >= 780) { HeaderHtml = "<div style='border-radius:10px; margin:0 0 5px; font-family:helvetica; background-color:#333333; color:white; text-align:center; opacity: 1; width:350px' type=button id=showBtn value= onclick=showHide() onmousemove='this.style.opacity=0.8' onmouseout='this.style.opacity=1'></div>"; } else if (window.innerWidth >= 480) { HeaderHtml = "<div style='border-radius:10px; margin:0 0 5px; font-family:helvetica; background-color:#333333; color:white; text-align:center; opacity: 1; width:220px' type=button id=showBtn value= onclick=showHide() onmousemove='this.style.opacity=0.8' onmouseout='this.style.opacity=1'></div>"; } else { HeaderHtml = "<div style='border-radius:10px; margin:0 0 5px; font-family:helvetica; background-color:#333333; color:white; text-align:center; opacity: 1; width:220px' type=button id=showBtn value= onclick=showHide() onmousemove='this.style.opacity=0.8' onmouseout='this.style.opacity=1'></div>"; } if (arrayV[0] === null) { } else { HeaderHtml = HeaderHtml + "<a style='font-family: Helvetica'>" + arrayV[0] + "</a>"; } for (i = 0; i < arrayL.length; i++) { DetailHtml = DetailHtml + preCells + arrayL[i] + interCells + arrayV[i] + subCells; } document.getElementById('infoHeader').style.display = 'block'; document.getElementById('infoHeader').innerHTML = HeaderHtml; document.getElementById('info').style.display = 'block'; document.getElementById('info').innerHTML = DetailHtml; }
Function deployment based on https://github.com/Azure-Samples/<API key> ## How to deploy bash ../../../gradlew <API key>
package main import ( "encoding/json" "flag" "fmt" "gopkg.in/mgo.v2/bson" "os" "path/filepath" "strings" "time" "github.com/apache/thrift/lib/go/thrift" "github.com/go-kit/kit/log" thriftclient "github.com/banerwai/micros/command/contact/client/thrift" "github.com/banerwai/micros/command/contact/service" thriftcontact "github.com/banerwai/micros/command/contact/thrift/gen-go/contact" "github.com/banerwai/global/bean" banerwaicrypto "github.com/banerwai/gommon/crypto" bstrings "github.com/banerwai/gommon/strings" ) func main() { var ( thriftAddr = flag.String("thrift.addr", "localhost:36090", "Address for Thrift server") thriftProtocol = flag.String("thrift.protocol", "binary", "binary, compact, json, simplejson") thriftBufferSize = flag.Int("thrift.buffer.size", 0, "0 for unbuffered") thriftFramed = flag.Bool("thrift.framed", false, "true to enable framing") ) flag.Parse() if len(os.Args) < 2 { fmt.Fprintf(os.Stderr, "\n%s [flags] method arg1 arg2\n\n", filepath.Base(os.Args[0])) flag.Usage() os.Exit(1) } _instances := strings.Split(*thriftAddr, ",") <API key> := banerwaicrypto.GetRandomItNum(len(_instances)) method, _contactID := flag.Arg(0), flag.Arg(1) var logger log.Logger logger = log.NewLogfmtLogger(os.Stdout) logger = log.NewContext(logger).With("caller", log.DefaultCaller) var svc service.ContactService var protocolFactory thrift.TProtocolFactory switch *thriftProtocol { case "compact": protocolFactory = thrift.<API key>() case "simplejson": protocolFactory = thrift.<API key>() case "json": protocolFactory = thrift.<API key>() case "binary", "": protocolFactory = thrift.<API key>() default: logger.Log("protocol", *thriftProtocol, "err", "invalid protocol") os.Exit(1) } var transportFactory thrift.TTransportFactory if *thriftBufferSize > 0 { transportFactory = thrift.<API key>(*thriftBufferSize) } else { transportFactory = thrift.<API key>() } if *thriftFramed { transportFactory = thrift.<API key>(transportFactory) } transportSocket, err := thrift.NewTSocket(_instances[<API key>]) if err != nil { logger.Log("during", "thrift.NewTSocket", "err", err) os.Exit(1) } trans := transportFactory.GetTransport(transportSocket) defer trans.Close() if err := trans.Open(); err != nil { logger.Log("during", "thrift transport.Open", "err", err) os.Exit(1) } cli := thriftcontact.<API key>(trans, protocolFactory) svc = thriftclient.New(cli, logger) begin := time.Now() switch method { case "ping": v := svc.Ping() logger.Log("method", "Ping", "v", v, "took", time.Since(begin)) // case "prepare": // _tpl := prepareContactTpl() // _mmap := prepareContactParam() // b, _ := json.Marshal(_mmap) // fmt.Println(string(b)) // _contact := bstrings.ParseTpl("default", _tpl, _mmap) // fmt.Println(_contact) case "create": var _obj bean.Contact _obj.ID = bson.NewObjectId() _obj.ClientEmail = "ministor@gmail.com" _obj.FreeLancerEmail = "ministor@126.com" _tpl := prepareContactTpl() _mmap := prepareContactParam() _bParam, _ := json.Marshal(_mmap) // _content := bstrings.ParseTpl("default", _tpl, _mmap) // _obj.ContactContent = _content _obj.ContactTpl = _tpl _obj.TplParam = string(_bParam) b, _ := json.Marshal(_obj) v := svc.CreateContact(string(b)) logger.Log("method", "CreateContact", "v", v, "took", time.Since(begin)) case "csign": v := svc.ClientSignContact(_contactID, true) logger.Log("method", "ClientSignContact", "v", v, "took", time.Since(begin)) case "fsign": v := svc.<API key>(_contactID, true) logger.Log("method", "<API key>", "v", v, "took", time.Since(begin)) case "deal": v := svc.DealContact(_contactID, true) logger.Log("method", "DealContact", "v", v, "took", time.Since(begin)) case "update": _mapUpdate := make(map[string]string) _tpl := prepareContactTpl() _mmap := updateContactParam() _bParam, _ := json.Marshal(_mmap) _content := bstrings.ParseTpl("default", _tpl, _mmap) _mapUpdate["contact_content"] = _content _mapUpdate["contact_tpl"] = _tpl _mapUpdate["tpl_param"] = string(_bParam) v := svc.UpdateContact(_contactID, _mapUpdate) logger.Log("method", "UpdateContact", "v", v, "took", time.Since(begin)) default: logger.Log("err", "invalid method "+method) os.Exit(1) } } func prepareContactTpl() string { _tpl := `:{{.ContactNumber}} # {{.ProjectName}} ** : {{.ClientName}}** ** : {{.FreeLancerName}}** **{{.ExpectedTime}}** ** : {{.PayRate}}** ** : {{.PaymentMethod}}** ` return _tpl } func prepareContactParam() map[string]string { _map := make(map[string]string) _map["ContactNumber"] = bson.NewObjectId().Hex() _map["ProjectName"] = "banerwai" _map["ClientName"] = "ministor@gmail.com" _map["FreeLancerName"] = "ministor@126.com" _map["ExpectedTime"] = "4weeks" _map["PayRate"] = "150Y / hour" _map["PaymentMethod"] = "week" return _map } func updateContactParam() map[string]string { _map := make(map[string]string) _map["ContactNumber"] = bson.NewObjectId().Hex() _map["ProjectName"] = "banerwai" _map["ClientName"] = "ministor@gmail.com" _map["FreeLancerName"] = "ministor@126.com" _map["ExpectedTime"] = "8weeks" _map["PayRate"] = "200Y / hour" _map["PaymentMethod"] = "day" return _map }
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import urlparse from scrapy import log from scrapy.http import Request from base.base_wolf import Base_Wolf class Wolf(Base_Wolf): def __init__(self, *args, **kwargs): super(Wolf, self).__init__(*args, **kwargs) self.name = 'henbt' self.seed_urls = [ 'http://henbt.com/', ] self.base_url = 'http://henbt.com/' self.rule['follow'] = re.compile(r'show-')
package org.aja.tej.examples.spark.rdd.dataOrganization.partitioner import org.aja.tej.utils.TejUtils import org.apache.spark.{HashPartitioner, SparkContext} /* RDD is distributed this means it is split on some number of parts. Each of this partitions is potentially on different machine. Hash partitioner with arument numPartitions choses on what partition to place pair (key, value) in following way: 1. Creates exactly numPartitions partitions. 2. Places (key, value) in partition with number Hash(key) % numPartition */ object <API key> extends App { def useCases(sc: SparkContext): Unit = { println(this.getClass.getSimpleName) //<API key>$ val rddData = sc.parallelize(for { x <- 1 to 3 y <- 1 to 2 } yield (x, None), 8) //(key, value) with 8 partitions println("rddData partitons: " + rddData.partitions.length) //rdd partitons: 8 println("rddData contents: " + rddData.collect.foreach(print)) // (1,None)(1,None)(2,None)(2,None)(3,None)(3,None) println("rddData partitioner: " + rddData.partitioner) //rddData partitioner: None //mapPartitions U -> T of iterator val <API key> = rddData.mapPartitions(iter => Iterator(iter.length)) println("<API key> : " + <API key>.collect().foreach(print)) //0 1 1 1 0 1 1 1 //so 2 of 8 partition is empty println(" val <API key> = rddData.partitionBy(new HashPartitioner(1)) println("<API key> partitons: " + <API key>.partitions.length) //<API key> partitons: 1 println("<API key> contents: " + <API key>.collect.foreach(print)) //(1,None)(1,None)(2,None)(2,None)(3,None)(3,None)<API key> conten //Since we have only one partition it contains all elements println("<API key> : " + <API key>.mapPartitions(iter => Iterator(iter.length)).collect().foreach(println)) println(" val <API key> = rddData.partitionBy(new HashPartitioner(2)) println("<API key> partitons: " + <API key>.partitions.length) //<API key> partitons: 2 println("<API key> contents: " + <API key>.collect.foreach(print)) //(2,None)(2,None)(1,None)(1,None)(3,None)(3,None) /i.e partitionBy -> ShuffleRDD -> partition for current element is selected by (k.hashcode % numPartition) println("<API key> : " + <API key>.mapPartitions(iter => Iterator(iter.length)).collect().foreach(println)) //2 4 //Since rdd is partitioned by key data won't be distributed uniformly anymore: //Lets see why? //Because with have three keys and only two different values of hashCode mod numPartitions(2) there is nothing unexpected println("(1 to 3).map((k: Int) => (k, k.hashCode, k.hashCode % 2)) : " + (1 to 3).map((k: Int) => (k, k.hashCode, k.hashCode % 2))) //Vector((1,1,1), (2,2,0), (3,3,1)) //Lets confirm in our rdd println("Keys in each partition" + <API key>.mapPartitions(iter => Iterator(iter.map(_._1).toSet)).collect.foreach(println)) //Set(2) //Set(1,3) println(" val <API key> = rddData.partitionBy(new HashPartitioner(10)) println("<API key> partitons: " + <API key>.partitions.length) //<API key> partitons: 10 println("<API key> contents: " + <API key>.collect.foreach(print)) //(1,None)(1,None)(2,None)(2,None)(3,None)(3,None) /i.e partitionBy -> ShuffleRDD -> partition for current element is selected by (k.hashcode % numPartition) println("<API key> : " + <API key>.mapPartitions(iter => Iterator(iter.length)).collect().foreach(println)) //0 2 2 2 0 0 0 0 0 0 println("(1 to 3).map((k: Int) => (k, k.hashCode, k.hashCode % 10)) : " + (1 to 10).map((k: Int) => (k, k.hashCode, k.hashCode % 10))) // Vector((1,1,1), (2,2,2), (3,3,3), (4,4,4), (5,5,5), (6,6,6), (7,7,7), (8,8,8), (9,9,9), (10,10,0)) //Lets confirm in our rdd println("Keys in each partition" + <API key>.mapPartitions(iter => Iterator(iter.map(_._1).toSet)).collect.foreach(println)) //Set() //Set(1) //Set(2) //Set(3) //Set() //Set() //Set() //Set() //Set() //Set() } useCases(TejUtils.getSparkContext(this.getClass.getSimpleName)) }
package com.github.flyinghe.tools; import java.io.Serializable; import java.util.List; public class PageBean<T> implements Serializable { private static final long serialVersionUID = 1L; private Integer pageCode; private Integer pageRecord; private Long totalRecord; private Integer indexNo;//5 1 2 3 ... 4 5 private Integer begin;// ,: 1 2 3 ... 4 5 () private Integer end; private List<T> beanList = null; /** * @param pageCode * @param pageRecord * @param totalRecord * @param indexNo */ public PageBean(Integer pageCode, Integer pageRecord, Long totalRecord, Integer indexNo) { this.pageCode = pageCode; this.pageRecord = pageRecord; this.totalRecord = totalRecord; this.indexNo = indexNo; } /** * @param pageCode * @param pageRecord * @param indexNo * @param totalRecord * @param beanList */ public PageBean(Integer pageCode, Integer pageRecord, Integer indexNo, Long totalRecord, List<T> beanList) { super(); this.pageCode = pageCode; this.pageRecord = pageRecord; this.indexNo = indexNo; this.totalRecord = totalRecord; this.beanList = beanList; } /** * * * @return */ public Integer getPageCode() { return pageCode; } /** * * * @param pageCode */ public void setPageCode(Integer pageCode) { this.pageCode = pageCode; } /** * * * @return */ public Integer getPageRecord() { return pageRecord; } /** * * * @param pageRecord */ public void setPageRecord(Integer pageRecord) { this.pageRecord = pageRecord; } /** * * * @return */ public Long getTotalRecord() { return totalRecord; } /** * * * @param totalRecord */ public void setTotalRecord(Long totalRecord) { this.totalRecord = totalRecord; } /** * * * @return */ public Integer getIndexNo() { return indexNo; } /** * * * @param indexNo */ public void setIndexNo(Integer indexNo) { this.indexNo = indexNo; } /** * * * @return */ public Integer getBegin() { this.setBeginAndEnd(); return begin; } /** * * * @return */ public Integer getEnd() { this.setBeginAndEnd(); return end; } /** * * * @return */ public Integer getTotalPage() { Number i = this.totalRecord / this.pageRecord; return this.totalRecord % this.pageRecord == 0 ? i.intValue() : i.intValue() + 1; } /** * * * @return */ public List<T> getBeanList() { return beanList; } /** * * * @param beanList */ public void setBeanList(List<T> beanList) { this.beanList = beanList; } private void setBeginAndEnd() { Integer totalPage = this.getTotalPage(); if (totalPage <= this.indexNo) { this.begin = 1; this.end = totalPage; return; } int minus = this.indexNo / 2; int add = this.indexNo % 2 == 0 ? minus - 1 : minus; if (this.pageCode - minus < 1) { this.begin = 1; this.end = this.indexNo; return; } if (this.pageCode + add > totalPage) { this.begin = totalPage - (this.indexNo - 1); this.end = totalPage; return; } this.begin = this.pageCode - minus; this.end = this.pageCode + add; } }
// Code generated by go-bindata. // sources: // config/config.go // config/local.local // DO NOT EDIT! package config import ( "bytes" "compress/gzip" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "time" ) func bindataRead(data []byte, name string) ([]byte, error) { gz, err := gzip.NewReader(bytes.NewBuffer(data)) if err != nil { return nil, fmt.Errorf("Read %q: %v", name, err) } var buf bytes.Buffer _, err = io.Copy(&buf, gz) clErr := gz.Close() if err != nil { return nil, fmt.Errorf("Read %q: %v", name, err) } if clErr != nil { return nil, err } return buf.Bytes(), nil } type asset struct { bytes []byte info os.FileInfo } type bindataFileInfo struct { name string size int64 mode os.FileMode modTime time.Time } func (fi bindataFileInfo) Name() string { return fi.name } func (fi bindataFileInfo) Size() int64 { return fi.size } func (fi bindataFileInfo) Mode() os.FileMode { return fi.mode } func (fi bindataFileInfo) ModTime() time.Time { return fi.modTime } func (fi bindataFileInfo) IsDir() bool { return false } func (fi bindataFileInfo) Sys() interface{} { return nil } var _configConfigGo = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\x01\x00\x00\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00") func configConfigGoBytes() ([]byte, error) { return bindataRead( _configConfigGo, "config/config.go", ) } func configConfigGo() (*asset, error) { bytes, err := configConfigGoBytes() if err != nil { return nil, err } info := bindataFileInfo{name: "config/config.go", size: 0, mode: os.FileMode(420), modTime: time.Unix(1583878393, 0)} a := &asset{bytes: bytes, info: info} return a, nil } var _configLocalLocal = []byte("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xaa\xae\xe5\x02\x04\x00\x00\xff\xff\x06\xb0\xa1\xdd\x03\x00\x00\x00") func <API key>() ([]byte, error) { return bindataRead( _configLocalLocal, "config/local.local", ) } func configLocalLocal() (*asset, error) { bytes, err := <API key>() if err != nil { return nil, err } info := bindataFileInfo{name: "config/local.local", size: 3, mode: os.FileMode(420), modTime: time.Unix(1570028531, 0)} a := &asset{bytes: bytes, info: info} return a, nil } // Asset loads and returns the asset for the given name. // It returns an error if the asset could not be found or // could not be loaded. func Asset(name string) ([]byte, error) { cannonicalName := strings.Replace(name, "\\", "/", -1) if f, ok := _bindata[cannonicalName]; ok { a, err := f() if err != nil { return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err) } return a.bytes, nil } return nil, fmt.Errorf("Asset %s not found", name) } // MustAsset is like Asset but panics when Asset would return an error. // It simplifies safe initialization of global variables. func MustAsset(name string) []byte { a, err := Asset(name) if err != nil { panic("asset: Asset(" + name + "): " + err.Error()) } return a } // AssetInfo loads and returns the asset info for the given name. // It returns an error if the asset could not be found or // could not be loaded. func AssetInfo(name string) (os.FileInfo, error) { cannonicalName := strings.Replace(name, "\\", "/", -1) if f, ok := _bindata[cannonicalName]; ok { a, err := f() if err != nil { return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err) } return a.info, nil } return nil, fmt.Errorf("AssetInfo %s not found", name) } // AssetNames returns the names of the assets. func AssetNames() []string { names := make([]string, 0, len(_bindata)) for name := range _bindata { names = append(names, name) } return names } // _bindata is a table, holding each asset generator, mapped to its name. var _bindata = map[string]func() (*asset, error){ "config/config.go": configConfigGo, "config/local.local": configLocalLocal, } // AssetDir returns the file names below a certain // directory embedded in the file by go-bindata. // For example if you run go-bindata on data/... and data contains the // following hierarchy: // data/ // foo.txt // img/ // a.png // b.png // then AssetDir("data") would return []string{"foo.txt", "img"} // AssetDir("data/img") would return []string{"a.png", "b.png"} // AssetDir("foo.txt") and AssetDir("notexist") would return an error // AssetDir("") will return []string{"data"}. func AssetDir(name string) ([]string, error) { node := _bintree if len(name) != 0 { cannonicalName := strings.Replace(name, "\\", "/", -1) pathList := strings.Split(cannonicalName, "/") for _, p := range pathList { node = node.Children[p] if node == nil { return nil, fmt.Errorf("Asset %s not found", name) } } } if node.Func != nil { return nil, fmt.Errorf("Asset %s not found", name) } rv := make([]string, 0, len(node.Children)) for childName := range node.Children { rv = append(rv, childName) } return rv, nil } type bintree struct { Func func() (*asset, error) Children map[string]*bintree } var _bintree = &bintree{nil, map[string]*bintree{ "config": {nil, map[string]*bintree{ "config.go": {configConfigGo, map[string]*bintree{}}, "local.local": {configLocalLocal, map[string]*bintree{}}, }}, }} // RestoreAsset restores an asset under the given directory func RestoreAsset(dir, name string) error { data, err := Asset(name) if err != nil { return err } info, err := AssetInfo(name) if err != nil { return err } err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755)) if err != nil { return err } err = ioutil.WriteFile(_filePath(dir, name), data, info.Mode()) if err != nil { return err } err = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime()) if err != nil { return err } return nil } // RestoreAssets restores an asset under the given directory recursively func RestoreAssets(dir, name string) error { children, err := AssetDir(name) // File if err != nil { return RestoreAsset(dir, name) } // Dir for _, child := range children { err = RestoreAssets(dir, filepath.Join(name, child)) if err != nil { return err } } return nil } func _filePath(dir, name string) string { cannonicalName := strings.Replace(name, "\\", "/", -1) return filepath.Join(append([]string{dir}, strings.Split(cannonicalName, "/")...)...) }
<!DOCTYPE html> <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header <API key>" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo <API key>"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="<API key>">OpenClover</span></a> </h1> </div> <div class="<API key>"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="<API key>"> <div class="aui-page-panel-nav <API key>"> <div class="<API key>" style="margin-bottom: 20px;"> <div class="<API key>"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="<API key>" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup <API key>"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading <API key>"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui <API key>"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="<API key> hidden"> <small>No results found.</small> </p> <div class="<API key>" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="<API key>"></div> <div class="<API key>"></div> </div> </div> </div> </nav> </div> <section class="<API key>"> <div class="<API key>"> <div class="<API key>"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="<API key>.html">Class <API key></a></li> </ol></div> <h1 class="aui-h2-clover"> Test <API key> </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/<API key>.html?line=31384#src-31384" ><API key></a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:35:34 </td> <td> 0.001 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> <API key></th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=9449#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="<API key>" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="<API key>" --> </div> <!-- class="<API key>" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
## Minio/ ( / ) ||| |: ||16| ||4| ||N / 2| ||N / 2+1 | ||| |: |Web| 5GB| Limits of S3 API ||| |: ||| ||| || 5 TB | || 0 B | |PUT| 5 GB | |Part| 10,000| |Part |5MB5GB. part0B5GB| |list partspart| 1000| |list objectsobject| 1000| |list multipart uploadsmultipart uploads| 1000| AWS S3APIminio[github](https://github.com/minio/minio/issues)issue MinioAmazon S3 Bucket API - BucketACL ( [bucket policies](https://docs.min.io/docs/<API key>#policy)) - BucketCORS (HTTPCORS) - BucketLifecycle (Minio) - BucketReplication ( [`mc mirror`](https://docs.min.io/docs/<API key>#mirror)) - BucketVersions, BucketVersioning ( [`s3git`](https://github.com/s3git/s3git)) - BucketWebsite ( [`caddy`](https: - BucketAnalytics, BucketMetrics, BucketLogging ( [bucket notification](https://docs.min.io/docs/<API key>#events) APIs) - <API key> - BucketTagging MinioAmazon S3 Object API. - ObjectACL ( [bucket policies](https://docs.min.io/docs/<API key>#policy)) - ObjectTorrent
package io.quarkus.smallrye.jwt.runtime.auth; import java.util.function.Consumer; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.eclipse.microprofile.jwt.JsonWebToken; import org.jboss.logging.Logger; import io.quarkus.security.<API key>; import io.quarkus.security.identity.<API key>; import io.quarkus.security.identity.IdentityProvider; import io.quarkus.security.identity.SecurityIdentity; import io.quarkus.security.identity.request.<API key>; import io.quarkus.security.runtime.<API key>; import io.quarkus.vertx.http.runtime.security.HttpSecurityUtils; import io.smallrye.jwt.auth.principal.JWTParser; import io.smallrye.jwt.auth.principal.ParseException; import io.smallrye.mutiny.Uni; import io.smallrye.mutiny.subscription.UniEmitter; import io.vertx.ext.web.RoutingContext; /** * Validates a bearer token according to the MP-JWT rules */ @ApplicationScoped public class MpJwtValidator implements IdentityProvider<<API key>> { private static final Logger log = Logger.getLogger(MpJwtValidator.class); final JWTParser parser; final boolean <API key>; public MpJwtValidator() { this.parser = null; this.<API key> = false; } @Inject public MpJwtValidator(JWTParser parser, SmallRyeJwtConfig config) { this.parser = parser; this.<API key> = config == null ? false : config.<API key>; } @Override public Class<<API key>> getRequestType() { return <API key>.class; } @Override public Uni<SecurityIdentity> authenticate(<API key> request, <API key> context) { if (!(request.getToken() instanceof <API key>)) { return Uni.createFrom().nullItem(); } if (!<API key>) { return Uni.createFrom().emitter(new Consumer<UniEmitter<? super SecurityIdentity>>() { @Override public void accept(UniEmitter<? super SecurityIdentity> uniEmitter) { try { uniEmitter.complete(<API key>(request)); } catch (<API key> e) { uniEmitter.fail(e); } } }); } else { return context.runBlocking(() -> <API key>(request)); } } private SecurityIdentity <API key>(<API key> request) { try { JsonWebToken jwtPrincipal = parser.parse(request.getToken().getToken()); <API key>.Builder builder = <API key>.builder().setPrincipal(jwtPrincipal) .addCredential(request.getToken()) .addRoles(jwtPrincipal.getGroups()) .addAttribute(SecurityIdentity.USER_ATTRIBUTE, jwtPrincipal); RoutingContext routingContext = HttpSecurityUtils.<API key>(request); if (routingContext != null) { builder.addAttribute(RoutingContext.class.getName(), routingContext); } return builder.build(); } catch (ParseException e) { log.debug("Authentication failed", e); throw new <API key>(e); } } }
package io.quarkus.spring.security.runtime.interceptor.check; import java.lang.reflect.Method; import io.quarkus.arc.Arc; import io.quarkus.security.ForbiddenException; import io.quarkus.security.<API key>; import io.quarkus.security.identity.SecurityIdentity; import io.quarkus.security.spi.runtime.MethodDescription; import io.quarkus.security.spi.runtime.SecurityCheck; import io.quarkus.spring.security.runtime.interceptor.accessor.<API key>; /** * Instances of this classes are created in order to check if the value of property of method parameter * inside a Spring Security expression matches the principal name * * Access to the property of the object is performed by delegating to a purpose generated * accessor */ public class <API key> implements SecurityCheck { private final int index; private final Class<?> <API key>; private final Class<? extends <API key>> <API key>; private final String propertyName; private <API key>(int index, String <API key>, String <API key>, String propertyName) throws <API key> { this.index = index; this.<API key> = Class.forName(<API key>, false, Thread.currentThread().<API key>()); this.<API key> = (Class<? extends <API key>>) Class.forName(<API key>, false, Thread.currentThread().<API key>()); this.propertyName = propertyName; } public static <API key> of(int index, String <API key>, String <API key>, String propertyName) { try { return new <API key>(index, <API key>, <API key>, propertyName); } catch (<API key> e) { throw new RuntimeException(e); } } @Override public void apply(SecurityIdentity identity, Method method, Object[] parameters) { doApply(identity, parameters, method.getDeclaringClass().getName(), method.getName()); } @Override public void apply(SecurityIdentity identity, MethodDescription methodDescription, Object[] parameters) { doApply(identity, parameters, methodDescription.getClassName(), methodDescription.getMethodName()); } private void doApply(SecurityIdentity identity, Object[] parameters, String className, String methodName) { if (index > parameters.length - 1) { throw <API key>(className, methodName); } Object parameterValue = parameters[index]; if (!<API key>.equals(parameterValue.getClass())) { throw <API key>(className, methodName); } String parameterValueStr = getStringValue(parameterValue); if (identity.isAnonymous()) { throw new <API key>(); } String name = identity.getPrincipal().getName(); if (!name.equals(parameterValueStr)) { throw new ForbiddenException(); } } private String getStringValue(Object parameterValue) { return Arc.container().instance(<API key>).get().access(parameterValue, propertyName); } private <API key> <API key>(String className, String methodName) { return new <API key>( "<API key> with index " + index + " cannot be applied to '" + className + "#" + methodName + "'"); } }
import template from './footer.html'; import controller from './footer.controller'; import './footer.styl'; let footerComponent = { restrict: 'E', bindings: {}, template, controller, controllerAs: 'vm' }; export default footerComponent;