language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
3,461
2.546875
3
[]
no_license
--- layout: post title: "2/12" date: 2021-02-12 02:39:38 -0700 categories: Procedural Content Generation Independent Study --- Constructive Generation Dungeon generation typically has 3 elements: A representational model which abstracts the dungeon's structure, a method of constructing that model, and a method of creating the actual geometry of the dungeon from that model. Dungeons and platformers both have free space, walls, treasures, enemies, and traps. Constructive generation, while faster than the search based methods of the prior chapter, but as a cost give less control to the creator. Space Partitioning, a method of subdividing portions of levels into sectionals called cells. This is often done hierarchically to form different levels of cells. One method of this is binary space partiitioning BSP which recursively divides space. This is expaned upon to quadtrees for 2d and octrees for 3d. The entire dungeon is represented by the root node, and then each branch subdivides this. The subdivisions are checked if they meet the idealized size, and if not are further subdivided. Once reaching the idealized size, a room is generated stochastically within that plot, which will then have hallways connecting to at least one adjacent cell. Agent Based Dungeon Growing, more organic and chaotic, a creation as needed sort of approach. Often called digger agents, as they create tunnels which define the dungeon. Upon generating a room or turning the tunneler agent, the chance of doing so is reset, and will grow by a degree until it does so again. More advanced diggers can look ahead in order to avoid intersection, however that's not always desired, as intersection can create more chaotic and interesting dungeons. Because of the innate chaos of the agent based approach, tuning can require many tests in order to receive the desired results. Cellular Automata, consists of an n dimensional grid, a set of states and transition rules. Often demonstrated as a vector or a 2d matrix. Each cell looks to its neighbors in order to determin its state. Everytime a room is exited, a new room is generated. This uses four parameters, a percentage of inaccessible areas, a number of cellular automata generations, a neighberhood trheshhold value, and the number of cells in one neighborhood. Whenever a room is generated, its immediate neighboors are also generated in order to have proper connections between them. Grammar based dungeon generation, uses the rules of a graph grammar to generate a graph that describes a level's topology. This is a high level topological representation and can be controlled through parameters including dificulty, fun, and global size. advanced platform generation methods Rhythm based generation, which links to the timing and repetition of user actions. This generation is reflective of the current user. ORE based Chunk aproach takes pregenerated regions and sews them together as the player moves through the level. Post generation then places things like powerups. This is very designer oriented, and if taken too far strays away from procedural generation into manual construction. LAB level generator for infinitux, a freeware 2d platforming game. The software to be used comes from https://sites.google.com/site/platformersai/platformer-ai-competition [jekyll-docs]: https://jekyllrb.com/docs/home [jekyll-gh]: https://github.com/jekyll/jekyll [jekyll-talk]: https://talk.jekyllrb.com/ 
Java
UTF-8
19,656
1.515625
2
[]
no_license
package handlers; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.context.MessageSource; import com.google.common.base.Splitter; import com.integration.DefaultPricePlan; import com.tools.SMPPConnector; import connexions.AIRRequest; import dao.DAO; import dao.queries.JdbcSubscriberDao; import dao.queries.JdbcUSSDRequestDao; import dao.queries.JdbcUSSDServiceDao; import domain.models.Subscriber; import domain.models.USSDRequest; import domain.models.USSDService; import exceptions.AirAvailabilityException; import filter.MSISDNValidator; import product.FaFManagement; import product.PricePlanCurrent; import product.PricePlanCurrentActions; import product.ProductProperties; import product.USSDMenu; import util.AccountDetails; import util.FafInformation; public class InputHandler { public InputHandler() { } public void handle(MessageSource i18n, ProductProperties productProperties, Map<String, String> parameters, Map<String, Object> modele, HttpServletRequest request, DAO dao) { USSDRequest ussd = null; int language = 1; try { if(productProperties.getAir_preferred_host() != -1) { AccountDetails accountDetails = (new AIRRequest(productProperties.getAir_hosts(), productProperties.getAir_io_sleep(), productProperties.getAir_io_timeout(), productProperties.getAir_io_threshold(), productProperties.getAir_preferred_host())).getAccountDetails(parameters.get("msisdn")); language = (accountDetails == null) ? 1 : accountDetails.getLanguageIDCurrent(); } else { throw new AirAvailabilityException(); } long sessionId = Long.parseLong(parameters.get("sessionid")); ussd = new JdbcUSSDRequestDao(dao).getOneUSSD(sessionId, parameters.get("msisdn")); if(ussd == null) { USSDService service = null; // check if short code is faf portail if(parameters.get("input").trim().startsWith(productProperties.getSc_secondary() + "")) { parameters.put("input", parameters.get("input").trim().replaceFirst(productProperties.getSc_secondary() + "", productProperties.getSc() + "*4")); service = new JdbcUSSDServiceDao(dao).getOneUSSDService(productProperties.getSc_secondary()); } else { service = new JdbcUSSDServiceDao(dao).getOneUSSDService(productProperties.getSc()); } Date now = new Date(); if((service == null) || (((service.getStart_date() != null) && (now.before(service.getStart_date()))) || ((service.getStop_date() != null) && (now.after(service.getStop_date()))))) { modele.put("next", false); modele.put("message", i18n.getMessage("service.unavailable", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH)); return; } ussd = new USSDRequest(0, sessionId, parameters.get("msisdn"), parameters.get("input").trim(), 1, null); } else { ussd.setStep(ussd.getStep() + 1); ussd.setInput((ussd.getInput() + "*" + parameters.get("input").trim()).trim()); } // USSD Flow Status Map<String, Object> flowStatus = new USSDFlow().validate(ussd, language, (new USSDMenu()).getContent(productProperties.getSc()), productProperties, i18n, dao); // -1 : exit with error (delete state from ussd table; message) if(((Integer)flowStatus.get("status")) == -1) { endStep(dao, ussd, modele, productProperties, (String)flowStatus.get("message"), null, null, null, null); } // 0 : successful (delete state from ussd table; actions and message) else if(((Integer)flowStatus.get("status")) == 0) { // logging Logger logger = LogManager.getLogger("logging.log4j.ProcessingLogger"); logger.trace("[" + productProperties.getSc() + "] " + "[USSD] " + "[" + parameters.get("msisdn") + "] " + "[" + ussd.getInput() + "]"); // short code String short_code = productProperties.getSc() + ""; if(ussd.getInput().equals(short_code + "*2")) { // statut pricePlanCurrentStatus(i18n, language, productProperties, dao, ussd, modele); } else if(ussd.getInput().equals(short_code + "*3")) { // infos endStep(dao, ussd, modele, productProperties, (new PricePlanCurrentActions()).getInfo(i18n, productProperties, ussd.getMsisdn()), null, null, null, null); } else if((ussd.getInput().equals(short_code + "*1")) || (ussd.getInput().equals(short_code + "*0"))) { if((new MSISDNValidator()).isFiltered(dao, productProperties, ussd.getMsisdn(), "A")) { List<String> inputs = Splitter.onPattern("[*]").trimResults().omitEmptyStrings().splitToList(ussd.getInput()); if(inputs.size() == 2) { Object [] requestStatus = (new PricePlanCurrent()).getStatus(productProperties, i18n, dao, ussd.getMsisdn(), language, false); if((int)(requestStatus[0]) >= 0) { /*if(false && ussd.getInput().endsWith("*0")) {*/ if(ussd.getInput().endsWith("*0")) { // deactivation if((int)(requestStatus[0]) == 0) { endStep(dao, ussd, modele, productProperties, i18n.getMessage("service.internal.error", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); // pricePlanCurrentDeactivation(dao, ussd, (Subscriber)requestStatus[2], i18n, language, productProperties, modele); } else endStep(dao, ussd, modele, productProperties, i18n.getMessage("status.unsuccessful.already", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); } else if(ussd.getInput().endsWith("*1")) { // activation if((int)(requestStatus[0]) == 0) endStep(dao, ussd, modele, productProperties, i18n.getMessage("status.successful.already", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); else { // check msisdn is in default price plan requestStatus[0] = productProperties.isDefault_price_plan_deactivated() ? (new DefaultPricePlan()).requestDefaultPricePlanStatus(productProperties, ussd.getMsisdn(), "eBA") : 0; if((int)(requestStatus[0]) == 0) { endStep(dao, ussd, modele, productProperties, i18n.getMessage("activation.info", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); // pricePlanCurrentActivation(dao, ussd, (Subscriber)requestStatus[2], i18n, language, productProperties, modele); } else endStep(dao, ussd, modele, productProperties, i18n.getMessage("default.price.plan.required", new Object [] {productProperties.getDefault_price_plan()}, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); } } } else { endStep(dao, ussd, modele, productProperties, i18n.getMessage("service.internal.error", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); } } else { endStep(dao, ussd, modele, productProperties, i18n.getMessage("request.unavailable", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); } } else endStep(dao, ussd, modele, productProperties, i18n.getMessage("service.disabled", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); } else if(ussd.getInput().startsWith(short_code + "*4")) { if((new MSISDNValidator()).isFiltered(dao, productProperties, ussd.getMsisdn(), "A")) { try { // List<String> inputs = Splitter.onPattern("[*]").trimResults().splitToList(ussd.getInput()); List<String> inputs = Splitter.onPattern("[*]").trimResults().omitEmptyStrings().splitToList(ussd.getInput()); // status if((inputs.size() == 3) && (ussd.getInput().equals(short_code + "*4*4"))) { // statut fafNumbersStatus(i18n, language, productProperties, dao, ussd, modele); } // add fafNumber else if((inputs.size() == 5) && (ussd.getInput().startsWith(short_code + "*4*1")) && (ussd.getInput().endsWith("*1"))) { handleFaFChangeRequest(dao, ussd, 1, null, inputs.get(3), i18n, language, productProperties, modele); } // delete fafNumber else if((inputs.size() == 5) && (ussd.getInput().startsWith(short_code + "*4*3")) && (ussd.getInput().endsWith("*1"))) { int indexOld = Integer.parseInt(Splitter.onPattern("[*]").trimResults().omitEmptyStrings().splitToList(ussd.getInput()).get(3)); HashSet<Integer> indexes = new HashSet<Integer>(); indexes.add(indexOld); String fafNumberOld = (getFaFNumbers(((new AIRRequest(productProperties.getAir_hosts(), productProperties.getAir_io_sleep(), productProperties.getAir_io_timeout(), productProperties.getAir_io_threshold(), productProperties.getAir_preferred_host()))).getFaFList(ussd.getMsisdn(), productProperties.getFafRequestedOwner()).getList(), productProperties, indexes)).get(indexOld); if(fafNumberOld == null) endStep(dao, ussd, modele, productProperties, i18n.getMessage("service.internal.error", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); else handleFaFChangeRequest(dao, ussd, 3, fafNumberOld, null, i18n, language, productProperties, modele); } // modify fafNumber else if((inputs.size() == 6) && ((ussd.getInput().startsWith(short_code + "*4*2")) && (ussd.getInput().endsWith("*1")))) { int indexOld = Integer.parseInt(Splitter.onPattern("[*]").trimResults().omitEmptyStrings().splitToList(ussd.getInput()).get(3)); HashSet<Integer> indexes = new HashSet<Integer>(); indexes.add(indexOld); HashMap<Integer, String> result = (getFaFNumbers(((new AIRRequest(productProperties.getAir_hosts(), productProperties.getAir_io_sleep(), productProperties.getAir_io_timeout(), productProperties.getAir_io_threshold(), productProperties.getAir_preferred_host()))).getFaFList(ussd.getMsisdn(), productProperties.getFafRequestedOwner()).getList(), productProperties, indexes)); String fafNumberOld = result.get(indexOld); String fafNumberNew = Splitter.onPattern("[*]").trimResults().omitEmptyStrings().splitToList(ussd.getInput()).get(4); if(fafNumberOld == null) endStep(dao, ussd, modele, productProperties, i18n.getMessage("service.internal.error", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); else handleFaFChangeRequest(dao, ussd, 2, fafNumberOld, fafNumberNew, i18n, language, productProperties, modele); } else { throw new Exception(); } } catch(NumberFormatException ex) { endStep(dao, ussd, modele, productProperties, i18n.getMessage("request.unavailable", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); } catch(Exception ex) { endStep(dao, ussd, modele, productProperties, i18n.getMessage("service.internal.error", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); } catch(Throwable ex) { endStep(dao, ussd, modele, productProperties, i18n.getMessage("service.internal.error", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); } } else endStep(dao, ussd, modele, productProperties, i18n.getMessage("service.disabled", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); } else { endStep(dao, ussd, modele, productProperties, i18n.getMessage("service.internal.error", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); } } // 1 : flow continues (save state; message) else if(((Integer)flowStatus.get("status")) == 1) { nextStep(dao, ussd, false, (String)flowStatus.get("message"), modele, productProperties); } // this case should not occur else { endStep(dao, ussd, modele, productProperties, i18n.getMessage("service.internal.error", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); } } catch(NullPointerException ex) { endStep(dao, ussd, modele, productProperties, i18n.getMessage("service.internal.error", null, null, Locale.FRENCH), null, null, null, null); } catch(AirAvailabilityException ex) { endStep(dao, ussd, modele, productProperties, i18n.getMessage("service.internal.error", null, null, Locale.FRENCH), null, null, null, null); } catch(Throwable th) { endStep(dao, ussd, modele, productProperties, i18n.getMessage("service.internal.error", null, null, Locale.FRENCH), null, null, null, null); } } public void pricePlanCurrentStatus(MessageSource i18n, int language, ProductProperties productProperties, DAO dao, USSDRequest ussd, Map<String, Object> modele) { endStep(dao, ussd, modele, productProperties, (String)(((new PricePlanCurrent()).getStatus(productProperties, i18n, dao, ussd.getMsisdn(), language, true))[1]), null, null, null, null); } public void endStep(DAO dao, USSDRequest ussd, Map<String, Object> modele, ProductProperties productProperties, String messageA, String Anumber, String messageB, String Bnumber, String senderName) { if((ussd != null) && (ussd.getId() > 0)) { new JdbcUSSDRequestDao(dao).deleteOneUSSD(ussd.getId()); } modele.put("next", false); modele.put("message", messageA); if(senderName != null) { Logger logger = LogManager.getLogger("logging.log4j.SubmitSMLogger"); // Logger logger = LogManager.getRootLogger(); if(Anumber != null) { // if(Anumber.startsWith(productProperties.getMcc() + "")) Anumber = Anumber.substring((productProperties.getMcc() + "").length()); new SMPPConnector().submitSm(senderName, Anumber, messageA); logger.trace("[" + Anumber + "] " + messageA); } if(Bnumber != null) { // if(Bnumber.startsWith(productProperties.getMcc() + "")) Bnumber = Bnumber.substring((productProperties.getMcc() + "").length()); new SMPPConnector().submitSm(senderName, Bnumber, messageB); logger.log(Level.TRACE, "[" + Bnumber + "] " + messageB); } } } public void nextStep(DAO dao, USSDRequest ussd, boolean reset, String message, Map<String, Object> modele, ProductProperties productProperties) { if(reset) { ussd.setStep(1); ussd.setInput(productProperties.getSc() + ""); } else { // } new JdbcUSSDRequestDao(dao).saveOneUSSD(ussd); modele.put("next", true); modele.put("message", message); } public void pricePlanCurrentActivation(DAO dao, USSDRequest ussd, Subscriber subscriber, MessageSource i18n, int language, ProductProperties productProperties, Map<String, Object> modele) { Object [] requestStatus = (new PricePlanCurrent()).activation(dao, ussd.getMsisdn(), subscriber, i18n, language, productProperties, "eBA"); endStep(dao, ussd, modele, productProperties, (String)requestStatus[1], ((int)requestStatus[0] == 0) ? ussd.getMsisdn() : null, null, null, ((int)requestStatus[0] == 0) ? productProperties.getSms_notifications_header() : null); } public void pricePlanCurrentDeactivation(DAO dao, USSDRequest ussd, Subscriber subscriber, MessageSource i18n, int language, ProductProperties productProperties, Map<String, Object> modele) { Object [] requestStatus = (new PricePlanCurrent()).deactivation(dao, ussd.getMsisdn(), subscriber, i18n, language, productProperties, "eBA"); endStep(dao, ussd, modele, productProperties, (String)requestStatus[1], ((int)requestStatus[0] == 0) ? ussd.getMsisdn() : null, null, null, ((int)requestStatus[0] == 0) ? productProperties.getSms_notifications_header() : null); } public void fafNumbersStatus(MessageSource i18n, int language, ProductProperties productProperties, DAO dao, USSDRequest ussd, Map<String, Object> modele) { endStep(dao, ussd, modele, productProperties, (String)(((new FaFManagement()).getStatus(productProperties, i18n, dao, ussd.getMsisdn(), language))[1]), null, null, null, null); } public void handleFaFChangeRequest(DAO dao, USSDRequest ussd, int action, String fafNumberOld, String fafNumberNew, MessageSource i18n, int language, ProductProperties productProperties, Map<String, Object> modele) { Object [] requestStatus = (new PricePlanCurrent()).getStatus(productProperties, i18n, dao, ussd.getMsisdn(), language, false); if((int)(requestStatus[0]) == 0) { // check Bnumber is allowed if(action != 3) { if((new MSISDNValidator()).isFiltered(dao, productProperties, ((((productProperties.getMcc() + "").length() + productProperties.getMsisdn_length()) == (fafNumberNew.length())) ? fafNumberNew : (productProperties.getMcc() + "" + fafNumberNew)), "B")) { // fafNumber is allowed } else { // fafNumber is not allowed endStep(dao, ussd, modele, productProperties, i18n.getMessage("faf.number.disabled", new Object[] {fafNumberNew}, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); } } Subscriber subscriber = (Subscriber)requestStatus[2]; if(new JdbcSubscriberDao(dao).lock(subscriber) == 1) { // fire the checking of fafChangeRequest charging (new FaFManagement()).setFafChangeRequestChargingEnabled(dao, productProperties, subscriber); if(action == 1) { requestStatus = (new FaFManagement()).add(dao, subscriber, fafNumberNew, i18n, language, productProperties, "eBA"); } else if(action == 3) { requestStatus = (new FaFManagement()).delete(dao, subscriber, fafNumberOld, i18n, language, productProperties, "eBA"); } else { requestStatus = (new FaFManagement()).replace(dao, subscriber, fafNumberOld, fafNumberNew, i18n, language, productProperties, "eBA"); } // unlock new JdbcSubscriberDao(dao).unLock(subscriber); // notification via sms endStep(dao, ussd, modele, productProperties, (String)requestStatus[1], ((int)requestStatus[0] == 0) ? ussd.getMsisdn() : null, null, null, ((int)requestStatus[0] == 0) ? productProperties.getSms_notifications_header() : null); } else { endStep(dao, ussd, modele, productProperties, i18n.getMessage("service.internal.error", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); } } else { endStep(dao, ussd, modele, productProperties, i18n.getMessage("menu.disabled", null, null, (language == 2) ? Locale.ENGLISH : Locale.FRENCH), null, null, null, null); } } public HashMap<Integer, String> getFaFNumbers(HashSet<FafInformation> fafNumbers, ProductProperties productProperties, HashSet<Integer> indexes) { HashMap<Integer, String> result = new HashMap<Integer, String>(); LinkedList<Long> fafNumbers_copy = new LinkedList<Long>(); for(FafInformation fafInformation : fafNumbers) { fafNumbers_copy.add(Long.parseLong(fafInformation.getFafNumber())); } Collections.sort (fafNumbers_copy) ; // Collections.sort (fafNumbers_copy, Collections.reverseOrder()) ; int i = 0; for(Long fafInformation : fafNumbers_copy) { i++; if(indexes.contains(i)) { result.put(i, fafInformation + ""); } } return result; } }
Java
UTF-8
804
1.96875
2
[]
no_license
package com.zx.train; import com.baidu.aip.ocr.AipOcr; import org.json.JSONObject; import java.util.HashMap; /** * 图片文字提取 */ public class Test3 { //设置APPID/AK/SK public static final String APP_ID = "17723363"; public static final String API_KEY = "aD4SDTgEISUlAB0sm60cbOSb"; public static final String SECRET_KEY = "0xlOrGhRxZG3ZZeZ7tZ9S3e8NzaM7Oc5"; public static void main(String[] args) { // 初始化一个AipOcr AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY); // 可选:设置网络连接参数 client.setConnectionTimeoutInMillis(2000); client.setSocketTimeoutInMillis(60000); String path = "C:\\Users\\Yue\\Desktop\\14.png"; JSONObject res = client.basicGeneral(path, new HashMap<String, String>()); } }
Markdown
UTF-8
12,589
3.296875
3
[]
no_license
> 先赞后看,养成习惯 🌹 欢迎微信关注 `[Java编程之道] `每天进步一点点,沉淀技术分享知识。<br> >后续发布的文章、源码等,都会收录到GitHub:`Xxianglei/Alei`仓库之中,欢迎大家前来自取。 今天由于时间关系就聊一点简单,我正在计划后期写作的文章,近期工作上接触了一些有意思的东西,后面会跟大家唠唠。如果你有意见或建议欢迎留言。📫<br> `***文末有惊喜***` 🎁 # List 集合 --- - List集合代表一个**有序集合**,集合中每个元素都有其对应的顺序索引。List集合允许使用重复元素,可以通过索引来访问指定位置的集合元素。 - List接口继承于Collection接口,它可以定义一个允许重复的有序集合。因为List中的元素是有序的,所以我们可以通过使用索引(元素在List中的位置,类似于数组下标)来访问List中的元素,这类似于Java的**数组**。 - List接口为Collection直接接口。List所代表的是有序的Collection,即它用某种特定的插入顺序来维护元素顺序。用户可以对列表中每个元素的插入位置进行精确地控制,同时可以根据元素的整数索引(在列表中的位置)访问元素,并搜索列表中的元素。实现List接口的集合主要有:**ArrayList、LinkedList、Vector、Stack**。 接下来先借鉴一下源码,我们照着源码的思路,来写一个自己的ArrayList集合。 在开始看源码之前我需要补充说明一下**数组扩容技术** - Arrays.copyOf(Object[] original, int newLength) 功能是实现数组的复制,返回复制后的数组。参数是被复制的**数组**和复制的**长度**。这个没什么好说的就等于是把数组按**新**的大小给重新赋值了一份返回了一个新的数组。 - System.arraycopy(src, srcPos, dest, destPos, length); 如果是数组比较大,那么使用System.arraycopy会比较有优势,因为其使用的是内存复制,省去了大量的数组寻址访问等时间 参数解释: - src:源数组; - srcPos:源数组要复制的起始位置; - dest:目的数组; - destPos:目的数组放置的起始位置; length:复制的长度。 注意:src and dest都必须是同类型或者可以进行转换类型的数组. **原理图解**: ![在这里插入图片描述](https://img-blog.csdnimg.cn/20190306133702240.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTE1ODMzMTY=,size_16,color_FFFFFF,t_70) ## ArrayList 源码 --- 1. 想想我们需要手写一个ArrayList、需要看点什么?构造方法? ```java /** * Default initial capacity. */ private static final int DEFAULT_CAPACITY = 10; /** * Shared empty array instance used for empty instances. */ private static final Object[] EMPTY_ELEMENTDATA = {}; /** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } ``` 可以看到,默认无参时,数组的初始容量大小是10. 2. 带参构造方法 ```java // 带参构造方法 public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; } else { throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } } ``` 3. 看看数据添加方法 ```java /** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); } // 数据扩容 这里用了一个位运算 private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); } ``` 看到这里你基本上也清楚了,ArrayList的扩容倍数是1.5倍。比如oldCapacity=2,oldCapacity + (oldCapacity >> 1)执行后就等于3。 补充说明:**位运算** - <<(向左位移) 针对二进制,转换成二进制后向左移动1位,后面用0补齐 - \>>(向右位移) 针对二进制,转换成二进制后向右移动1位 4. 看看按索引添加,类似于插入吧 ```java public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; } ``` 其实和添加没有多大的不同,就是用到了数组的赋值,如下图 原size=5,现在F要插入到下标为2的位置,所以 System.arraycopy(elementData, 2, elementData, index + 1, 5 - 2); 后移后面的三位元素。 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20190306135205499.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTE1ODMzMTY=,size_16,color_FFFFFF,t_70) 5. 再看看remove方法 1. 按索引删除。这个很简单,原理同添加,只不过需要注意的是如果删除的是最后一位要进行一个判断,就不需要进行数组赋值,直接置空即可! ```java public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work return oldValue; } ``` 2.按对象删除. 这个相信大家都能看懂 ```java public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } ``` 好了,源码基础的内容就看完咯。接下来就是见证奇迹的时刻了! ## 手写 ArrayList 说明以及被我写在注释里了,没有特别之处我就不做多余的提示了。 ```java package com.xianglei.Utils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ExtArrayList<E> implements ExtList<E> { // ArrayList底层采用数组存放 private Object[] elementData; // 默认数组容量 private static final int DEFAULT_CAPACITY = 10; // 记录实际ArrayList大小 初始为0 private int size; // 默认容量大小为10 public ExtArrayList() { this(DEFAULT_CAPACITY); } // 构造方法指定数组容量 public ExtArrayList(int defaultCapacity) { if (defaultCapacity < 0) { throw new IllegalArgumentException("初始容量不能小于0"); } elementData = new Object[defaultCapacity]; } public void add(E e) { // 1.判断实际存放的数据容量是否大于elementData容量 ensureExplicitCapacity(size + 1); // 判断实际存储的数据所占容量大小 // 从下标0开始存储 elementData[size++] = e; } // int minCapacity 最当前size+1 最小的扩容量 private void ensureExplicitCapacity(int minCapacity) { // 一旦等于数组容量大小就进行扩容 if (size == elementData.length) { // 原来本身elementData容量大小 2 int oldCapacity = elementData.length; // 新数据容量大小 (oldCapacity >> 1)=oldCapacity/ // <<(向左位移) 针对二进制,转换成二进制后向左移动1位,后面用0补齐 // >>(向右位移) 针对二进制,转换成二进制后向右移动1位, /** * 如果初始是1的话 目前扩容后 newCapacity还是1 */ int newCapacity = oldCapacity + (oldCapacity >> 1);// (2+2/2)=3 // 如果初始容量为1的时候,那么他扩容的大小为多少呢? if (newCapacity - minCapacity < 0) newCapacity = minCapacity; // 最少保证容量和minCapacity一样 // 将老数组的值赋值到新数组里面去 elementData = Arrays.copyOf(elementData, newCapacity); } } // 按下标删除 public Object remove(int index) { rangeCheck(index); Object object = get(index); int numMoved; numMoved = size - index - 1; if (numMoved > 0) { System.arraycopy(elementData, index + 1, elementData, index, numMoved); } elementData[--size] = null; return object; } public boolean removeObj(E object) { for (int i = 0; i < elementData.length; i++) { Object element = elementData[i]; if (element.equals(object)) { remove(i); return true; } } return false; } public void insert(int index, E e) { // 1.判断实际存放的数据容量是否大于elementData容量 ensureExplicitCapacity(size + 1); System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = e; size++; } private void rangeCheck(int index) { if (index >= size) throw new IndexOutOfBoundsException("越界啦!"); } public int getSize() { return size; } // 使用下标获取数组元素 public Object get(int index) { rangeCheck(index); return elementData[index]; } public boolean remove(E object) { // TODO Auto-generated method stub return false; } } ``` 做个简单的优化,使用泛型接口。 ```java public interface ExtList<E> { public void add(E object); public void insert(int index, E object); public Object remove(int index); public boolean removeObj(E object); public int getSize(); public Object get(int index); } ``` 大家都听说过ArrayList是**线程不安全**的,我想通过源码大家已经知道为什么不安全了。没有**synchronized**关键字。与之相反的有一个Vector集合,他就是**线程安全**的。他们俩的源码很相似,Vector无非只是加上了锁synchronized。 - Vector的add方法: ```java public synchronized boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = e; return true; } ``` ---- ## 总结 ---- Vector是线程安全的,但是**性能**比ArrayList要**低**。 ArrayList,Vector主要区别为以下几点: - Vector是线程安全的,源码中的方法都用synchronized修饰,而ArrayList不是。Vector效率无法和ArrayList相比。 - ArrayList和Vector都采用**线性连续存储空间**,当存储空间不足的时候,ArrayList默认增加为原来的50%,Vector默认增加为原来的一倍。 **也就是常知的1.5 和 2 倍** - Vector可以设置capacityIncrement,而ArrayList不可以,从字面理解就是capacity容量,Increment增加,容量增长的参数。 - ArrayList 查询快,修改、删除、插入慢。因为除了查询操作其他都涉及大量的元素移动。 --- 该文章转至我的 [CSDN博客](https://blog.csdn.net/u011583316),近期我已经在`掘金`注册了一个新博客账号 [爱唠嗑的阿磊](https://juejin.im/user/5985a384f265da3e0f119974) ,CSDN的博客号我不会再更新了,欢迎大家来掘金溜达溜达---一个全是`好文`的地方。
Markdown
UTF-8
4,978
3.984375
4
[]
no_license
# ES6 Reference Guide ![es6_logo](Images/es6_logo.jpg) ## Background "ECMAScript" (also called "ES") is the name of the international standard defining JavaScript. Released in 2015, ES6 contains numerous changes to the language syntax and is the recommended version of this standard. - - - ### Assigning Variables ## `let` `let` allows you to declare a block scope local variable: Take a look at the code here ```js let x = 13; console.log(x); // x is 13 function printX() { let x = 22; console.log(x); // x is 22 } printX(); console.log(x); // x is 13 ``` Notice that inside of the function scope, x = 22, but as soon as it hits the end of its "block" or `}`, x is 13 again. ### <u> let vs var</u> **`var`** ```js function usingVar() { for (var i = 0; i < 3; i++) { console.log(i); // logs 0,1,2 } console.log(i); // logs 3 } usingVar(); ``` A variable declared using `var` will be accessible outside of the block it was declared in. **`let`** ```js function usingLet() { for (let i = 0; i < 3; i++) { console.log(i); // logs 0,1,2 } console.log(i); // throws error } usingLet(); ``` **Error:** ```output console.log(i); ^ ReferenceError: i is not defined ``` A variable declared using `let` will **not** be accessible outside of the block it was declared in. For more info on `let`, checkout the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) ## `const` `const` stands for "constant" and values may not be reassigned. Similar to `let`, `const` does not declare or initialize values until that line of code is run. Though the values cannot be reassigned, objects and arrays can be manipulated using methods such as `.pop()` and `.push()`: ```js const petNames = ["Cleo", "Jax", "Chance", "Buckaroo", "fishy"] console.log("All of my pets: ", petNames); // Remove the last value from the array petNames.pop(); // View the array console.log("Dogs and cats: ", petNames) ``` The array after using `.pop()`: ```output Dogs and cats: >(4) ["Cleo", "Jax", "Chance", "Buckaroo"] ``` For more info on `const`, checkout the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) - - - ## `.forEach` `.forEach` is used to call a function on each item in an array. ```js function printWithIndex(d, i) { console.log(i, d) } var arr = ["One", "Two", "Three", "Four"]; arr.forEach(printWithIndex); ``` ```output 0 "One" 1 "Two" 2 "Three" 3 "Four" ``` In the above example, `.forEach` is chained with the variable `arr`, returning both arguments (data and index) of the function. - - - ## Template Literals `Template Literals` replace traditional string concatenation. Instead of quotes, backticks are utilized. Place holders are contained with `$` and the expression is wrapped in curly brackets: ```js let firstName = "John"; let lastName = "Doe"; const fullName = `${firstName} ${lastName}`; console.log(fullName); > John Doe ``` - - - ## `.map` This method creates a new array from an existing array while leaving the original unchanged. Let's work through an example. * First, create an example that will multiply a number by two: ```js function timesTwo(num) { return 2 * num; } ``` * Next, call the `timesTwo` function on each element in the array using `.map`: ```js var doubleItems = [1, 2, 3, 4].map(timesTwo); console.log(doubleItems); ``` ```output > (4) [2, 4, 6, 8] ``` Here is another example using `.map`: ```js let students = [{name: "John", grade: 89}, {name: "Jane", grade: 91}]; function getGrades(student) { return student.grade; } let grades = students.map(getGrades); console.log(grades) ``` ```output > (2) [89, 91] ``` When used in conjunction with the `getGrades` function above, `.map` creates a new variable containing only the student grades. The original array remains untouched. - - - ## Arrow Functions Arrow functions provide a new syntax for writing functions in JavaScript. Using arrow functions creates code that is more concise and streamlined. Let's revisit the code from the `.map` example above: ```js // Original function function getGrades(student) { return student.grade; } let grades = students.map(getGrades); ``` ```js // The same function rewritten as an arrow function students.map(student => student.grade) ``` The same block of code has been condensed into a single line with the use of an arrow function. Note that a "fat arrow" has replaced the word "function". Also, without the curly brackets, the return statement is implied. To create an arrow function using a single parameter, parentheses and curly brackets are omitted completely: ```js var square = x => x * x; ``` Parentheses contain two parameters in an arrow function, but curly brackets are still omitted: ```js var multiply = (a, b) => a * b; ``` - - -
JavaScript
UTF-8
11,687
3.21875
3
[]
no_license
//Hi, thank you for grading my assigment, I would like clarify some thing that I have done here: //I have not validated every input, but I have done quite a lot, mainly the ones that required text, I did validate each section except the feedback as the user should not be obligated to answer it. //The person section is dynamically added from a <template> tag to the <form> depending on the number of people who spend the night in the house. It works fine, but the only "bug" I couldn't resolve was when the user speaks another language than English and choose his options. The next person gets selected the previously chosen options, then they can change them, but it is still a "bug". This problem is probably caused because I wrote a function to allow users to click multiple options without holding down the CRTL key, and because each "person" section is dynamically added, the function retains the previous "non-English" language selection. I tried different things to solve it but couldn't work it out. //I tried to write the functions separately to keep clean and easy for debugging but inevitably My function nextButton() got really long and complex, I apologize for that. //function for displaying the help section function helpButton(){ $('#help').on("click", function(){ if($(".HelpAddress").css("display") == "none"){ $(".HelpAddress").css("display", "initial") } else{ $(".HelpAddress").css("display", "none") } }); $('#helpbuttonDwelling').on("click", function(){ if($(".HelpDwelling").css("display") == "none"){ $(".HelpDwelling").css("display", "initial") } else{ $(".HelpDwelling").css("display", "none") } }); $('#helpbuttonFeed').on("click", function(){ if($(".HelpFeedback").css("display") == "none"){ $(".HelpFeedback").css("display", "initial") } else{ $(".HelpFeedback").css("display", "none") } }); }; //function to highlight in red and go back to withe when focus, wrong inputs function redInput(parameter){ parameter.css("background-color", "rgba( 190, 5, 5, .5)"); parameter.focus(function(){ parameter.css("background-color", "white"); $("#empty").remove(); }) }; //This is the master function, It validates how many people are at the dwelling, then displays a quetionnaire per each person declared in the "people spending the night at dwelling" when "next button" is pressed. It also validates patterns for people sections. function nextButton(){ var temPeople = $("#people").contents(); var alert = $("#alerts").contents(); $("#next").on("click", function(){ var patternWord = /^\s*[a-zA-Z]+\s*\w*/; var qty = $('[name = "peopleNight"]'); var state = $('[name = "state"]'); var stNumber = $('[name = "streetNumber"]'); var stName = $('[name = "streetName"]'); var suburb = $('[name = "suburb"]'); var code = $('[name = "code"]'); if( stNumber.val() == 0){ redInput(stNumber); $("#address").append(alert); }else if( stName.val() == 0 || patternWord.test(stName.val()) == false){ redInput(stName); $("#address").append(alert); }else if( suburb.val() == 0 || patternWord.test(suburb.val()) == false){ redInput(suburb); $("#address").append(alert); }else if( state.val() == 0 || patternWord.test(state.val()) == false){ redInput(state); $("#address").append(alert); }else if( code.val() == 0){ redInput(code); $("#address").append(alert); }else if( qty.val() == 0){ redInput(qty); $("#address").append(alert); }else{ $("#address").css("display", "none"); //I used this For loop to get the number of people and display the sections with the number of person that is doing the questionnaire. for(var i = 1; i <= qty.val(); i ++){ var newPerson = temPeople.clone().attr("id" , "people " + i); newPerson.insertBefore("#dwelling"); $(newPerson).find("#legend").html('Person ' + i ); var btnNew = $(newPerson).find("#nextPerson").attr("id", "nextPerson " + i); var btnInfo = $(newPerson).find("#helpPersonBtn").attr("id", "helpPersonBtn " + i); var isCitizen = $(newPerson).find('[name = "citizen"]'); //var yearArrive = $(newPerson).children("#yearArrive"); var newLang = $("#tempLang").contents(); var langCont = $(newPerson).find("#languageContainer"); var language = $(newPerson).find('[name = "lang"]'); if( i != 1){ $(newPerson).css("display", "none"); } $(btnNew).on("click", function(){ var box = $(this).parent().parent(); var nextBox = $(this).parent().parent().next(); var patternW = /^\s*[a-zA-Z]+\s*\w*/; var GivName = $(box).find('[name = "GivenName"]'); var FamName = $(box).find('[name = "FamilyName"]'); var gender = $(box).find('[name = "gender"]'); var dob = $(box).find('[name = "dob"]'); var lang = $(box).find('[name = "lang"]'); var field = $(box).find('[name = "studyField"]'); if( GivName.val() == 0 || patternW.test(GivName.val()) == false ){ redInput(GivName); $(box).append(alert); }else if( FamName.val() == 0 || patternW.test(FamName.val()) == false){ redInput(FamName); $(box).append(alert); }else if( gender.val() == 0 || patternW.test(gender.val()) == false){ redInput(gender); $(box).append(alert); }else if( dob.val() == 0){ redInput(dob); $(box).append(alert); }else if( lang.val() == 0){ redInput(lang); $(box).append(alert); }else if( field.val() == 0 || patternW.test(gender.val()) == false){ redInput(field); $(box).append(alert); }else{ box.css("display", "none"); nextBox.css("display", "inline-block"); } }); $(isCitizen).on("click", function(e){ var up = $(this).parent().parent(); var yearArrive = $(up).find("#yearArrive") console.log("CLICK"); console.log(yearArrive); var citizenVal = $(this).val(); if( citizenVal != "yes"){ console.log(citizenVal) $(yearArrive).css("display", "initial"); }else{ console.log(citizenVal) $(yearArrive).css("display", "none"); } }); newHTML(newLang, language, langCont) $(btnInfo).on("click", function(){ var info = $(this).parent().parent().find("#helpBox"); if($(info).css("display") == "none"){ $(info).css("display", "initial") } else{ $(info).css("display", "none") } }); } } }); }; //Function to validate the dwelling section, this section just validates two inputs. function dwellingBtn(){ $("#nextDwelling").on("click", function(){ var Gb = $('[name = "GBs"]'); var beds = $('[name = "beds"]'); var alertEmpty = $("#alerts").contents(); console.log(alertEmpty) if(Gb.val() == 0){ redInput(Gb); $(alertEmpty).appendTo("#dwelling"); }else if(beds.val() == 0){ redInput(beds); $(alertEmpty).appendTo("#dwelling"); }else{ $("#dwelling").css("display", "none") $("#dwelling").next().css("display", "inline-block") } }); helpButton(); } // This function reload the website when the "reset" button is pressed function FeedbackSubmit(){ $(".reset").on("click", function(){ location.reload(); }); helpButton(); } // This function toggles visibility from elements already created in the hmtl form structure. It also validates the radio inputs and displays more options depending of some answers but I had to remove and place it inside the function that creates person's section because was giving me issues when submit. // function ToggleVisibility(){ // $('[name = "citizen"]').on("click", function(e){ // var citizen = $(this).val(); // if( citizen != "yes"){ // $("#yearArrive").css("display", "initial"); // }else{ // $("#yearArrive").css("display", "none"); // } // }); // }; //function to prevent the default settings for multiple choices to avoid using the CTRL key when selecting various options function multipleOptions(){ var langOptions = $("#lang > option"); // var carOptions = $("#Car > option"); $(langOptions).mousedown(function(eve){ eve.preventDefault(); console.log("multiple working") $(this).prop("selected", !$(this).prop("selected")) }); }; //This function appends some contents such as datalists to the HTML form, either from the <template> or as new elements. function newHTML(p1, p2, p3){ var tempCar = $("#tempCar").contents(); $(p2).on("click", function(e){ var langRadioValue = $(this).val(); if( langRadioValue == "yes" ){ $(p3).append(p1); multipleOptions(); }else{ $("#lang").remove(); }; }); $('[name = "Car"]').on("click", function(e){ var langCarValue = $(this).val(); if( langCarValue == "yes" ){ $("#carContainer").append(tempCar); multipleOptions(); }else{ $("#Car").remove(); } }); }; // function to prevent the Default behaviour of submit the form when "Enter key" is accidentally pressed function enterKey(){ $(window).keydown(function (e) { if(e.keyCode == 13){ e.preventDefault(); return false; } }); } //initialise function; contains all functions in separate pieces of code for a better debbuging when necessary function initialise() { helpButton(); nextButton(); newHTML(); enterKey(); dwellingBtn(); FeedbackSubmit(); };
Python
UTF-8
5,391
3.453125
3
[]
no_license
import sqlite3 import os class KatakanaDatabaseUtilities(): """Purpose of this class is to set-up connection with the katakana database and fill it with the katakanas and options for the different game levels. Idea is to use operations in this class once when the game is first established. """ def __init__(self): """Constructor for the class. """ text = os.path.join(".", "data", "katakanadatabase.db") self._file_name = text self.katakana_db = "" def initialize_katakana_db(self): """Method calls other methods in class to create the necessary databases, tables and data at the beginning of the game for the Katakana database. """ self.create_katakana_database_connection() self._create_katakana_database_table() self._create_games_database_table() def create_katakana_database_connection(self): """Method sets up connection with the Katakana database. """ self.katakana_db = sqlite3.connect(self._file_name) self.katakana_db.isolation_level = None def _create_katakana_database_table(self): """Method creates an empty table Katakanas for katakanas in the Katakana database, if the table does not yet exist. """ self.create_katakana_database_connection() raw_existing_databases = self.katakana_db.execute("""SELECT name FROM sqlite_master WHERE type = "table" """).fetchall() existing_databases = [] for i in raw_existing_databases: existing_databases.append(i[0]) if (len(existing_databases) == 0) or ("Katakanas" not in existing_databases): self.katakana_db.execute("""CREATE TABLE Katakanas( id INTEGER PRIMARY KEY, roomaji TEXT, katakana TEXT, series TEXT, difficulty_level INTEGER)""" ) self._create_katakana_baseline_data() def _create_katakana_baseline_data(self): """Method fills in the Katakana table in the Katakana Database when the table is created for the first time. Note. This function is only called in the first time, when the database is created and it is filled with original raw katakana data. """ text = os.path.join(".", "data", "katakanas.csv") with open(text) as katakana_baseline_file: raw_katakana_data = katakana_baseline_file.readlines() for i in range(1, len(raw_katakana_data)): line = raw_katakana_data[i] line = line.strip() line = line.split(',') self.katakana_db.execute("""INSERT INTO Katakanas (roomaji, katakana, series, difficulty_level) VALUES(?, ?, ?, ?) """, [line[0], line[1], line[2], line[3]]) def _create_games_database_table(self): """At the beginning of the game, a table Games is created, if it does not exist. This operation is done only once at the beginning of the game. """ self.create_katakana_database_connection() raw_existing_databases = self.katakana_db.execute("""SELECT * FROM sqlite_master WHERE type = "table" """).fetchall() existing_databases = [] for i in raw_existing_databases: existing_databases.append(i[1]) if (len(existing_databases) == 0) or ("Games" not in existing_databases): self.katakana_db.execute("""CREATE TABLE Games( game_level INTEGER PRIMARY KEY, number_of_cards INTEGER, number_of_deaths INTEGER, number_of_unique_cards INTEGER)""" ) self._create_games_baseline_data() def _create_games_baseline_data(self): """Method fills in the Games table in the Katakana database at the beginning of the game. Source for the data is a separate csv file. Contents of the table contain specifications for the different levels of the game. """ text = os.path.join(".", "data", "games.csv") with open(text) as games_baseline_file: raw_games_data = games_baseline_file.readlines() self.create_katakana_database_connection() for i in range(1, len(raw_games_data)): line = raw_games_data[i] line = line.strip() line = line.split(',') self.katakana_db.execute("""INSERT INTO Games (game_level, number_of_cards, number_of_deaths, number_of_unique_cards) VALUES(?, ?, ?, ?) """, [line[0], line[1], line[2], line[3]])
C++
UTF-8
2,260
2.765625
3
[]
no_license
#include "stdafx.h" #include "GridDistances.h" #include "ParameterManager.h" int g_relPosCountInRange= 0; int g_absPosCountInRange= 0; struct RelPos { int relX; int relY; float relDist; }; RelPos *g_pDistMatrix= 0; int g_entryCount= 0; void ReleaseDistMatrix() { if (g_pDistMatrix) { delete [] g_pDistMatrix; g_pDistMatrix= 0; } } void InitDistMatrix(int maxRelX,int maxRelY,float maxRelDist,bool bAllowNullDist) { ReleaseDistMatrix(); g_entryCount= (maxRelX*2+1)*(maxRelY*2+1); if (!bAllowNullDist) g_entryCount--; g_pDistMatrix= new RelPos[g_entryCount]; int i= 0; //construct all possible relative displacements for (int x=-maxRelX; x<=maxRelX;x++) { for (int y=-maxRelY; y<=maxRelY; y++) { if (x!=0 || y!=0 || bAllowNullDist) { g_pDistMatrix[i].relX= x; g_pDistMatrix[i].relY= y; g_pDistMatrix[i].relDist= sqrt((float)(x*x+y*y)); i++; } } } //sort the relative displacements RelPos aux; for (int a= 0; a<g_entryCount-1; a++) { for (int b= a+1; b<g_entryCount; b++) { if (g_pDistMatrix[b].relDist<g_pDistMatrix[a].relDist) { //swap //aux<-matrix(a) aux.relX= g_pDistMatrix[a].relX; aux.relY= g_pDistMatrix[a].relY; aux.relDist= g_pDistMatrix[a].relDist; //matrix(a)<-matrix(b) g_pDistMatrix[a].relX= g_pDistMatrix[b].relX; g_pDistMatrix[a].relY= g_pDistMatrix[b].relY; g_pDistMatrix[a].relDist= g_pDistMatrix[b].relDist; //matrix(b)<-aux g_pDistMatrix[b].relX= aux.relX; g_pDistMatrix[b].relY= aux.relY; g_pDistMatrix[b].relDist= aux.relDist; } } } //MACHINE LEARNING - HOSE EXPERIMENT MOD///////////////// g_relPosCountInRange= CountRelPosInRange(maxRelDist); ///////////////////////////////////////////////////////// } int CountRelPosInRange(float maxDist) { int count= 0; int i= 0; while (i<g_entryCount && g_pDistMatrix[i].relDist<=maxDist) { count++; i++; } return count; } void GetIthRelPos(int i,int &outX,int &outY) { if (i<0 || i>=g_entryCount) return; outX= g_pDistMatrix[i].relX; outY= g_pDistMatrix[i].relY; } int GetRelPosIndex(int x,int y,int maxI) { for (int i= 0; i<g_entryCount && i<maxI; i++) { if (x==g_pDistMatrix[i].relX && y==g_pDistMatrix[i].relY) return i; } return -1; }
JavaScript
UTF-8
1,014
3.71875
4
[]
no_license
/** * 策略模式 */ // 普通情况下,没有使用策略模式 class User { constructor(type) { this.type = type; } buy() { if (this.type === "ordinary") { console.log("普通用户购买"); } else if (this.type === "member") { console.log("会员用户购买"); } else if (this.type === "vip") { console.log("高级会员购买"); } } } // 使用 let u1 = new User("ordinary"); u1.buy(); let u2 = new User("member"); u2.buy(); let u3 = new User("vip"); u3.buy(); // ================ 使用策略模式进行调整 =================== class OrdinaryUser { buy() { console.log("普通用户购买"); } } class MemberUser { buy() { console.log("会员用户购买"); } } class VipUser { buy() { console.log("高级会员用户购买"); } } // 测试 let ou = new OrdinaryUser(); ou.buy(); let mu = new MemberUser(); mu.buy(); let vu = new VipUser(); vu.buy();
Java
UTF-8
353
2.40625
2
[]
no_license
package model; import java.util.List; import java.util.Map; public interface I_Portfolio<T extends I_OwnedStock> { void setName(String n); String getName(); List<T> getOwnedStocks(); double getTotalValue(); boolean addStock(String ticker, String name,int numberOfShares); double getValueOfHolding(String stockTicker); }
PHP
UTF-8
2,134
2.796875
3
[]
no_license
<?php namespace Spirit\View; /** * Class Template * @package Spirit\View * * @method static in($block_name) * @method static append($block_name) * @method static prepend($block_name) * @method static block($block_name) * @method static view($tpl, $data = []) * @method static save() */ class Template { /** * @var string|null */ protected static $prepareExtendingFile = null; /** * @var Layout[] */ protected static $layouts = []; /** * @var Layout|null */ protected static $extendLayout = null; /** * @param $path * @param null $file * @return Layout * @throws \Exception */ public static function extend($path, $file = null) { if (!$file && !static::$prepareExtendingFile) { throw new \Exception('Extending file is not found'); } $l = static::layout($path)->extendedBy($file ? $file : static::$prepareExtendingFile); static::$prepareExtendingFile = null; return $l; } public static function prepareExtendingFile($file) { static::$prepareExtendingFile = $file; } public static function clean(Layout $layout) { $path = array_search($layout, static::$layouts, true); if ($path) { unset(static::$layouts[$path]); } } /** * @param $path * @return Layout */ public static function layout($path) { if (!isset($layouts[$path])) { static::$layouts[$path] = new Layout($path); } return static::$layouts[$path]; } public static function add(Layout $layout, $key = null) { static::$layouts[$key] = $layout; } public static function current() { if (!count(static::$layouts)) { return null; } /** * @var Layout $layout */ $layout = array_values(array_slice(static::$layouts, -1))[0]; return $layout; } public static function __callStatic($name, $arguments) { return static::current()->{$name}(...$arguments); } }
JavaScript
UTF-8
4,922
2.609375
3
[]
no_license
"use strict"; const ECS = require('yagl-ecs'), PIXI = require('pixi.js'), math = require('../util/math'), MessageManager = require('../messaging/messagemanager') ; class Renderer extends ECS.System { constructor( width, height) { super(); this.renderer = new PIXI.WebGLRenderer(width, height); this.renderer.backgroundColor = 0x999999; document.body.appendChild(this.renderer.view); // install stage this.stage = new PIXI.Container(); this.layers = {}; this.fixedEntities = []; this.width = width; this.height = height; } depthSort() { this.stage.children.sort((a, b) => { return a.zIndex - b.zIndex; }); } test(entity) { return entity.components.sprite && entity.components.position; } enter(entity) { let {sprite} = entity.components; entity.sprite = new PIXI.Sprite(PIXI.Texture.fromImage(sprite.src)); if (sprite.width && sprite.height) { entity.sprite.width = sprite.width; entity.sprite.height = sprite.height; } if (entity.components.collision) { entity.collisionBoxTopLeft = new PIXI.Sprite(PIXI.Texture.fromImage('assets/textures/sun.png')); entity.collisionBoxTopRight = new PIXI.Sprite(PIXI.Texture.fromImage('assets/textures/sun.png')); entity.collisionBoxBottomRight = new PIXI.Sprite(PIXI.Texture.fromImage('assets/textures/sun.png')); entity.collisionBoxBottomLeft = new PIXI.Sprite(PIXI.Texture.fromImage('assets/textures/sun.png')); entity.collisionBoxTopLeft.anchor.x = .5; entity.collisionBoxTopLeft.anchor.y = .5; entity.collisionBoxTopLeft.scale.x = .05; entity.collisionBoxTopLeft.scale.y = .05; entity.collisionBoxTopRight.anchor.x = .5; entity.collisionBoxTopRight.anchor.y = .5; entity.collisionBoxTopRight.scale.x = .05; entity.collisionBoxTopRight.scale.y = .05; entity.collisionBoxBottomRight.anchor.x = .5; entity.collisionBoxBottomRight.anchor.y = .5; entity.collisionBoxBottomRight.scale.x = .05; entity.collisionBoxBottomRight.scale.y = .05; entity.collisionBoxBottomLeft.anchor.x = .5; entity.collisionBoxBottomLeft.anchor.y = .5; entity.collisionBoxBottomLeft.scale.x = .05; entity.collisionBoxBottomLeft.scale.y = .05; } entity.sprite.anchor.x = sprite.anchor[0]; entity.sprite.anchor.y = sprite.anchor[1]; // If it's a skybox, add it to the back on the stage if (entity.components.skybox) { entity.sprite.zIndex = -20; this.fixedEntities.push(entity); this.stage.addChild(entity.sprite); this.depthSort(); return; } // If it's fixed if (entity.components.positionfixed) { this.stage.addChild(entity.sprite); this.depthSort(); return; } // Determine depth let depth = 0; if (entity.components.depth) { depth = entity.components.depth.value; let minDepth = -20, maxDepth = 7, scalingDepthFactor = (depth - minDepth) / (maxDepth - minDepth); // Normalize to a value between 0 and 1 entity.sprite.scale.x = scalingDepthFactor; entity.sprite.scale.y = scalingDepthFactor; } if( ! this.layers[depth] ) { // Create depth layer this.layers[depth] = new PIXI.Container(); this.layers[depth].zIndex = depth; this.stage.addChild(this.layers[depth]); this.depthSort(); } // Add entity to depth layer this.layers[depth].addChild(entity.sprite); if (entity.components.collision) { this.layers[depth].addChild(entity.collisionBoxTopLeft); this.layers[depth].addChild(entity.collisionBoxTopRight); this.layers[depth].addChild(entity.collisionBoxBottomRight); this.layers[depth].addChild(entity.collisionBoxBottomLeft); } } update(entity) { let {sprite, position} = entity.components; if (entity.components.collision) { entity.collisionBoxTopLeft.position.x = entity.components.collision.boxTopLeft[0]; entity.collisionBoxTopLeft.position.y = entity.components.collision.boxTopLeft[1]; entity.collisionBoxTopRight.position.x = entity.components.collision.boxTopRight[0]; entity.collisionBoxTopRight.position.y = entity.components.collision.boxTopRight[1]; entity.collisionBoxBottomRight.position.x = entity.components.collision.boxBottomRight[0]; entity.collisionBoxBottomRight.position.y = entity.components.collision.boxBottomRight[1]; entity.collisionBoxBottomLeft.position.x = entity.components.collision.boxBottomLeft[0]; entity.collisionBoxBottomLeft.position.y = entity.components.collision.boxBottomLeft[1]; } entity.sprite.alpha = sprite.alpha; entity.sprite.position.x = position.value[0]; entity.sprite.position.y = position.value[1]; } postUpdate() { this.renderer.render(this.stage); } } module.exports = Renderer;
TypeScript
UTF-8
2,041
2.59375
3
[]
no_license
import { createPopper, Instance as Popper } from '@popperjs/core'; import { toHtml } from '../util/html'; const createInspector = () => { const element = document.createElement('div'); element.setAttribute("style", "background: white; padding: 10px; border-radius: 8px; box-shadow: 10px 10px solid black"); element.innerHTML = `Super Useful info`; document.body.appendChild(element); console.log(element) return element; } let hoveringElement: HTMLElement | null = null; let clickedElement: HTMLElement | null = null; let inspector: HTMLDivElement = createInspector(); let instance: Popper | null = null; const getData = (element: HTMLElement, type: 'data' | 'context') => { const ko: KnockoutStatic = (window as any)?.wrappedJSObject?.ko; if (typeof ko === "undefined") { console.log("Window doesn't appear to have knockout"); return; } const data = (ko as any)[`${type}For`](element); return data; } const logData = (element: HTMLElement, type: 'data' | 'context') => { console.log(getData(element, type)); } window.addEventListener('contextmenu', e => { clickedElement = e.target as HTMLElement; }); window.addEventListener('mousemove', e => { if (hoveringElement === e.target) return; const data = getData(e.target as any, 'data'); if (!data) return; console.log(data); if (hoveringElement) hoveringElement.setAttribute("style", ""); hoveringElement = e.target as any; if (!hoveringElement) return; hoveringElement.setAttribute("style", "outline: 1px solid red") if (instance) { instance.destroy(); } try { const html = toHtml(data); console.log(html) inspector.innerHTML = html; } catch (err) { console.trace(err) } instance = createPopper(hoveringElement, inspector); }) browser.runtime.onMessage.addListener((message) => { if (!message.type.startsWith("inspect-")) return; if (!clickedElement) return; logData(clickedElement, message.type.slice(8)); });
Java
UTF-8
1,089
2.25
2
[]
no_license
package com.kkb.cubemall.gateway.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CubemallCorsConfiguration { @Bean public CorsWebFilter corsWebFilter(){ CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); //可以携带cookie信息 config.addAllowedOriginPattern("*"); //允许所有的请求地址 访问 config.addAllowedHeader("*"); //允许携带所有的请求头信息 config.addAllowedMethod("*"); //允许所有的请求方式 get post put delete option UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); } }
C#
UTF-8
855
3.5625
4
[]
no_license
using System.IO; using System.Linq; namespace CodeevalChallenges { public class _37_Pangrams { public _37_Pangrams(string text) { this.text = text.ToLower(); } public string text { get; private set; } public char[] missingLetters() { int textLength = this.text.Length; char[] letters = new char[textLength]; using (StringReader sr = new StringReader(this.text)) { sr.Read(letters, 0, textLength); } int[] textCharCodes = (from i in letters select (int)i).ToArray(); int[] alphabetCodes = Enumerable.Range(97, 26).Select(x => x).ToArray(); return (from i in alphabetCodes where !textCharCodes.Contains(i) select (char)i).OrderBy(i=> i).ToArray(); } } }
Python
UTF-8
792
3.828125
4
[]
no_license
import datetime today = datetime.date.today(); print('today is ', today) from datetime import date, timedelta today = date.today() print('today is ', today) # 년도, 월, 일 출력 print('연도: ', today.year) print('월: ', today.month) print('일: ', today.day) # 날짜 계산 today = date.today() print('어제: ', today + timedelta(days=-1)) # 일주일전 print('일주일전: ', today + timedelta(days=7)) # 열흘 후 print('열흘 후: ', today + timedelta(days=10)) # 날짜 변환 (중요) # 1) date to string : strftime() from datetime import datetime today = datetime.today() print(today.strftime('%Y-%m-%d %H:%M')) # 2) string to date : strptime() from datetime import datetime strToday = '2021-05-10 10:30:30' print(datetime.strptime(strToday, '%Y-%m-%d %H:%M:%S'))
Java
UTF-8
1,426
2.71875
3
[]
no_license
package de.fub.bytecode.generic; import de.fub.bytecode.Constants; import de.fub.bytecode.ExceptionConstants; /** * Super class for the xRETURN family of instructions. * * @version $Id: ReturnInstruction.java,v 1.6 2001/07/03 08:20:18 dahm Exp $ * @author <A HREF="http://www.berlin.de/~markus.dahm/">M. Dahm</A> */ public abstract class ReturnInstruction extends Instruction implements ExceptionThrower, TypedInstruction, StackConsumer { /** * Empty constructor needed for the Class.newInstance() statement in * Instruction.readInstruction(). Not to be used otherwise. */ ReturnInstruction() {} /** * @param opcode of instruction */ protected ReturnInstruction(short opcode) { super(opcode, (short)1); } public Type getType() { switch(opcode) { case Constants.IRETURN: return Type.INT; case Constants.LRETURN: return Type.LONG; case Constants.FRETURN: return Type.FLOAT; case Constants.DRETURN: return Type.DOUBLE; case Constants.ARETURN: return Type.OBJECT; case Constants.RETURN: return Type.VOID; default: // Never reached throw new ClassGenException("Unknown type " + opcode); } } public Class[] getExceptions() { return new Class[] { ExceptionConstants.ILLEGAL_MONITOR_STATE }; } /** @return type associated with the instruction */ public Type getType(ConstantPoolGen cp) { return getType(); } }
Java
UTF-8
149
1.875
2
[]
no_license
public class Main { public static void main(String [] args){ //Starts an intance of UI that runs the program Ui.menu(); } }
Markdown
UTF-8
2,164
3.375
3
[]
no_license
# Hom Fried Rice Yes, it's spelled correctly! We learned a fried rice recipe from the Hom family, and this is basically hacks on that one. Ours makes use of an InstantPot, which makes rice cooking easy. Thank you, Homs! :D ## Prepare Rice The rice needs to be prepared ahead of time. It also needs to be cooked 'dry', so it won't stick to everything during the stir-fry. This is why it uses less water than rice that would simply be eaten. We like Jasmine or Basmati rice for this recipe, since it can be pressure-cooked dryer than a Japanese or Korean sticky rice, for example. | *ingredient* | *amount* | | --- | --- | | rice | 3 cups | | water | 2 1/2 cups (See below.) | 1. Rinse rice at least twice in the pot or **thoroughly** with a sieve. 1. Add water (See above.) 1. Place in InstantPot. 1. Run the Rice program (10 min high pressure.) 1. Quick-depressurize. 1. Fluff with a fork 1. Cover and set aside. ## Prepare Sauce Mix the following in a small bowl: | *ingredient* | *amount* | | --- | --- | | soy sauce | 3 tablespoons | | fish sauce | 2 tablespoons | | sesame oil | 1 tablespoon | ## Prepare Ingredients in a Bowl | *ingredient* | *amount* | *notes* | | --- | --- | --- | | eggs | ~5 | beaten | | onion (white or yellow) | 1/2 | chopped fine | | garlic | 1 tablespoon | minced | | ginger | 1 teaspoon | minced | ## Prepare More Ingredients | *ingredient* | *amount* | *notes* | | --- | --- | --- | | spam | 1 can | diced | | green onions | 1 cup | chopped | | corn kernels | 1 can or 2 cups | | | peanut oil | 3 tablespoons | Needed for cooking in the wok. | ## Optional | *ingredient* | *notes* | | --- | --- | | broccoli | pre-cooked | | bamboo shoots | canned | | mini-corn | canned | ## Go for a Wok! 1. Heat the wok on a **high** heat. 1. Add peanut oil to the wok and spread around. 1. Get it **HOT**, or everything will stick to your wok. 1. Add the spam cubes. 1. Fry until browned. 1. Add bowl with eggs, garlic, onions, ginger. 1. Fry until eggs are almost, not quite done. 1. Add rice. 1. Fry until it's crisped up to your taste. 1. Add green onions and corn. 1. Stir it up well. 1. Crisp it a little more. 1. Done.
Python
UTF-8
4,182
3.328125
3
[]
no_license
import re import pprint from sys import argv def syntaxCheck(jsonString): if jsonString[0] != '{' or jsonString[-1] != '}': return False return bracketsMatch(jsonString) # check if all open brackets/braces have a corresponding close character def bracketsMatch(string): bracketStack = [] braceStack = [] balanced = True i = 0 while i<len(string) and balanced: char = string[i] if char == "[": bracketStack.append(char) elif char == "{": braceStack.append(char) elif char == "]": if len(bracketStack) == 0: print("Bad \"]\" at char " + str(i)) else: bracketStack.pop() elif char == "}": if len(braceStack) == 0: print("Bad \"}\" at char " + str(i)) else: braceStack.pop() i+=1 err = "" if len(bracketStack) != 0: err += str(len(bracketStack)) + " extra brackets found.\n" if len(braceStack) != 0: err += str(len(braceStack)) + " extra braces found.\n" if err != "": print(err) return balanced and err == "" def tokenize(string): return list(filter(None, re.split(r"([\{\}\[\]\",:])", string))) # Split on any viable token, then remove empty strings from list # Reconnects string tokens that were split during tokanization def fixEscapedStrings(tokens): tokensIter = iter(tokens) newTokens = [] while True: try: token = next(tokensIter) except StopIteration: return newTokens if token not in ["\"", "'"]: newTokens.append(token) continue stringToken = "" quoteType = token lastChar = token[-1] while True: try: token = next(tokensIter) except StopIteration: print("Unmatched quote found. Exiting.") quit() if token != quoteType: lastChar = token[-1] stringToken += token continue if lastChar == "\\": lastChar = token[-1] stringToken += token continue newTokens.append(stringToken) break def parseObject(tokensIter): token = None jsonDict = {} key = "" haveKey = False while True: try: lastToken = token token = next(tokensIter) except StopIteration: return jsonDict if token == "}": return jsonDict if token == ":": key = lastToken haveKey = True if haveKey: jsonDict[key] = parseValue(tokensIter) haveKey = False; def parseArray(tokensIter): jsonList = [] lastToken = "," while True: if lastToken == ",": jsonList.append(parseValue(tokensIter)) try: token = next(tokensIter) except StopIteration: return jsonList if token == "]": return jsonList def parseValue(tokensIter): while True: try: token = next(tokensIter) except StopIteration: print("Something went wrong in value parsing: " + str(list(tokensIter))) quit() # Null if token == "null": return None # Boolean if token in ["true", "false"]: return token == "true" # Array if token == "[": return parseArray(tokensIter) # Object if token == "{": return parseObject(tokensIter) # Number if isInt(token): return int(token) elif isFloat(token): return float(token) # String return token def isInt(string): try: int(string) return True except ValueError: return False def isFloat(string): try: float(string) return True except ValueError: return False def parseJSON(string): return parseValue(iter(fixEscapedStrings(tokenize(string)))) if __name__ == "__main__": # Only run code if the script is being called directly, not if it's imported if len(argv) > 2: print("Incorrect number of arguments. Pass one file to parse it, or none to parse demo YouTube API JSON response file (\"File.json\")") quit() inputFile = argv[1] if len(argv) == 2 else "File.json" with open(inputFile, 'r') as file: jsonString = re.sub(r"\s+", '', file.read()) # load the file into a string and strip whitespace pp = pprint.PrettyPrinter(indent=4) # For better dict formatting if syntaxCheck(jsonString): print("Parsed JSON:") pp.pprint(parseJSON(jsonString)) else: print("Bad syntax in file. Exiting")
Python
UTF-8
1,487
2.703125
3
[]
no_license
import pygame, random from componentes import Grid, Snake, Tempo, Pontos, Comida cor_de_fundo = (100, 100, 100) azul_claro = (130, 180, 200) amarelo = (255, 255, 0) preto = (0, 0, 0) verde = (20, 110, 20) largura = 620 altura = 680 grid_tam = (600, 600) pos_grid = (10, 70) cel_tam = (15, 15) info_tam = (200, 50) pos_tmp =(10, 10) pos_pnt = (410, 10) var_comida_x = (10, 600) var_comida_y = (70, 600) UP = (0, -15) DOWN = (0, 15) LEFT = (-15, 0) RIGHT = (15, 0) def cria_janela(nome, tamanho): janela = pygame.display.set_mode(tamanho) pygame.display.set_caption(nome) janela.fill(cor_de_fundo) return(janela) pygame.init() tela = cria_janela("Snake", (largura, altura)) pygame.display.flip() tempo = pygame.time.Clock() rodar = True grid = Grid(tela, pos_grid) tmp = Tempo(tela, pos_tmp) pontos = Pontos(0, tela, pos_pnt) cobra = Snake(tela, 310, 370, pontos) comida = Comida() while (rodar): tela.fill(cor_de_fundo) for evento in pygame.event.get(): if (evento.type == pygame.QUIT): rodar = False press = pygame.key.get_pressed() if (press[pygame.K_LEFT]): cobra.anda(LEFT) if (press[pygame.K_RIGHT]): cobra.anda(RIGHT) if (press[pygame.K_UP]): cobra.anda(UP) if (press[pygame.K_DOWN]): cobra.anda(DOWN) if cobra.comeu(comida): comida.renova() cobra.anda(cobra.direcao) grid.desenhaGrid(comida.pos) cobra.apresenta() tmp.atualiza() tmp.apresenta() pontos.apresenta() tempo.tick(10) pygame.display.update() pygame.quit()
Python
UTF-8
1,185
3.328125
3
[]
no_license
# Support Vector Regression (SVR) # Importing the libraries from sklearn.metrics import r2_score from sklearn.svm import SVR from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('practice2/Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, -1].values y = y.reshape(len(y), 1) # Splitting the dataset into the Training set and Test set X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=0) # Feature Scaling sc_X = StandardScaler() sc_y = StandardScaler() X_train = sc_X.fit_transform(X_train) y_train = sc_y.fit_transform(y_train) # Training the SVR model on the Training set regressor = SVR(kernel='rbf') regressor.fit(X_train, y_train) # Predicting the Test set results y_pred = sc_y.inverse_transform(regressor.predict(sc_X.transform(X_test))) np.set_printoptions(precision=2) print(np.concatenate((y_pred.reshape(len(y_pred), 1), y_test.reshape(len(y_test), 1)), 1)) # Evaluating the Model Performance print(r2_score(y_test, y_pred)) # 0.9480784049986258
Python
UTF-8
1,401
3.1875
3
[]
no_license
#!/usr/bin/env python # import required modules: # import os import sys import string def dups(A): current = [] counter = 0 while True: maxbank = max(A) maxind = A.index(maxbank) A[maxind] = 0 while maxbank > 0: # Check if maxind == len(A)-1: A[0] += 1 else: A[maxind+1] += 1 maxbank -= 1 maxind = (maxind+1) % len(A) #print A #print maxbank #print A # use A[:] since we need to pass a copy # of the list current.append(A[:]) #print current tempcur = map(tuple, current) counter += 1 #print tempcur #print set(tempcur) if len(tempcur) != len(set(tempcur)): # Here is where part 2 begins # starting from a state that has already been seen, # how many block redistribution cycles must be performed # before that same state is seen again? return counter, A, len(current)- 1 - current.index(A) # main function # def main(argv): mytest = [0, 2, 7, 0] mylist = [5,1,10,0,1,7,13,14,3,12,8,10,7,12,0,6] print dups(mylist) # Exit gracefully # return # Begin gracefully # if __name__ == "__main__": main(sys.argv[0:]) # # End of file
C++
UTF-8
6,064
2.953125
3
[]
no_license
#include "utils.h" size_t nearestTwoPower(size_t num) { size_t ones_count = 0; size_t count = 0; while (num) { ones_count += num & 1; ++count; num >>= 1; } if (ones_count == 1) return count - 1; return count; } void recursiveStrassen( double *A, double *B, double *C, int lda, int ldb, int ldc, int N, int depth ) { if (N <= 8) { matrixMul(A, B, C, lda, ldb, ldc, N, N, N, N ,N, N, 1, 0); return; } int XA2 = N / 2; int XB2 = N / 2; int XC2 = N / 2; int YA2 = N / 2; int YB2 = N / 2; int YC2 = N / 2; double *W_1, *W_2; int lw1 = XA2; int lw2 = XB2; W_1 = (double*)malloc(lw1 * YA2 * sizeof(double)); W_2 = (double*)malloc(lw2 * YB2 * sizeof(double)); int dXA = XA2; int dYA = YA2 * lda; int dXB = XB2; int dYB = YB2 * ldb; int dXC = XC2; int dYC = YC2 * ldc; double *A11, *A12, *A21, *A22; double *B11, *B12, *B21, *B22; double *C11, *C12, *C21, *C22; A11 = A; A12 = A + dXA; A21 = A + dYA; A22 = A + dXA + dYA; B11 = B; B12 = B + dXB; B21 = B + dYB; B22 = B + dXB + dYB; C11 = C; C12 = C + dXC; C21 = C + dYC; C22 = C + dXC + dYC; if (depth <= 1) { matrixAdd(A11, A21, W_1, lda, lda, lw1, XA2, YA2, 1.0, -1.0); // W_1 = A11 - A21 matrixAdd(B22, B12, W_2, ldb, ldb, lw2, XB2, YB2, 1.0, -1.0); // W_2 = B22 - B12 matrixMul(W_1, W_2, C21, lw1, lw2, ldc, XA2, XB2, XC2, YA2, YB2, YC2, 1.0, 0.0); // C21 = W_1 * W_2 matrixAdd(A21, A22, W_1, lda, lda, lw1, XA2, YA2, 1.0, 1.0); // W_1 = A21 + A22 matrixAdd(B12, B11, W_2, ldb, ldb, lw2, XB2, YB2, 1.0, -1.0); // W_2 = B12 - B11 matrixMul(W_1, W_2, C22, lw1, lw2, ldc, XA2, XB2, XC2, YA2, YB2, YC2, 1.0, 0.0); // C22 = W_1 * W_2 matrixAdd(W_1, A11, W_1, lw1, lda, lw1, XA2, YA2, 1.0, -1.0); // W_1 = W_1- A11 matrixAdd(B22, W_2, W_2, ldb, lw2, lw2, XB2, YB2, 1.0, -1.0); // W_2 = B22 - W_2 matrixMul(W_1, W_2, C11, lw1, lw2, ldc, XA2, XB2, XC2, YA2, YB2, YC2, 1.0, 0.0); // C11 = W_1 * W_2 matrixAdd(A12, W_1, W_1, lda, lw1, lw1, XA2, YA2, 1.0, -1.0); // W_1 = A12 - W_1 matrixMul(W_1, B22, C12, lw1, ldb, ldc, XA2, XB2, XC2, YA2, YB2, YC2, 1.0, 0.0); // C12 = W_1 * B22 matrixAdd(C22, C12, C12, ldc, ldc, ldc, XC2, YC2, 1.0, 1.0); // C12 = C22 + C12 matrixMul(A11, B11, W_1, lda, ldb, lw1, XA2, XB2, XC2, YA2, YB2, YC2, 1.0, 0.0); // W_1= A11 * B11 matrixAdd(W_1, C11, C11, lw1, ldc, ldc, XC2, YC2, 1.0, 1.0); // C11 = W_1 + C11 matrixAdd(C11, C12, C12, ldc, ldc, ldc, XC2, YC2, 1.0, 1.0); // C12 = C11 + C12 matrixAdd(C11, C21, C11, ldc, ldc, ldc, XC2, YC2, 1.0, 1.0); // C11 = C11 + C21 matrixAdd(W_2, B21, W_2, lw2, ldb, lw2, XB2, YB2, 1.0, -1.0); // W_2 = W_2- B21 matrixMul(A22, W_2, C21, lda, lw2, ldc, XA2, XB2, XC2, YA2, YB2, YC2, 1.0, 0.0); // C21 = A22 * W_2 matrixAdd(C11, C21, C21, ldc, ldc, ldc, XC2, YC2, 1.0, -1.0); // C11 = C11 - C21 matrixAdd(C11, C22, C22, ldc, ldc, ldc, XC2, YC2, 1.0, 1.0); // C22 = C11 + C22 matrixMul(A12, B21, C11, lda, ldb, ldc, XA2, XB2, XC2, YA2, YB2, YC2, 1.0, 0.0); // C11 = A12 * B21 matrixAdd(W_1, C11, C11, lw1, ldc, ldc, XC2, YC2, 1.0, 1.0); // C11 = W_1+ C11 } else { matrixAdd(A11, A21, W_1, lda, lda, lw1, XA2, YA2, 1.0, -1.0); // W_1 = A11 - A21 matrixAdd(B22, B12, W_2, ldb, ldb, lw2, XB2, YB2, 1.0, -1.0); // W_2 = B22 - B12 recursiveStrassen(W_1, W_2, C21, lw1, lw2, ldc, N / 2, depth - 1); matrixAdd(A21, A22, W_1, lda, lda, lw1, XA2, YA2, 1.0, 1.0); // W_1 = A21 + A22 matrixAdd(B12, B11, W_2, ldb, ldb, lw2, XB2, YB2, 1.0, -1.0); // W_2 = B12 - B11 recursiveStrassen(W_1, W_2, C22, lw1, lw2, ldc,N / 2, depth - 1); matrixAdd(W_1, A11, W_1, lw1, lda, lw1, XA2, YA2, 1.0, -1.0); // W_1 = W_1- A11 matrixAdd(B22, W_2, W_2, ldb, lw2, lw2, XB2, YB2, 1.0, -1.0); // W_2 = B22 - W_2 recursiveStrassen(W_1, W_2, C11, lw1, lw2, ldc,N / 2, depth - 1); matrixAdd(A12, W_1, W_1, lda, lw1, lw1, XA2, YA2, 1.0, -1.0); // W_1 = A12 - W_1 recursiveStrassen(W_1, B22, C12, lw1, ldb, ldc, N / 2, depth - 1); matrixAdd(C22, C12, C12, ldc, ldc, ldc, XC2, YC2, 1.0, 1.0); // C12 = C22 + C12 recursiveStrassen(A11, B11, W_1, lda, ldb, lw1, N / 2, depth - 1); matrixAdd(W_1, C11, C11, lw1, ldc, ldc, XC2, YC2, 1.0, 1.0); // C11 = W_1 + C11 matrixAdd(C11, C12, C12, ldc, ldc, ldc, XC2, YC2, 1.0, 1.0); // C12 = C11 + C12 matrixAdd(C11, C21, C11, ldc, ldc, ldc, XC2, YC2, 1.0, 1.0); // C11 = C11 + C21 matrixAdd(W_2, B21, W_2, lw2, ldb, lw2, XB2, YB2, 1.0, -1.0); // W_2 = W_2- B21 recursiveStrassen(A22, W_2, C21, lda, lw2, ldc, N / 2, depth - 1); matrixAdd(C11, C21, C21, ldc, ldc, ldc, XC2, YC2, 1.0, -1.0); // C11 = C11 - C21 matrixAdd(C11, C22, C22, ldc, ldc, ldc, XC2, YC2, 1.0, 1.0); // C22 = C11 + C22 recursiveStrassen(A12, B21, C11, lda, ldb, ldc, N / 2, depth - 1); matrixAdd(W_1, C11, C11, lw1, ldc, ldc, XC2, YC2, 1.0, 1.0); // C11 = W_1+ C11 } free(W_1); free(W_2); } void strassen_mm( const double *A, const double *B, double *C, size_t m, size_t k, size_t n, size_t level_num ) { double* A_square; double* B_square; double* C_square; size_t levels = nearestTwoPower(std::max(std::max(m, k), n)); size_t N = 1 << levels; size_t mem_size = sizeof(double) * N * N; A_square = (double*)malloc(mem_size); B_square = (double*)malloc(mem_size); C_square = (double*)malloc(mem_size); for (size_t i = 0; i < N; ++i) { for (size_t j = 0; j < N; ++j) { if (i < m && j < k) { A_square[i * N + j] = A[i * k + j]; } else { A_square[i * N + j] = 0; } if (i < k && j < n) { B_square[i * N + j] = B[i * n + j]; } else { B_square[i * N + j] = 0; } } } recursiveStrassen(A_square, B_square, C_square, N, N, N, N, level_num); for (size_t i = 0; i < m; ++i) { for (size_t j = 0; j < n; ++j) { C[i * n + j] = C_square[i * N + j]; } } free(A_square); free(B_square); free(C_square); }
TypeScript
UTF-8
445
2.515625
3
[]
no_license
import { LazyExoticComponent, ComponentType, ReactNode } from 'react'; interface IExtraProps { [key: string]: any; } export interface IRoute { path: string; component?: LazyExoticComponent<ComponentType<any>>; componentExtraProps?: IExtraProps; // Preloader for lazy loading fallback?: NonNullable<ReactNode> | null; // Redirect path redirect?: string; // Sub routes routes?: IRoute[]; exact?: boolean; params?: any; }
Java
UTF-8
894
2.203125
2
[]
no_license
package com.example.ilijaangeleski.flixbus.model; import com.google.gson.annotations.SerializedName; import java.io.Serializable; /** * Created by Ilija Angeleski on 2/1/2018. */ public class Departures implements Serializable{ @SerializedName("direction") private String direction; @SerializedName("line_code") private String line_code; @SerializedName("datetime") private DateTime dateTime; public String getDirection() { return direction; } public void setDirection(String direction) { this.direction = direction; } public String getLine_code() { return line_code; } public void setLine_code(String line_code) { this.line_code = line_code; } public DateTime getDateTime() { return dateTime; } public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } }
C++
UTF-8
1,376
3.203125
3
[]
no_license
class car_conf //configuratioin of car {public: double x; double y; double theta; void setValue(double a, double b, double c) { x=a; y=b; theta=c; } }; class car_steering //drive with speed v and steering angle phi from one configuration to another {public: double v; double phi; void setValue(double a, double b) { v=a; phi=b; } }; class node {public: int ID;//its own index in the vector<node>map int father_ID;//its father's index in the vector<node>map car_conf conf; car_steering v_dir;//the velocity and steering angle that its previous node(i.e., its father node) uses to //get to the current node(i.e., child node (itself)) void setValue(int ID, int father_ID,car_conf conf,car_steering v_dir) { this->ID=ID; this->father_ID=father_ID; this->conf=conf; this->v_dir=v_dir; } bool equal(node compare_node) { if(compare_node.ID==this->ID) return true; return false; } }; class obstacles {public: double x0; double y0; double x1; double y1; void setValue(double x0,double y0,double x1,double y1) { this->x0=x0; this->y0=y0; this->x1=x1; this->y1=y1; } }; class vect//vector {public: double x; double y; void setValue(double x,double y) { this->x=x; this->y=y; } }; class point//point {public: double x; double y; void setValue(double x,double y) { this->x=x; this->y=y; } };
Markdown
UTF-8
3,219
3.109375
3
[]
no_license
# ASSIGNMENT 03 (updated): Introduction to Computational Media **DUE:** 27 September 2018, 6:00 PM ## Brief NOTE: As part of a bit of course restructuring, we are going to focus the next couple weeks on establishing a base level of computational literacy. As part of this effort, you will be assigned a "playlist" of videos to watch before coming to class so we can work together in class to discuss our learnings and questions and make amazing things together. ### P5.js Introduction P5.js is a library written in javascript that makes creating interactive and visual things (like data visuals!) possible in the web browser. P5.js was inspired by the programming environment Processing which aimed to make coding and computation more accessible to artists, designers (hey that's us!), and people not traditionally represented in the computational world. The idea was to allow artists and designers to build their own tools. This week your task is to do 2 things: 1. Write a short paragraph about your master's research interests and write out how you might apply computation to furthering your research goals. If you have come across any datasets that are of interest, please note them down. If you might be interested to collect data, write down what you would be interested to collect and why. Note down also why you are particularly interested or not interested in coding. 2. Watch the following videos and follow along with Dan Shiffman as he takes you through introducing p5.js, setting up an account on the p5.js web editor, and introducing you to your very first experiences with programming. Total: `~1hr 30 min` (sorry no netflix tonight!) * [Code! Programming for Beginners with p5.js](https://www.youtube.com/watch?v=yPWkPOfnGsw) | 13 min * [Introduction to the p5 web editor](https://www.youtube.com/watch?v=MXs1cOlidWs) | 8 min * [Shapes & Drawing](https://www.youtube.com/watch?v=c3TeLi6Ns1E) | 25 min * [Errors & Console](https://www.youtube.com/watch?v=LuGsp5KeJMM) | 6 min * [Code Comments](https://www.youtube.com/watch?v=xJcrPJuem5Q) | 4 min * [Variables in P5.js (mouseX, mouseY)](https://www.youtube.com/watch?v=RnS0YNuLfQQ) | 12 min * [Variables in p5.js (Make your own) - p5.js Tutorial](https://www.youtube.com/watch?v=Bn_B3T_Vbxs) | 12 min If you find yourself needing some more inspiration, here's a few talks and examples that I've always found to motivate my learning: * Lauren McCarthy, OpenVis Conf, [LEARNING WHILE MAKING P5 JS Lauren McCarthy](https://youtu.be/1k3X4DLDHdc?t=16m16s) * Casey Reas, [How To Draw With Code | Casey Reas](https://www.youtube.com/watch?v=_8DMEHxOLQE) * [The gap by Ira Glass](https://vimeo.com/85040589) * [Will Geary | 24 hours of buses in NYC](http://gothamist.com/2017/04/05/soothing_taxi_video.php) * [City Flows](https://vimeo.com/173760057) ## Deliverables 1. Short blog post on "How does computation and data visualization relate to your research interests?" 2. Bring your questions and be ready on Thursday to make some p5.js sketches in class on Thursday. ## Submission * #1 Submit your work here: https://github.com/sva-dsi/2018-fall-course/issues/12 * #2 Submit any questions about p5.js you have here: https://github.com/sva-dsi/2018-fall-course/issues
C#
UTF-8
1,328
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL { public class BikeInfoServer { public static object MakeCard(string icno, string bikeno, string bikeowername, string bikeowertel, string bikeoweraddr, System.DateTime icstatetime, System.DateTime icexpiretime,string icstate,string bikePhoto,string userName) { string sql = string.Format("INSERT INTO BikeInfo (icNo, bikeNo,bikeOwerName,bikeOwerTel,bikeOwerAddr,icStateTime,icExpireTime,icState,bikePhoto,userName) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')", icno, bikeno, bikeowername, bikeowertel, bikeoweraddr, icstatetime, icexpiretime,icstate,bikePhoto,userName); return (int)DBHelper.ExecuteNonQuery(sql); } public static SqlDataReader getDataReader(string icno) { string sql = string.Format("Select bikeNo,bikePhoto from BikeInfo where icNo='{0}'", icno); return DBHelper.executeReader(sql); } public static SqlDataReader getType(string icno) { string sql = string.Format("Select spaceType from SpaceInfo where ICCardNo='{0}'", icno); return DBHelper.executeReader(sql); } } }
TypeScript
UTF-8
522
3.1875
3
[ "MIT" ]
permissive
import * as test from 'tape'; import cache from '../cache'; test("cache", async t => { const key = "1"; const value = "test"; await cache.setKey(key, value); const result = await cache.getKey<string>(key); t.equal(result, value); t.end(); }) test("clone", async t => { type TestObj = { desc: string }; let obj = { desc: "test" }; cache.setKey("1", obj); obj.desc = "test2"; const result = await cache.getKey<TestObj>("1"); t.equal(result.desc, 'test'); t.end(); });
Java
UTF-8
274
1.6875
2
[ "MIT" ]
permissive
package com.drive.admin.repository; import com.drive.common.core.biz.ResObject; /** * 测试分布式事务 */ public interface AccountRepository { /** * 添加金额 * @param account * @return */ ResObject increaseAmount(String account); }
Java
UTF-8
8,942
1.648438
2
[]
no_license
package Netspan.NBI_14_0.API.Status; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for GpsStatus complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="GpsStatus"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="NodeId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Longitude" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Latitude" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Height" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="TrackedSatellites" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="VisibleSatellites" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="GpsComms" type="{http://Airspan.Netspan.WebServices}TrapStatusGpsComms"/> * &lt;element name="GpsLock" type="{http://Airspan.Netspan.WebServices}TrapStatusGpsLock"/> * &lt;element name="GpsSnr" type="{http://Airspan.Netspan.WebServices}TrapStatusGpsSnr"/> * &lt;element name="Satellite" type="{http://Airspan.Netspan.WebServices}Satellite" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "GpsStatus", propOrder = { "name", "nodeId", "longitude", "latitude", "height", "trackedSatellites", "visibleSatellites", "gpsComms", "gpsLock", "gpsSnr", "satellite" }) public class GpsStatus { @XmlElement(name = "Name") protected String name; @XmlElement(name = "NodeId") protected String nodeId; @XmlElement(name = "Longitude") protected String longitude; @XmlElement(name = "Latitude") protected String latitude; @XmlElement(name = "Height") protected String height; @XmlElement(name = "TrackedSatellites", required = true, type = Integer.class, nillable = true) protected Integer trackedSatellites; @XmlElement(name = "VisibleSatellites", required = true, type = Integer.class, nillable = true) protected Integer visibleSatellites; @XmlElement(name = "GpsComms", required = true, nillable = true) @XmlSchemaType(name = "string") protected TrapStatusGpsComms gpsComms; @XmlElement(name = "GpsLock", required = true, nillable = true) @XmlSchemaType(name = "string") protected TrapStatusGpsLock gpsLock; @XmlElement(name = "GpsSnr", required = true, nillable = true) @XmlSchemaType(name = "string") protected TrapStatusGpsSnr gpsSnr; @XmlElement(name = "Satellite") protected List<Satellite> satellite; /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the nodeId property. * * @return * possible object is * {@link String } * */ public String getNodeId() { return nodeId; } /** * Sets the value of the nodeId property. * * @param value * allowed object is * {@link String } * */ public void setNodeId(String value) { this.nodeId = value; } /** * Gets the value of the longitude property. * * @return * possible object is * {@link String } * */ public String getLongitude() { return longitude; } /** * Sets the value of the longitude property. * * @param value * allowed object is * {@link String } * */ public void setLongitude(String value) { this.longitude = value; } /** * Gets the value of the latitude property. * * @return * possible object is * {@link String } * */ public String getLatitude() { return latitude; } /** * Sets the value of the latitude property. * * @param value * allowed object is * {@link String } * */ public void setLatitude(String value) { this.latitude = value; } /** * Gets the value of the height property. * * @return * possible object is * {@link String } * */ public String getHeight() { return height; } /** * Sets the value of the height property. * * @param value * allowed object is * {@link String } * */ public void setHeight(String value) { this.height = value; } /** * Gets the value of the trackedSatellites property. * * @return * possible object is * {@link Integer } * */ public Integer getTrackedSatellites() { return trackedSatellites; } /** * Sets the value of the trackedSatellites property. * * @param value * allowed object is * {@link Integer } * */ public void setTrackedSatellites(Integer value) { this.trackedSatellites = value; } /** * Gets the value of the visibleSatellites property. * * @return * possible object is * {@link Integer } * */ public Integer getVisibleSatellites() { return visibleSatellites; } /** * Sets the value of the visibleSatellites property. * * @param value * allowed object is * {@link Integer } * */ public void setVisibleSatellites(Integer value) { this.visibleSatellites = value; } /** * Gets the value of the gpsComms property. * * @return * possible object is * {@link TrapStatusGpsComms } * */ public TrapStatusGpsComms getGpsComms() { return gpsComms; } /** * Sets the value of the gpsComms property. * * @param value * allowed object is * {@link TrapStatusGpsComms } * */ public void setGpsComms(TrapStatusGpsComms value) { this.gpsComms = value; } /** * Gets the value of the gpsLock property. * * @return * possible object is * {@link TrapStatusGpsLock } * */ public TrapStatusGpsLock getGpsLock() { return gpsLock; } /** * Sets the value of the gpsLock property. * * @param value * allowed object is * {@link TrapStatusGpsLock } * */ public void setGpsLock(TrapStatusGpsLock value) { this.gpsLock = value; } /** * Gets the value of the gpsSnr property. * * @return * possible object is * {@link TrapStatusGpsSnr } * */ public TrapStatusGpsSnr getGpsSnr() { return gpsSnr; } /** * Sets the value of the gpsSnr property. * * @param value * allowed object is * {@link TrapStatusGpsSnr } * */ public void setGpsSnr(TrapStatusGpsSnr value) { this.gpsSnr = value; } /** * Gets the value of the satellite property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the satellite property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSatellite().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Satellite } * * */ public List<Satellite> getSatellite() { if (satellite == null) { satellite = new ArrayList<Satellite>(); } return this.satellite; } }
Python
UTF-8
163
3.328125
3
[]
no_license
#! /usr/bin/env python3 def int_to_string(int): return chr(int) if __name__ == "__main__": a = 65 print(a) a = chr(a) print(a)
Java
UTF-8
7,030
2.125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package GUI; import javafx.application.Platform; import javafx.beans.property.IntegerProperty; import javafx.beans.property.ListProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleListProperty; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Insets; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.KeyCode; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import DB.Coffee; import DB.CoffeeDao; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Optional; import java.util.ResourceBundle; public class FormTableController implements Initializable { static Optional<Coffee> showAndWait(Stage stage) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @FXML private TableView<Coffee> tablecoffee; @FXML private TableColumn<Coffee, String> columnkodepbl; @FXML private TableColumn<Coffee, String> columnnamapbl; @FXML private TableColumn<Coffee, String> columnnamabrg; @FXML private TableColumn<Coffee, String> columnhargabrg; @FXML private TextField txtfilter; @FXML private Button btndelete; @FXML private Button btnfilter; @FXML private Button btnInput; private CoffeeDao dao; private ListProperty<Coffee> coffee; String filter; // primary stage, untuk dikirim ke form input sebagai parent window private Stage stage; public FormTableController(CoffeeDao dao, Stage stage) { this.dao = dao; this.stage = stage; } @Override public void initialize(URL url, ResourceBundle resourceBundle) { // load semua data mahasiswa try { coffee.addAll(dao.all()); } catch (SQLException e) { e.printStackTrace(); } coffee = new SimpleListProperty<>(FXCollections.observableArrayList()); tablecoffee.itemsProperty().bind(coffee); columnkodepbl.setCellValueFactory(new PropertyValueFactory<>("kodepbl")); columnnamapbl.setCellValueFactory(new PropertyValueFactory<>("namapbl")); columnnamabrg.setCellValueFactory(new PropertyValueFactory<>("namabrg")); columnhargabrg.setCellValueFactory(new PropertyValueFactory<>("hargabrg")); btnfilter.setOnAction(event -> { filter = txtfilter.getText(); coffee.clear(); try { // cari by nim Integer.parseInt(filter); runSQL(() -> coffee.addAll(dao.findBykodepbl(filter))); } catch (NumberFormatException e) { runSQL(() -> coffee.addAll(dao.findBynamapbl(filter))); } }); tablecoffee.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.DELETE) { runSQL(() -> dao.delete(tablecoffee.getSelectionModel().getSelectedItem())); coffee.clear(); } }); btndelete.setOnAction(event -> { // buat dialog Coffee m = inputDataCoffee(new Coffee("", "", "", ""), false).orElse(null); }); btnInput.setOnAction(event -> { this.stage.close(); }); tablecoffee.setOnMouseClicked(event -> { if (event.getClickCount() == 2) { Coffee m = inputDataCoffee(tablecoffee.getSelectionModel().getSelectedItem(), true).orElse(null); } }); } private Optional<Coffee> inputDataCoffee(Coffee coffee, boolean edit) { Dialog<Coffee> dialog = new Dialog<>(); dialog.setTitle("Input Data Coffee"); // Set the button types. ButtonType okButtonType = new ButtonType("Simpan", ButtonBar.ButtonData.OK_DONE); dialog.getDialogPane().getButtonTypes().addAll(okButtonType, ButtonType.CANCEL); // Create the username and password labels and fields. GridPane grid = new GridPane(); grid.setHgap(10); grid.setVgap(10); grid.setPadding(new Insets(20, 150, 10, 10)); TextField kodepbl = new TextField(); kodepbl.setPromptText("kodepbl"); kodepbl.setText(coffee.getKodepbl()); if (edit) { kodepbl.setDisable(true); } TextField namapbl = new TextField(); namapbl.setPromptText("namapbl"); namapbl.setText(coffee.getNamapbl()); TextField namabrg = new TextField(); namabrg.setPromptText("namabrg"); namabrg.setText(coffee.getNamabrg()); TextField hargabrg = new TextField(); hargabrg.setPromptText("hargabrg"); hargabrg.setText(coffee.getHargabrg()); grid.add(new Label("Kode Pembelian:"), 0, 0); grid.add(kodepbl, 1, 0); grid.add(new Label("Nama Pembeli:"), 0, 1); grid.add(namapbl, 1, 1); grid.add(new Label("Nama Barang:"), 0, 1); grid.add(namabrg, 1, 1); grid.add(new Label("Harga Barang:"), 0, 1); grid.add(hargabrg, 1, 1); dialog.getDialogPane().setContent(grid); // Request focus on the username field by default. Platform.runLater(kodepbl::requestFocus); // Convert the result to a username-password-pair when the login button is clicked. dialog.setResultConverter(dialogButton -> { if (dialogButton == okButtonType) { return new Coffee(kodepbl.getText(), namapbl.getText(), namabrg.getText(), hargabrg.getText()); } return null; }); Optional<Coffee> result = dialog.showAndWait(); return result; } private void runSQL(SQLAction action) { try { action.run(); } catch (SQLException e) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("SQL Error"); alert.setContentText(e.getMessage()); alert.showAndWait(); } } } @FunctionalInterface interface SQLAction { void run() throws SQLException; }
Python
UTF-8
76
3.171875
3
[]
no_license
name = "gReElEy" print(name.upper()) print(name.lower()) print(name.title())
JavaScript
UTF-8
1,205
3.421875
3
[]
no_license
const { expect } = require('chai'); const Obstacle = require('../lib/Obstacle.js'); describe('Obstacle', () => { let obstacle; beforeEach(() => { obstacle = new Obstacle(); }); it('should have an x property that defaults to 700', () => { expect(obstacle.x).to.equal(700); }); it('should have a y property that defaults to 0', () => { expect(obstacle.y).to.equal(0); }); it('should have a width property that defaults to 100', () => { expect(obstacle.width).to.equal(100); }); it('should have a height property that defaults to 225', () => { expect(obstacle.height).to.equal(225); }); it('should be able to move when passed an object as an argument', () => { obstacle.move({ x: -3, y: 0 }); expect(obstacle.x).to.equal(697); expect(obstacle.y).to.equal(0); }); }); describe('Obstacle arguments', () => { let obstacle; beforeEach(() => { obstacle = new Obstacle(10, 20, 50, 60); }); it('should accept arguments for x, y, width, and height properties', () => { expect(obstacle.x).to.equal(10); expect(obstacle.y).to.equal(20); expect(obstacle.width).to.equal(50); expect(obstacle.height).to.equal(60); }); });
Java
UTF-8
2,117
1.96875
2
[]
no_license
package org.triplea.game.server; import static com.google.common.base.Preconditions.checkNotNull; import static games.strategy.engine.framework.CliProperties.LOBBY_URI; import games.strategy.engine.framework.startup.LobbyWatcherThread; import games.strategy.engine.framework.startup.login.ClientLoginValidator; import games.strategy.engine.framework.startup.mc.ServerModel; import games.strategy.engine.framework.startup.ui.panels.main.game.selector.GameSelectorModel; import java.util.Optional; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import lombok.extern.java.Log; import org.triplea.game.startup.ServerSetupModel; import org.triplea.http.client.lobby.game.hosting.request.GameHostingResponse; /** Setup panel model for headless server. */ @RequiredArgsConstructor(access = AccessLevel.PACKAGE) @Log public class HeadlessServerSetupPanelModel implements ServerSetupModel { private final GameSelectorModel gameSelectorModel; private HeadlessServerSetup headlessServerSetup; @Override public void showSelectType() { new ServerModel(gameSelectorModel, this, null, new HeadlessLaunchAction(), log::severe); } @Override public void onServerMessengerCreated( final ServerModel serverModel, final GameHostingResponse gameHostingResponse) { checkNotNull(gameHostingResponse, "hosting response is null, did the bot connect to lobby?"); checkNotNull(System.getProperty(LOBBY_URI)); Optional.ofNullable(headlessServerSetup).ifPresent(HeadlessServerSetup::cancel); final ClientLoginValidator loginValidator = new ClientLoginValidator(); loginValidator.setServerMessenger(checkNotNull(serverModel.getMessenger())); serverModel.getMessenger().setLoginValidator(loginValidator); Optional.ofNullable(serverModel.getLobbyWatcherThread()) .map(LobbyWatcherThread::getLobbyWatcher) .ifPresent(lobbyWatcher -> lobbyWatcher.setGameSelectorModel(gameSelectorModel)); headlessServerSetup = new HeadlessServerSetup(serverModel, gameSelectorModel); } public HeadlessServerSetup getPanel() { return headlessServerSetup; } }
Java
UTF-8
196
2.125
2
[]
no_license
package decorator; /** * Created with Intellij IDEA. * Description: * User: baby * Date: 2017/8/21 * Time: 19:05 */ public interface Shape { /** * Draw. */ void draw(); }
C#
UTF-8
2,402
2.609375
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using CatBoardApi.Models; using System.Globalization; namespace CatBoardApi.Controllers { [Route("api/boards/{boardId}/[controller]")] [ApiController] public class PostsController : ControllerBase { private CatBoardApiContext _db; public PostsController(CatBoardApiContext db) { _db = db; } // GET api/Posts [HttpGet] public ActionResult<IEnumerable<Post>> Get(int boardId) { List<Post> thesePosts = _db.Posts.Where(post => post.BoardId == boardId).ToList(); return thesePosts; } // GET api/Posts/5 [HttpGet("{id}")] public ActionResult<Post> Get(int boardId, int id) { Post thisPost = _db.Posts.FirstOrDefault(post => post.PostId == id); thisPost.Comments = _db.Comments.Where(comments => comments.PostId == id).ToList(); return thisPost; } // POST api/Posts [HttpPost] public void Post(int boardId, [FromBody] Post post) { post.BoardId = boardId; post.DateCreated = DateTime.Now; post.EditDate = DateTime.Now; _db.Posts.Add(post); _db.SaveChanges(); } // PUT api/Posts/5 [HttpPut("{id}")] public void Put( int id, int boardId, [FromBody] Post post) { post.EditDate = DateTime.Now; post.PostId = id; //double checking id of the form body is the correct id post.BoardId = boardId; _db.Entry(post).State = EntityState.Modified; _db.SaveChanges(); } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { Post thisPost = _db.Posts.FirstOrDefault(post => post.PostId == id); _db.Posts.Remove(thisPost); _db.SaveChanges(); } //upvote [HttpPatch("{id}/upvote")] public void UpVote(int id) { Post thisPost = _db.Posts.FirstOrDefault(post => post.PostId == id); thisPost.Score ++; _db.Entry(thisPost).State = EntityState.Modified; _db.SaveChanges(); } //downvote [HttpPatch("{id}/downvote")] public void DownVote(int id) { Post thisPost = _db.Posts.FirstOrDefault(post => post.PostId == id); thisPost.Score --; _db.Entry(thisPost).State = EntityState.Modified; _db.SaveChanges(); } } }
Markdown
UTF-8
1,108
2.75
3
[]
no_license
# MERN app > CRUD API to get all the users from the MySQL database and to view their friends. ## MySQL Database The SQL commands for creating the tables of the database is in the root directory under the name code.sql. ## Quick start Launch the backend server locally and connect it to your MySQL database by providing your username, password and the database name in config/db.js. ```bash # Install dependencies for backend server npm install # Install dependencies for frontend client npm run client-install # Run the backend nodejs(express) server only npm run server # Run the frontend React client only npm run client # Run the client & server with concurrently npm run dev # Backend Server runs on http://localhost:8000 and Frontend Client on http://localhost:3000 ``` ## Test API endpoints Start the backend server locally and test any API endpoint using postman or any other API testing tool by adding the 'Content-type' header and set it to 'Application/json' and then if it is a POST, then add the appropriate post data in body by choosing raw and JSON option. ### Author Abishek Srinivasan
JavaScript
UTF-8
2,398
2.78125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import { fetchJson, fetchText } from 'umbrella-common-js/ajax.js'; /** * * interface options { * forceRefresh: boolean; don't use cache * onlyIfCached: boolean; only return data from cache if available, don't fetch, superceded by forceRefresh * isPaginated: boolean; if api route is paginated; the way pagination works is that the total number of items in the cache are returned up to the total number of items requested determined by offset and limit * offset: number; number to start at for api pagination, zero indexed * limit: number; maximum number of items to return starting at pagination * contentType: 'text' | 'json' - default 'json' * } */ function fetchIntoCache(apiUrl, cacheMap, mapId, options={}){ const isCached = !options.forceRefresh && cacheMap.has(mapId); const fetchFunc = options.contentType === 'text' ? fetchText : fetchJson; if(options.isPaginated){ const cachedLength = isCached ? cacheMap.get(mapId).offset + cacheMap.get(mapId).limit : 0; const desiredLength = options.offset + options.limit; // check if cache contains enough items to fulfill request if(cachedLength >= desiredLength){ return Promise.resolve(cacheMap.get(mapId).data.slice(0, desiredLength)); } if(options.onlyIfCached){ return Promise.resolve(null); } const adjustedOffset = Math.max(options.offset, cachedLength); const adjustedLimit = desiredLength - cachedLength; const url = new URL(apiUrl, window.location); const query = url.search ? url.search + '&' : '?'; const paginatedUrl = `${url.pathname}${query}offset=${adjustedOffset}&limit=${adjustedLimit}`; return fetchFunc(paginatedUrl).then((data)=>{ const oldData = cacheMap.has(mapId) ? cacheMap.get(mapId).data : []; const combinedData = oldData.concat(data); cacheMap.set(mapId, {data: combinedData, offset: options.offset, limit: options.limit}); return combinedData; }); } if(isCached){ return Promise.resolve(cacheMap.get(mapId).data); } if(options.onlyIfCached){ return Promise.resolve(null); } return fetchFunc(apiUrl).then((data)=>{ cacheMap.set(mapId, {data}); return data; }); } export default { fetchIntoCache, };
TypeScript
UTF-8
971
2.9375
3
[]
no_license
import { User } from '../models'; import * as fromUsers from '../actions/user.actions'; export interface UserState { users: User[]; } export const initialState: UserState = { users: [] }; export function userReducer(state = initialState, action: fromUsers.Actions): UserState { switch (action.type) { case fromUsers.LOAD_USERS_SUCCESS: { return { ...state, users: action.payload }; } case fromUsers.DELETE_USER: { return state = { ...state, // filter the array keeping only users with ids not provided in payload (in our store). users: state.users.filter(user => user.id !== action.payload) }; } case fromUsers.ADD_USER: { return { ...state, users: [...state.users, action.payload] }; } default: { return state; } } }
Python
UTF-8
764
3.5
4
[ "MIT" ]
permissive
import data class Strings: def __init__(self): print( """ String Problems 1.winner of election 2.Maximum length of consecutive 1in a binary string """ ) def electionWinner(self, votes=data.electionWinner_Votes): candidates = {} for c in votes: if candidates.has_key(c): candidates[c] = candidates[c] + 1 else: candidates[c] = 1 winnder = max(candidates.items(), key=lambda x: x[1]) print('winner is {0} with votes {1}'.format(winnder[0], winnder[1])) def maxBinaryOnes(self, data=data.maxBinaryOnes_str): print(max(map(len, data.split('0')))) s=Strings() s.maxBinaryOnes()
C++
UTF-8
2,829
2.953125
3
[]
no_license
#include "stdafx.h" #include "Stretch.h" DWORD Stretch(UINT w, UINT h, UINT lower, UINT upper, UCHAR *img) { if(!img) return FALSE; if(upper > 255) upper = 255; if(lower < 0) lower = 0; UINT i = NULL; UINT end = w*h; DWORD min = NULL; DWORD max = NULL; FLOAT ratio = NULL; DWORD temp = NULL; GetMaxMin(w*h, &max, &min, img); if(max-min) ratio = (FLOAT)(upper - lower) / (FLOAT)(max - min); else ratio = 0; for(i = 0; i < end; i++) { /*img[i]*/temp = (img[i]*ratio); img[i] = temp; if(temp > upper) img[i] = upper; if(temp < lower) img[i] = lower; } return i; } DWORD Stretch(UINT w, UINT h, FLOAT lower, FLOAT upper, FLOAT *in, FLOAT *out) { if(!in || !out) return FALSE; UINT i = NULL; UINT end = w*h; FLOAT min = NULL; FLOAT max = NULL; FLOAT midData = NULL; FLOAT midRange = NULL; FLOAT ratio = NULL; //FLOAT shift = NULL; DWORD temp = NULL; GetMaxMin(w*h, &max, &min, in); //midData = (Magnitude(max) - Magnitude(min))/2.0; //midRange = (Magnitude(upper) - Magnitude(lower))/2.0; midData = (FLOAT)(max + min) / (FLOAT) 2.0; midRange = (FLOAT)(upper + lower) / (FLOAT) 2.0; if(max-min) ratio = (FLOAT)(midRange*2) / (FLOAT) (midData*2); else ratio = 0; for(i = 0; i < end; i++) { //out[i] = (in[i]*ratio) + shift; out[i] = ((in[i]-midData)*ratio) + midRange; if(out[i] > upper) out[i] = upper; if(out[i] < lower) out[i] = lower; } return i; } DWORD Stretch(UINT w, UINT h, INT lower, INT upper, INT *in, INT *out) { if(!in || !out) return FALSE; UINT i = NULL; UINT end = w*h; INT min = NULL; INT max = NULL; FLOAT midData = NULL; FLOAT midRange = NULL; FLOAT ratio = NULL; DWORD temp = NULL; GetMaxMin(w*h, &max, &min, in); midData = (FLOAT)(max + min) / (FLOAT) 2.0; midRange = (FLOAT)(upper + lower) / (FLOAT) 2.0; if(max-min) ratio = (FLOAT)(midRange*2) / (FLOAT) (midData*2); else ratio = 0; for(i = 0; i < end; i++) { //out[i] = (in[i]*ratio) + shift; out[i] = ((in[i]-midData)*ratio) + midRange; if(out[i] > upper) out[i] = upper; if(out[i] < lower) out[i] = lower; } return i; } DWORD Stretch(UINT w, UINT h, INT lower, INT upper, INT *in, UCHAR *out) { if(!in || !out) return FALSE; UINT i = NULL; UINT end = w*h; INT min = NULL; INT max = NULL; FLOAT midData = NULL; FLOAT midRange = NULL; FLOAT ratio = NULL; DWORD temp = NULL; GetMaxMin(w*h, &max, &min, in); midData = (FLOAT)(max + min) / (FLOAT) 2.0; midRange = (FLOAT)(upper + lower) / (FLOAT) 2.0; if(max-min) ratio = (FLOAT)(midRange*2) / (FLOAT) (midData*2); else ratio = 0; for(i = 0; i < end; i++) { //out[i] = (in[i]*ratio) + shift; out[i] = ((in[i]-midData)*ratio) + midRange; if(out[i] > upper) out[i] = upper; if(out[i] < lower) out[i] = lower; } return i; }
Python
UTF-8
54,915
2.53125
3
[ "BSD-3-Clause" ]
permissive
# Copyright 2012-2021 M. Andersen and L. Vandenberghe. # Copyright 2010-2011 L. Vandenberghe. # Copyright 2004-2009 J. Dahl and L. Vandenberghe. # # This file is part of CVXOPT. # # CVXOPT is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # CVXOPT is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import math from kvxopt import base, blas, lapack, cholmod, misc_solvers from kvxopt.base import matrix, spmatrix __all__ = [] use_C = True if use_C: scale = misc_solvers.scale else: def scale(x, W, trans = 'N', inverse = 'N'): """ Applies Nesterov-Todd scaling or its inverse. Computes x := W*x (trans is 'N', inverse = 'N') x := W^T*x (trans is 'T', inverse = 'N') x := W^{-1}*x (trans is 'N', inverse = 'I') x := W^{-T}*x (trans is 'T', inverse = 'I'). x is a dense 'd' matrix. W is a dictionary with entries: - W['dnl']: positive vector - W['dnli']: componentwise inverse of W['dnl'] - W['d']: positive vector - W['di']: componentwise inverse of W['d'] - W['v']: lists of 2nd order cone vectors with unit hyperbolic norms - W['beta']: list of positive numbers - W['r']: list of square matrices - W['rti']: list of square matrices. rti[k] is the inverse transpose of r[k]. The 'dnl' and 'dnli' entries are optional, and only present when the function is called from the nonlinear solver. """ ind = 0 # Scaling for nonlinear component xk is xk := dnl .* xk; inverse # scaling is xk ./ dnl = dnli .* xk, where dnl = W['dnl'], # dnli = W['dnli']. if 'dnl' in W: if inverse == 'N': w = W['dnl'] else: w = W['dnli'] for k in range(x.size[1]): blas.tbmv(w, x, n = w.size[0], k = 0, ldA = 1, offsetx = k*x.size[0]) ind += w.size[0] # Scaling for linear 'l' component xk is xk := d .* xk; inverse # scaling is xk ./ d = di .* xk, where d = W['d'], di = W['di']. if inverse == 'N': w = W['d'] else: w = W['di'] for k in range(x.size[1]): blas.tbmv(w, x, n = w.size[0], k = 0, ldA = 1, offsetx = k*x.size[0] + ind) ind += w.size[0] # Scaling for 'q' component is # # xk := beta * (2*v*v' - J) * xk # = beta * (2*v*(xk'*v)' - J*xk) # # where beta = W['beta'][k], v = W['v'][k], J = [1, 0; 0, -I]. # # Inverse scaling is # # xk := 1/beta * (2*J*v*v'*J - J) * xk # = 1/beta * (-J) * (2*v*((-J*xk)'*v)' + xk). w = matrix(0.0, (x.size[1], 1)) for k in range(len(W['v'])): v = W['v'][k] m = v.size[0] if inverse == 'I': blas.scal(-1.0, x, offset = ind, inc = x.size[0]) blas.gemv(x, v, w, trans = 'T', m = m, n = x.size[1], offsetA = ind, ldA = x.size[0]) blas.scal(-1.0, x, offset = ind, inc = x.size[0]) blas.ger(v, w, x, alpha = 2.0, m = m, n = x.size[1], ldA = x.size[0], offsetA = ind) if inverse == 'I': blas.scal(-1.0, x, offset = ind, inc = x.size[0]) a = 1.0 / W['beta'][k] else: a = W['beta'][k] for i in range(x.size[1]): blas.scal(a, x, n = m, offset = ind + i*x.size[0]) ind += m # Scaling for 's' component xk is # # xk := vec( r' * mat(xk) * r ) if trans = 'N' # xk := vec( r * mat(xk) * r' ) if trans = 'T'. # # r is kth element of W['r']. # # Inverse scaling is # # xk := vec( rti * mat(xk) * rti' ) if trans = 'N' # xk := vec( rti' * mat(xk) * rti ) if trans = 'T'. # # rti is kth element of W['rti']. maxn = max( [0] + [ r.size[0] for r in W['r'] ] ) a = matrix(0.0, (maxn, maxn)) for k in range(len(W['r'])): if inverse == 'N': r = W['r'][k] if trans == 'N': t = 'T' else: t = 'N' else: r = W['rti'][k] t = trans n = r.size[0] for i in range(x.size[1]): # scale diagonal of xk by 0.5 blas.scal(0.5, x, offset = ind + i*x.size[0], inc = n+1, n = n) # a = r*tril(x) (t is 'N') or a = tril(x)*r (t is 'T') blas.copy(r, a) if t == 'N': blas.trmm(x, a, side = 'R', m = n, n = n, ldA = n, ldB = n, offsetA = ind + i*x.size[0]) else: blas.trmm(x, a, side = 'L', m = n, n = n, ldA = n, ldB = n, offsetA = ind + i*x.size[0]) # x := (r*a' + a*r') if t is 'N' # x := (r'*a + a'*r) if t is 'T' blas.syr2k(r, a, x, trans = t, n = n, k = n, ldB = n, ldC = n, offsetC = ind + i*x.size[0]) ind += n**2 if use_C: scale2 = misc_solvers.scale2 else: def scale2(lmbda, x, dims, mnl = 0, inverse = 'N'): """ Evaluates x := H(lambda^{1/2}) * x (inverse is 'N') x := H(lambda^{-1/2}) * x (inverse is 'I'). H is the Hessian of the logarithmic barrier. """ # For the nonlinear and 'l' blocks, # # xk := xk ./ l (inverse is 'N') # xk := xk .* l (inverse is 'I') # # where l is lmbda[:mnl+dims['l']]. if inverse == 'N': blas.tbsv(lmbda, x, n = mnl + dims['l'], k = 0, ldA = 1) else: blas.tbmv(lmbda, x, n = mnl + dims['l'], k = 0, ldA = 1) # For 'q' blocks, if inverse is 'N', # # xk := 1/a * [ l'*J*xk; # xk[1:] - (xk[0] + l'*J*xk) / (l[0] + 1) * l[1:] ]. # # If inverse is 'I', # # xk := a * [ l'*xk; # xk[1:] + (xk[0] + l'*xk) / (l[0] + 1) * l[1:] ]. # # a = sqrt(lambda_k' * J * lambda_k), l = lambda_k / a. ind = mnl + dims['l'] for m in dims['q']: a = jnrm2(lmbda, n = m, offset = ind) if inverse == 'N': lx = jdot(lmbda, x, n = m, offsetx = ind, offsety = ind)/a else: lx = blas.dot(lmbda, x, n = m, offsetx = ind, offsety = ind)/a x0 = x[ind] x[ind] = lx c = (lx + x0) / (lmbda[ind]/a + 1) / a if inverse == 'N': c *= -1.0 blas.axpy(lmbda, x, alpha = c, n = m-1, offsetx = ind+1, offsety = ind+1) if inverse == 'N': a = 1.0/a blas.scal(a, x, offset = ind, n = m) ind += m # For the 's' blocks, if inverse is 'N', # # xk := vec( diag(l)^{-1/2} * mat(xk) * diag(l)^{-1/2}). # # If inverse is 'I', # # xk := vec( diag(l)^{1/2} * mat(xk) * diag(l)^{1/2}). # # where l is kth block of lambda. # # We scale upper and lower triangular part of mat(xk) because the # inverse operation will be applied to nonsymmetric matrices. ind2 = ind for k in range(len(dims['s'])): m = dims['s'][k] for j in range(m): c = math.sqrt(lmbda[ind2+j]) * base.sqrt(lmbda[ind2:ind2+m]) if inverse == 'N': blas.tbsv(c, x, n = m, k = 0, ldA = 1, offsetx = ind + j*m) else: blas.tbmv(c, x, n = m, k = 0, ldA = 1, offsetx = ind + j*m) ind += m*m ind2 += m def compute_scaling(s, z, lmbda, dims, mnl = None): """ Returns the Nesterov-Todd scaling W at points s and z, and stores the scaled variable in lmbda. W * z = W^{-T} * s = lmbda. """ W = {} # For the nonlinear block: # # W['dnl'] = sqrt( s[:mnl] ./ z[:mnl] ) # W['dnli'] = sqrt( z[:mnl] ./ s[:mnl] ) # lambda[:mnl] = sqrt( s[:mnl] .* z[:mnl] ) if mnl is None: mnl = 0 else: W['dnl'] = base.sqrt( base.div( s[:mnl], z[:mnl] )) W['dnli'] = W['dnl']**-1 lmbda[:mnl] = base.sqrt( base.mul( s[:mnl], z[:mnl] ) ) # For the 'l' block: # # W['d'] = sqrt( sk ./ zk ) # W['di'] = sqrt( zk ./ sk ) # lambdak = sqrt( sk .* zk ) # # where sk and zk are the first dims['l'] entries of s and z. # lambda_k is stored in the first dims['l'] positions of lmbda. m = dims['l'] W['d'] = base.sqrt( base.div( s[mnl:mnl+m], z[mnl:mnl+m] )) W['di'] = W['d']**-1 lmbda[mnl:mnl+m] = base.sqrt( base.mul( s[mnl:mnl+m], z[mnl:mnl+m] ) ) # For the 'q' blocks, compute lists 'v', 'beta'. # # The vector v[k] has unit hyperbolic norm: # # (sqrt( v[k]' * J * v[k] ) = 1 with J = [1, 0; 0, -I]). # # beta[k] is a positive scalar. # # The hyperbolic Householder matrix H = 2*v[k]*v[k]' - J # defined by v[k] satisfies # # (beta[k] * H) * zk = (beta[k] * H) \ sk = lambda_k # # where sk = s[indq[k]:indq[k+1]], zk = z[indq[k]:indq[k+1]]. # # lambda_k is stored in lmbda[indq[k]:indq[k+1]]. ind = mnl + dims['l'] W['v'] = [ matrix(0.0, (k,1)) for k in dims['q'] ] W['beta'] = len(dims['q']) * [ 0.0 ] for k in range(len(dims['q'])): m = dims['q'][k] v = W['v'][k] # a = sqrt( sk' * J * sk ) where J = [1, 0; 0, -I] aa = jnrm2(s, offset = ind, n = m) # b = sqrt( zk' * J * zk ) bb = jnrm2(z, offset = ind, n = m) # beta[k] = ( a / b )**1/2 W['beta'][k] = math.sqrt( aa / bb ) # c = sqrt( (sk/a)' * (zk/b) + 1 ) / sqrt(2) cc = math.sqrt( ( blas.dot(s, z, n = m, offsetx = ind, offsety = ind) / aa / bb + 1.0 ) / 2.0 ) # vk = 1/(2*c) * ( (sk/a) + J * (zk/b) ) blas.copy(z, v, offsetx = ind, n = m) blas.scal(-1.0/bb, v) v[0] *= -1.0 blas.axpy(s, v, 1.0/aa, offsetx = ind, n = m) blas.scal(1.0/2.0/cc, v) # v[k] = 1/sqrt(2*(vk0 + 1)) * ( vk + e ), e = [1; 0] v[0] += 1.0 blas.scal(1.0/math.sqrt(2.0 * v[0]), v) # To get the scaled variable lambda_k # # d = sk0/a + zk0/b + 2*c # lambda_k = [ c; # (c + zk0/b)/d * sk1/a + (c + sk0/a)/d * zk1/b ] # lambda_k *= sqrt(a * b) lmbda[ind] = cc dd = 2*cc + s[ind]/aa + z[ind]/bb blas.copy(s, lmbda, offsetx = ind+1, offsety = ind+1, n = m-1) blas.scal((cc + z[ind]/bb)/dd/aa, lmbda, n = m-1, offset = ind+1) blas.axpy(z, lmbda, (cc + s[ind]/aa)/dd/bb, n = m-1, offsetx = ind+1, offsety = ind+1) blas.scal(math.sqrt(aa*bb), lmbda, offset = ind, n = m) ind += m # For the 's' blocks: compute two lists 'r' and 'rti'. # # r[k]' * sk^{-1} * r[k] = diag(lambda_k)^{-1} # r[k]' * zk * r[k] = diag(lambda_k) # # where sk and zk are the entries inds[k] : inds[k+1] of # s and z, reshaped into symmetric matrices. # # rti[k] is the inverse of r[k]', so # # rti[k]' * sk * rti[k] = diag(lambda_k)^{-1} # rti[k]' * zk^{-1} * rti[k] = diag(lambda_k). # # The vectors lambda_k are stored in # # lmbda[ dims['l'] + sum(dims['q']) : -1 ] W['r'] = [ matrix(0.0, (m,m)) for m in dims['s'] ] W['rti'] = [ matrix(0.0, (m,m)) for m in dims['s'] ] work = matrix(0.0, (max( [0] + dims['s'] )**2, 1)) Ls = matrix(0.0, (max( [0] + dims['s'] )**2, 1)) Lz = matrix(0.0, (max( [0] + dims['s'] )**2, 1)) ind2 = ind for k in range(len(dims['s'])): m = dims['s'][k] r, rti = W['r'][k], W['rti'][k] # Factor sk = Ls*Ls'; store Ls in ds[inds[k]:inds[k+1]]. blas.copy(s, Ls, offsetx = ind2, n = m**2) lapack.potrf(Ls, n = m, ldA = m) # Factor zs[k] = Lz*Lz'; store Lz in dz[inds[k]:inds[k+1]]. blas.copy(z, Lz, offsetx = ind2, n = m**2) lapack.potrf(Lz, n = m, ldA = m) # SVD Lz'*Ls = U*diag(lambda_k)*V'. Keep U in work. for i in range(m): blas.scal(0.0, Ls, offset = i*m, n = i) blas.copy(Ls, work, n = m**2) blas.trmm(Lz, work, transA = 'T', ldA = m, ldB = m, n = m, m = m) lapack.gesvd(work, lmbda, jobu = 'O', ldA = m, m = m, n = m, offsetS = ind) # r = Lz^{-T} * U blas.copy(work, r, n = m*m) blas.trsm(Lz, r, transA = 'T', m = m, n = m, ldA = m) # rti = Lz * U blas.copy(work, rti, n = m*m) blas.trmm(Lz, rti, m = m, n = m, ldA = m) # r := r * diag(sqrt(lambda_k)) # rti := rti * diag(1 ./ sqrt(lambda_k)) for i in range(m): a = math.sqrt( lmbda[ind+i] ) blas.scal(a, r, offset = m*i, n = m) blas.scal(1.0/a, rti, offset = m*i, n = m) ind += m ind2 += m*m return W def update_scaling(W, lmbda, s, z): """ Updates the Nesterov-Todd scaling matrix W and the scaled variable lmbda so that on exit W * zt = W^{-T} * st = lmbda. On entry, the nonlinear, 'l' and 'q' components of the arguments s and z contain W^{-T}*st and W*zt, i.e, the new iterates in the current scaling. The 's' components contain the factors Ls, Lz in a factorization of the new iterates in the current scaling, W^{-T}*st = Ls*Ls', W*zt = Lz*Lz'. """ # Nonlinear and 'l' blocks # # d := d .* sqrt( s ./ z ) # lmbda := lmbda .* sqrt(s) .* sqrt(z) if 'dnl' in W: mnl = len(W['dnl']) else: mnl = 0 ml = len(W['d']) m = mnl + ml s[:m] = base.sqrt( s[:m] ) z[:m] = base.sqrt( z[:m] ) # d := d .* s .* z if 'dnl' in W: blas.tbmv(s, W['dnl'], n = mnl, k = 0, ldA = 1) blas.tbsv(z, W['dnl'], n = mnl, k = 0, ldA = 1) W['dnli'][:] = W['dnl'][:] ** -1 blas.tbmv(s, W['d'], n = ml, k = 0, ldA = 1, offsetA = mnl) blas.tbsv(z, W['d'], n = ml, k = 0, ldA = 1, offsetA = mnl) W['di'][:] = W['d'][:] ** -1 # lmbda := s .* z blas.copy(s, lmbda, n = m) blas.tbmv(z, lmbda, n = m, k = 0, ldA = 1) # 'q' blocks. # # Let st and zt be the new variables in the old scaling: # # st = s_k, zt = z_k # # and a = sqrt(st' * J * st), b = sqrt(zt' * J * zt). # # 1. Compute the hyperbolic Householder transformation 2*q*q' - J # that maps st/a to zt/b. # # c = sqrt( (1 + st'*zt/(a*b)) / 2 ) # q = (st/a + J*zt/b) / (2*c). # # The new scaling point is # # wk := betak * sqrt(a/b) * (2*v[k]*v[k]' - J) * q # # with betak = W['beta'][k]. # # 3. The scaled variable: # # lambda_k0 = sqrt(a*b) * c # lambda_k1 = sqrt(a*b) * ( (2vk*vk' - J) * (-d*q + u/2) )_1 # # where # # u = st/a - J*zt/b # d = ( vk0 * (vk'*u) + u0/2 ) / (2*vk0 *(vk'*q) - q0 + 1). # # 4. Update scaling # # v[k] := wk^1/2 # = 1 / sqrt(2*(wk0 + 1)) * (wk + e). # beta[k] *= sqrt(a/b) ind = m for k in range(len(W['v'])): v = W['v'][k] m = len(v) # ln = sqrt( lambda_k' * J * lambda_k ) ln = jnrm2(lmbda, n = m, offset = ind) # a = sqrt( sk' * J * sk ) = sqrt( st' * J * st ) # s := s / a = st / a aa = jnrm2(s, offset = ind, n = m) blas.scal(1.0/aa, s, offset = ind, n = m) # b = sqrt( zk' * J * zk ) = sqrt( zt' * J * zt ) # z := z / a = zt / b bb = jnrm2(z, offset = ind, n = m) blas.scal(1.0/bb, z, offset = ind, n = m) # c = sqrt( ( 1 + (st'*zt) / (a*b) ) / 2 ) cc = math.sqrt( ( 1.0 + blas.dot(s, z, offsetx = ind, offsety = ind, n = m) ) / 2.0 ) # vs = v' * st / a vs = blas.dot(v, s, offsety = ind, n = m) # vz = v' * J *zt / b vz = jdot(v, z, offsety = ind, n = m) # vq = v' * q where q = (st/a + J * zt/b) / (2 * c) vq = (vs + vz ) / 2.0 / cc # vu = v' * u where u = st/a - J * zt/b vu = vs - vz # lambda_k0 = c lmbda[ind] = cc # wk0 = 2 * vk0 * (vk' * q) - q0 wk0 = 2 * v[0] * vq - ( s[ind] + z[ind] ) / 2.0 / cc # d = (v[0] * (vk' * u) - u0/2) / (wk0 + 1) dd = (v[0] * vu - s[ind]/2.0 + z[ind]/2.0) / (wk0 + 1.0) # lambda_k1 = 2 * v_k1 * vk' * (-d*q + u/2) - d*q1 + u1/2 blas.copy(v, lmbda, offsetx = 1, offsety = ind+1, n = m-1) blas.scal(2.0 * (-dd * vq + 0.5 * vu), lmbda, offset = ind+1, n = m-1) blas.axpy(s, lmbda, 0.5 * (1.0 - dd/cc), offsetx = ind+1, offsety = ind+1, n = m-1) blas.axpy(z, lmbda, 0.5 * (1.0 + dd/cc), offsetx = ind+1, offsety = ind+1, n = m-1) # Scale so that sqrt(lambda_k' * J * lambda_k) = sqrt(aa*bb). blas.scal(math.sqrt(aa*bb), lmbda, offset = ind, n = m) # v := (2*v*v' - J) * q # = 2 * (v'*q) * v' - (J* st/a + zt/b) / (2*c) blas.scal(2.0 * vq, v) v[0] -= s[ind] / 2.0 / cc blas.axpy(s, v, 0.5/cc, offsetx = ind+1, offsety = 1, n = m-1) blas.axpy(z, v, -0.5/cc, offsetx = ind, n = m) # v := v^{1/2} = 1/sqrt(2 * (v0 + 1)) * (v + e) v[0] += 1.0 blas.scal(1.0 / math.sqrt(2.0 * v[0]), v) # beta[k] *= ( aa / bb )**1/2 W['beta'][k] *= math.sqrt( aa / bb ) ind += m # 's' blocks # # Let st, zt be the updated variables in the old scaling: # # st = Ls * Ls', zt = Lz * Lz'. # # where Ls and Lz are the 's' components of s, z. # # 1. SVD Lz'*Ls = Uk * lambda_k^+ * Vk'. # # 2. New scaling is # # r[k] := r[k] * Ls * Vk * diag(lambda_k^+)^{-1/2} # rti[k] := r[k] * Lz * Uk * diag(lambda_k^+)^{-1/2}. # work = matrix(0.0, (max( [0] + [r.size[0] for r in W['r']])**2, 1)) ind = mnl + ml + sum([ len(v) for v in W['v'] ]) ind2, ind3 = ind, 0 for k in range(len(W['r'])): r, rti = W['r'][k], W['rti'][k] m = r.size[0] # r := r*sk = r*Ls blas.gemm(r, s, work, m = m, n = m, k = m, ldB = m, ldC = m, offsetB = ind2) blas.copy(work, r, n = m**2) # rti := rti*zk = rti*Lz blas.gemm(rti, z, work, m = m, n = m, k = m, ldB = m, ldC = m, offsetB = ind2) blas.copy(work, rti, n = m**2) # SVD Lz'*Ls = U * lmbds^+ * V'; store U in sk and V' in zk. blas.gemm(z, s, work, transA = 'T', m = m, n = m, k = m, ldA = m, ldB = m, ldC = m, offsetA = ind2, offsetB = ind2) lapack.gesvd(work, lmbda, jobu = 'A', jobvt = 'A', m = m, n = m, ldA = m, U = s, Vt = z, ldU = m, ldVt = m, offsetS = ind, offsetU = ind2, offsetVt = ind2) # r := r*V blas.gemm(r, z, work, transB = 'T', m = m, n = m, k = m, ldB = m, ldC = m, offsetB = ind2) blas.copy(work, r, n = m**2) # rti := rti*U blas.gemm(rti, s, work, n = m, m = m, k = m, ldB = m, ldC = m, offsetB = ind2) blas.copy(work, rti, n = m**2) # r := r*lambda^{-1/2}; rti := rti*lambda^{-1/2} for i in range(m): a = 1.0 / math.sqrt(lmbda[ind+i]) blas.scal(a, r, offset = m*i, n = m) blas.scal(a, rti, offset = m*i, n = m) ind += m ind2 += m*m ind3 += m if use_C: pack = misc_solvers.pack else: def pack(x, y, dims, mnl = 0, offsetx = 0, offsety = 0): """ Copy x to y using packed storage. The vector x is an element of S, with the 's' components stored in unpacked storage. On return, x is copied to y with the 's' components stored in packed storage and the off-diagonal entries scaled by sqrt(2). """ nlq = mnl + dims['l'] + sum(dims['q']) blas.copy(x, y, n = nlq, offsetx = offsetx, offsety = offsety) iu, ip = offsetx + nlq, offsety + nlq for n in dims['s']: for k in range(n): blas.copy(x, y, n = n-k, offsetx = iu + k*(n+1), offsety = ip) y[ip] /= math.sqrt(2) ip += n-k iu += n**2 np = sum([ int(n*(n+1)/2) for n in dims['s'] ]) blas.scal(math.sqrt(2.0), y, n = np, offset = offsety+nlq) if use_C: pack2 = misc_solvers.pack2 else: def pack2(x, dims, mnl = 0): """ In-place version of pack(), which also accepts matrix arguments x. The columns of x are elements of S, with the 's' components stored in unpacked storage. On return, the 's' components are stored in packed storage and the off-diagonal entries are scaled by sqrt(2). """ if not dims['s']: return iu = mnl + dims['l'] + sum(dims['q']) ip = iu for n in dims['s']: for k in range(n): x[ip, :] = x[iu + (n+1)*k, :] x[ip + 1 : ip+n-k, :] = x[iu + (n+1)*k + 1: iu + n*(k+1), :] \ * math.sqrt(2.0) ip += n - k iu += n**2 np = sum([ int(n*(n+1)/2) for n in dims['s'] ]) if use_C: unpack = misc_solvers.unpack else: def unpack(x, y, dims, mnl = 0, offsetx = 0, offsety = 0): """ The vector x is an element of S, with the 's' components stored in unpacked storage and off-diagonal entries scaled by sqrt(2). On return, x is copied to y with the 's' components stored in unpacked storage. """ nlq = mnl + dims['l'] + sum(dims['q']) blas.copy(x, y, n = nlq, offsetx = offsetx, offsety = offsety) iu, ip = offsety+nlq, offsetx+nlq for n in dims['s']: for k in range(n): blas.copy(x, y, n = n-k, offsetx = ip, offsety = iu+k*(n+1)) y[iu+k*(n+1)] *= math.sqrt(2) ip += n-k iu += n**2 nu = sum([ n**2 for n in dims['s'] ]) blas.scal(1.0/math.sqrt(2.0), y, n = nu, offset = offsety+nlq) if use_C: sdot = misc_solvers.sdot else: def sdot(x, y, dims, mnl = 0): """ Inner product of two vectors in S. """ ind = mnl + dims['l'] + sum(dims['q']) a = blas.dot(x, y, n = ind) for m in dims['s']: a += blas.dot(x, y, offsetx = ind, offsety = ind, incx = m+1, incy = m+1, n = m) for j in range(1, m): a += 2.0 * blas.dot(x, y, incx = m+1, incy = m+1, offsetx = ind+j, offsety = ind+j, n = m-j) ind += m**2 return a def sdot2(x, y): """ Inner product of two block-diagonal symmetric dense 'd' matrices. x and y are square dense 'd' matrices, or lists of N square dense 'd' matrices. """ a = 0.0 if type(x) is matrix: n = x.size[0] a += blas.dot(x, y, incx=n+1, incy=n+1, n=n) for j in range(1,n): a += 2.0 * blas.dot(x, y, incx=n+1, incy=n+1, offsetx=j, offsety=j, n=n-j) else: for k in range(len(x)): n = x[k].size[0] a += blas.dot(x[k], y[k], incx=n+1, incy=n+1, n=n) for j in range(1,n): a += 2.0 * blas.dot(x[k], y[k], incx=n+1, incy=n+1, offsetx=j, offsety=j, n=n-j) return a def snrm2(x, dims, mnl = 0): """ Returns the norm of a vector in S """ return math.sqrt(sdot(x, x, dims, mnl)) if use_C: trisc = misc_solvers.trisc else: def trisc(x, dims, offset = 0): """ Sets upper triangular part of the 's' components of x equal to zero and scales the strictly lower triangular part by 2.0. """ m = dims['l'] + sum(dims['q']) + sum([ k**2 for k in dims['s'] ]) ind = offset + dims['l'] + sum(dims['q']) for mk in dims['s']: for j in range(1, mk): blas.scal(0.0, x, n = mk-j, inc = mk, offset = ind + j*(mk + 1) - 1) blas.scal(2.0, x, offset = ind + mk*(j-1) + j, n = mk-j) ind += mk**2 if use_C: triusc = misc_solvers.triusc else: def triusc(x, dims, offset = 0): """ Scales the strictly lower triangular part of the 's' components of x by 0.5. """ m = dims['l'] + sum(dims['q']) + sum([ k**2 for k in dims['s'] ]) ind = offset + dims['l'] + sum(dims['q']) for mk in dims['s']: for j in range(1, mk): blas.scal(0.5, x, offset = ind + mk*(j-1) + j, n = mk-j) ind += mk**2 def sgemv(A, x, y, dims, trans = 'N', alpha = 1.0, beta = 0.0, n = None, offsetA = 0, offsetx = 0, offsety = 0): """ Matrix-vector multiplication. A is a matrix or spmatrix of size (m, n) where N = dims['l'] + sum(dims['q']) + sum( k**2 for k in dims['s'] ) representing a mapping from R^n to S. If trans is 'N': y := alpha*A*x + beta * y (trans = 'N'). x is a vector of length n. y is a vector of length N. If trans is 'T': y := alpha*A'*x + beta * y (trans = 'T'). x is a vector of length N. y is a vector of length n. The 's' components in S are stored in unpacked 'L' storage. """ m = dims['l'] + sum(dims['q']) + sum([ k**2 for k in dims['s'] ]) if n is None: n = A.size[1] if trans == 'T' and alpha: trisc(x, dims, offsetx) base.gemv(A, x, y, trans = trans, alpha = alpha, beta = beta, m = m, n = n, offsetA = offsetA, offsetx = offsetx, offsety = offsety) if trans == 'T' and alpha: triusc(x, dims, offsetx) def jdot(x, y, n = None, offsetx = 0, offsety = 0): """ Returns x' * J * y, where J = [1, 0; 0, -I]. """ if n is None: if len(x) != len(y): raise ValueError("x and y must have the "\ "same length") n = len(x) return x[offsetx] * y[offsety] - blas.dot(x, y, n = n-1, offsetx = offsetx + 1, offsety = offsety + 1) def jnrm2(x, n = None, offset = 0): """ Returns sqrt(x' * J * x) where J = [1, 0; 0, -I], for a vector x in a second order cone. """ if n is None: n = len(x) a = blas.nrm2(x, n = n-1, offset = offset+1) return math.sqrt(x[offset] - a) * math.sqrt(x[offset] + a) if use_C: symm = misc_solvers.symm else: def symm(x, n, offset = 0): """ Converts lower triangular matrix to symmetric. Fills in the upper triangular part of the symmetric matrix stored in x[offset : offset+n*n] using 'L' storage. """ if n <= 1: return for i in range(n-1): blas.copy(x, x, offsetx = offset + i*(n+1) + 1, offsety = offset + (i+1)*(n+1) - 1, incy = n, n = n-i-1) if use_C: sprod = misc_solvers.sprod else: def sprod(x, y, dims, mnl = 0, diag = 'N'): """ The product x := (y o x). If diag is 'D', the 's' part of y is diagonal and only the diagonal is stored. """ # For the nonlinear and 'l' blocks: # # yk o xk = yk .* xk. blas.tbmv(y, x, n = mnl + dims['l'], k = 0, ldA = 1) # For 'q' blocks: # # [ l0 l1' ] # yk o xk = [ ] * xk # [ l1 l0*I ] # # where yk = (l0, l1). ind = mnl + dims['l'] for m in dims['q']: dd = blas.dot(x, y, offsetx = ind, offsety = ind, n = m) blas.scal(y[ind], x, offset = ind+1, n = m-1) blas.axpy(y, x, alpha = x[ind], n = m-1, offsetx = ind+1, offsety = ind+1) x[ind] = dd ind += m # For the 's' blocks: # # yk o sk = .5 * ( Yk * mat(xk) + mat(xk) * Yk ) # # where Yk = mat(yk) if diag is 'N' and Yk = diag(yk) if diag is 'D'. if diag == 'N': maxm = max([0] + dims['s']) A = matrix(0.0, (maxm, maxm)) for m in dims['s']: blas.copy(x, A, offsetx = ind, n = m*m) # Write upper triangular part of A and yk. for i in range(m-1): symm(A, m) symm(y, m, offset = ind) # xk = 0.5 * (A*yk + yk*A) blas.syr2k(A, y, x, alpha = 0.5, n = m, k = m, ldA = m, ldB = m, ldC = m, offsetB = ind, offsetC = ind) ind += m*m else: ind2 = ind for m in dims['s']: for j in range(m): u = 0.5 * ( y[ind2+j:ind2+m] + y[ind2+j] ) blas.tbmv(u, x, n = m-j, k = 0, ldA = 1, offsetx = ind + j*(m+1)) ind += m*m ind2 += m def ssqr(x, y, dims, mnl = 0): """ The product x := y o y. The 's' components of y are diagonal and only the diagonals of x and y are stored. """ blas.copy(y, x) blas.tbmv(y, x, n = mnl + dims['l'], k = 0, ldA = 1) ind = mnl + dims['l'] for m in dims['q']: x[ind] = blas.nrm2(y, offset = ind, n = m)**2 blas.scal(2.0*y[ind], x, n = m-1, offset = ind+1) ind += m blas.tbmv(y, x, n = sum(dims['s']), k = 0, ldA = 1, offsetA = ind, offsetx = ind) if use_C: sinv = misc_solvers.sinv else: def sinv(x, y, dims, mnl = 0): """ The inverse product x := (y o\ x), when the 's' components of y are diagonal. """ # For the nonlinear and 'l' blocks: # # yk o\ xk = yk .\ xk. blas.tbsv(y, x, n = mnl + dims['l'], k = 0, ldA = 1) # For the 'q' blocks: # # [ l0 -l1' ] # yk o\ xk = 1/a^2 * [ ] * xk # [ -l1 (a*I + l1*l1')/l0 ] # # where yk = (l0, l1) and a = l0^2 - l1'*l1. ind = mnl + dims['l'] for m in dims['q']: aa = jnrm2(y, n = m, offset = ind)**2 cc = x[ind] dd = blas.dot(y, x, offsetx = ind+1, offsety = ind+1, n = m-1) x[ind] = cc * y[ind] - dd blas.scal(aa / y[ind], x, n = m-1, offset = ind+1) blas.axpy(y, x, alpha = dd/y[ind] - cc, n = m-1, offsetx = ind+1, offsety = ind+1) blas.scal(1.0/aa, x, n = m, offset = ind) ind += m # For the 's' blocks: # # yk o\ xk = xk ./ gamma # # where gammaij = .5 * (yk_i + yk_j). ind2 = ind for m in dims['s']: for j in range(m): u = 0.5 * ( y[ind2+j:ind2+m] + y[ind2+j] ) blas.tbsv(u, x, n = m-j, k = 0, ldA = 1, offsetx = ind + j*(m+1)) ind += m*m ind2 += m if use_C: max_step = misc_solvers.max_step else: def max_step(x, dims, mnl = 0, sigma = None): """ Returns min {t | x + t*e >= 0}, where e is defined as follows - For the nonlinear and 'l' blocks: e is the vector of ones. - For the 'q' blocks: e is the first unit vector. - For the 's' blocks: e is the identity matrix. When called with the argument sigma, also returns the eigenvalues (in sigma) and the eigenvectors (in x) of the 's' components of x. """ t = [] ind = mnl + dims['l'] if ind: t += [ -min(x[:ind]) ] for m in dims['q']: if m: t += [ blas.nrm2(x, offset = ind + 1, n = m-1) - x[ind] ] ind += m if sigma is None and dims['s']: Q = matrix(0.0, (max(dims['s']), max(dims['s']))) w = matrix(0.0, (max(dims['s']),1)) ind2 = 0 for m in dims['s']: if sigma is None: blas.copy(x, Q, offsetx = ind, n = m**2) lapack.syevr(Q, w, range = 'I', il = 1, iu = 1, n = m, ldA = m) if m: t += [ -w[0] ] else: lapack.syevd(x, sigma, jobz = 'V', n = m, ldA = m, offsetA = ind, offsetW = ind2) if m: t += [ -sigma[ind2] ] ind += m*m ind2 += m if t: return max(t) else: return 0.0 def kkt_ldl(G, dims, A, mnl = 0, kktreg = None): """ Solution of KKT equations by a dense LDL factorization of the 3 x 3 system. Returns a function that (1) computes the LDL factorization of [ H A' GG'*W^{-1} ] [ A 0 0 ], [ W^{-T}*GG 0 -I ] given H, Df, W, where GG = [Df; G], and (2) returns a function for solving [ H A' GG' ] [ ux ] [ bx ] [ A 0 0 ] * [ uy ] = [ by ]. [ GG 0 -W'*W ] [ uz ] [ bz ] H is n x n, A is p x n, Df is mnl x n, G is N x n where N = dims['l'] + sum(dims['q']) + sum( k**2 for k in dims['s'] ). """ p, n = A.size ldK = n + p + mnl + dims['l'] + sum(dims['q']) + sum([ int(k*(k+1)/2) for k in dims['s'] ]) K = matrix(0.0, (ldK, ldK)) ipiv = matrix(0, (ldK, 1)) u = matrix(0.0, (ldK, 1)) g = matrix(0.0, (mnl + G.size[0], 1)) def factor(W, H = None, Df = None): blas.scal(0.0, K) if H is not None: K[:n, :n] = H K[n:n+p, :n] = A for k in range(n): if mnl: g[:mnl] = Df[:,k] g[mnl:] = G[:,k] scale(g, W, trans = 'T', inverse = 'I') pack(g, K, dims, mnl, offsety = k*ldK + n + p) K[(ldK+1)*(p+n) :: ldK+1] = -1.0 if kktreg: K[0 : (ldK+1)*n : ldK+1] += kktreg # Reg. term, 1x1 block (positive) K[(ldK+1)*n :: ldK+1] -= kktreg # Reg. term, 2x2 block (negative) lapack.sytrf(K, ipiv) def solve(x, y, z): # Solve # # [ H A' GG'*W^{-1} ] [ ux ] [ bx ] # [ A 0 0 ] * [ uy [ = [ by ] # [ W^{-T}*GG 0 -I ] [ W*uz ] [ W^{-T}*bz ] # # and return ux, uy, W*uz. # # On entry, x, y, z contain bx, by, bz. On exit, they contain # the solution ux, uy, W*uz. blas.copy(x, u) blas.copy(y, u, offsety = n) scale(z, W, trans = 'T', inverse = 'I') pack(z, u, dims, mnl, offsety = n + p) lapack.sytrs(K, ipiv, u) blas.copy(u, x, n = n) blas.copy(u, y, offsetx = n, n = p) unpack(u, z, dims, mnl, offsetx = n + p) return solve return factor def kkt_ldl2(G, dims, A, mnl = 0): """ Solution of KKT equations by a dense LDL factorization of the 2 x 2 system. Returns a function that (1) computes the LDL factorization of [ H + GG' * W^{-1} * W^{-T} * GG A' ] [ ] [ A 0 ] given H, Df, W, where GG = [Df; G], and (2) returns a function for solving [ H A' GG' ] [ ux ] [ bx ] [ A 0 0 ] * [ uy ] = [ by ]. [ GG 0 -W'*W ] [ uz ] [ bz ] H is n x n, A is p x n, Df is mnl x n, G is N x n where N = dims['l'] + sum(dims['q']) + sum( k**2 for k in dims['s'] ). """ p, n = A.size ldK = n + p K = matrix(0.0, (ldK, ldK)) if p: ipiv = matrix(0, (ldK, 1)) g = matrix(0.0, (mnl + G.size[0], 1)) u = matrix(0.0, (ldK, 1)) def factor(W, H = None, Df = None): blas.scal(0.0, K) if H is not None: K[:n, :n] = H K[n:,:n] = A for k in range(n): if mnl: g[:mnl] = Df[:,k] g[mnl:] = G[:,k] scale(g, W, trans = 'T', inverse = 'I') scale(g, W, inverse = 'I') if mnl: base.gemv(Df, g, K, trans = 'T', beta = 1.0, n = n-k, offsetA = mnl*k, offsety = (ldK + 1)*k) sgemv(G, g, K, dims, trans = 'T', beta = 1.0, n = n-k, offsetA = G.size[0]*k, offsetx = mnl, offsety = (ldK + 1)*k) if p: lapack.sytrf(K, ipiv) else: lapack.potrf(K) def solve(x, y, z): # Solve # # [ H + GG' * W^{-1} * W^{-T} * GG A' ] [ ux ] # [ ] * [ ] # [ A 0 ] [ uy ] # # [ bx + GG' * W^{-1} * W^{-T} * bz ] # = [ ] # [ by ] # # and return x, y, W*z = W^{-T} * (GG*x - bz). blas.copy(z, g) scale(g, W, trans = 'T', inverse = 'I') scale(g, W, inverse = 'I') if mnl: base.gemv(Df, g, u, trans = 'T') beta = 1.0 else: beta = 0.0 sgemv(G, g, u, dims, trans = 'T', offsetx = mnl, beta = beta) blas.axpy(x, u) blas.copy(y, u, offsety = n) if p: lapack.sytrs(K, ipiv, u) else: lapack.potrs(K, u) blas.copy(u, x, n = n) blas.copy(u, y, offsetx = n, n = p) if mnl: base.gemv(Df, x, z, alpha = 1.0, beta = -1.0) sgemv(G, x, z, dims, alpha = 1.0, beta = -1.0, offsety = mnl) scale(z, W, trans = 'T', inverse = 'I') return solve return factor def kkt_chol(G, dims, A, mnl = 0): """ Solution of KKT equations by reduction to a 2 x 2 system, a QR factorization to eliminate the equality constraints, and a dense Cholesky factorization of order n-p. Computes the QR factorization A' = [Q1, Q2] * [R; 0] and returns a function that (1) computes the Cholesky factorization Q_2^T * (H + GG^T * W^{-1} * W^{-T} * GG) * Q2 = L * L^T, given H, Df, W, where GG = [Df; G], and (2) returns a function for solving [ H A' GG' ] [ ux ] [ bx ] [ A 0 0 ] * [ uy ] = [ by ]. [ GG 0 -W'*W ] [ uz ] [ bz ] H is n x n, A is p x n, Df is mnl x n, G is N x n where N = dims['l'] + sum(dims['q']) + sum( k**2 for k in dims['s'] ). """ p, n = A.size cdim = mnl + dims['l'] + sum(dims['q']) + sum([ k**2 for k in dims['s'] ]) cdim_pckd = mnl + dims['l'] + sum(dims['q']) + sum([ int(k*(k+1)/2) for k in dims['s'] ]) # A' = [Q1, Q2] * [R; 0] (Q1 is n x p, Q2 is n x n-p). if type(A) is matrix: QA = A.T else: QA = matrix(A.T) tauA = matrix(0.0, (p,1)) lapack.geqrf(QA, tauA) Gs = matrix(0.0, (cdim, n)) K = matrix(0.0, (n,n)) bzp = matrix(0.0, (cdim_pckd, 1)) yy = matrix(0.0, (p,1)) def factor(W, H = None, Df = None): # Compute # # K = [Q1, Q2]' * (H + GG' * W^{-1} * W^{-T} * GG) * [Q1, Q2] # # and take the Cholesky factorization of the 2,2 block # # Q_2' * (H + GG^T * W^{-1} * W^{-T} * GG) * Q2. # Gs = W^{-T} * GG in packed storage. if mnl: Gs[:mnl, :] = Df Gs[mnl:, :] = G scale(Gs, W, trans = 'T', inverse = 'I') pack2(Gs, dims, mnl) # K = [Q1, Q2]' * (H + Gs' * Gs) * [Q1, Q2]. blas.syrk(Gs, K, k = cdim_pckd, trans = 'T') if H is not None: K[:,:] += H symm(K, n) lapack.ormqr(QA, tauA, K, side = 'L', trans = 'T') lapack.ormqr(QA, tauA, K, side = 'R') # Cholesky factorization of 2,2 block of K. lapack.potrf(K, n = n-p, offsetA = p*(n+1)) def solve(x, y, z): # Solve # # [ 0 A' GG'*W^{-1} ] [ ux ] [ bx ] # [ A 0 0 ] * [ uy ] = [ by ] # [ W^{-T}*GG 0 -I ] [ W*uz ] [ W^{-T}*bz ] # # and return ux, uy, W*uz. # # On entry, x, y, z contain bx, by, bz. On exit, they contain # the solution ux, uy, W*uz. # # If we change variables ux = Q1*v + Q2*w, the system becomes # # [ K11 K12 R ] [ v ] [Q1'*(bx+GG'*W^{-1}*W^{-T}*bz)] # [ K21 K22 0 ] * [ w ] = [Q2'*(bx+GG'*W^{-1}*W^{-T}*bz)] # [ R^T 0 0 ] [ uy ] [by ] # # W*uz = W^{-T} * ( GG*ux - bz ). # bzp := W^{-T} * bz in packed storage scale(z, W, trans = 'T', inverse = 'I') pack(z, bzp, dims, mnl) # x := [Q1, Q2]' * (x + Gs' * bzp) # = [Q1, Q2]' * (bx + Gs' * W^{-T} * bz) blas.gemv(Gs, bzp, x, beta = 1.0, trans = 'T', m = cdim_pckd) lapack.ormqr(QA, tauA, x, side = 'L', trans = 'T') # y := x[:p] # = Q1' * (bx + Gs' * W^{-T} * bz) blas.copy(y, yy) blas.copy(x, y, n = p) # x[:p] := v = R^{-T} * by blas.copy(yy, x) lapack.trtrs(QA, x, uplo = 'U', trans = 'T', n = p) # x[p:] := K22^{-1} * (x[p:] - K21*x[:p]) # = K22^{-1} * (Q2' * (bx + Gs' * W^{-T} * bz) - K21*v) blas.gemv(K, x, x, alpha = -1.0, beta = 1.0, m = n-p, n = p, offsetA = p, offsety = p) lapack.potrs(K, x, n = n-p, offsetA = p*(n+1), offsetB = p) # y := y - [K11, K12] * x # = Q1' * (bx + Gs' * W^{-T} * bz) - K11*v - K12*w blas.gemv(K, x, y, alpha = -1.0, beta = 1.0, m = p, n = n) # y := R^{-1}*y # = R^{-1} * (Q1' * (bx + Gs' * W^{-T} * bz) - K11*v # - K12*w) lapack.trtrs(QA, y, uplo = 'U', n = p) # x := [Q1, Q2] * x lapack.ormqr(QA, tauA, x, side = 'L') # bzp := Gs * x - bzp. # = W^{-T} * ( GG*ux - bz ) in packed storage. # Unpack and copy to z. blas.gemv(Gs, x, bzp, alpha = 1.0, beta = -1.0, m = cdim_pckd) unpack(bzp, z, dims, mnl) return solve return factor def kkt_chol2(G, dims, A, mnl = 0): """ Solution of KKT equations by reduction to a 2 x 2 system, a sparse or dense Cholesky factorization of order n to eliminate the 1,1 block, and a sparse or dense Cholesky factorization of order p. Implemented only for problems with no second-order or semidefinite cone constraints. Returns a function that (1) computes Cholesky factorizations of the matrices S = H + GG' * W^{-1} * W^{-T} * GG, K = A * S^{-1} *A' or (if K is singular in the first call to the function), the matrices S = H + GG' * W^{-1} * W^{-T} * GG + A' * A, K = A * S^{-1} * A', given H, Df, W, where GG = [Df; G], and (2) returns a function for solving [ H A' GG' ] [ ux ] [ bx ] [ A 0 0 ] * [ uy ] = [ by ]. [ GG 0 -W'*W ] [ uz ] [ bz ] H is n x n, A is p x n, Df is mnl x n, G is dims['l'] x n. """ if dims['q'] or dims['s']: raise ValueError("kktsolver option 'kkt_chol2' is implemented "\ "only for problems with no second-order or semidefinite cone "\ "constraints") p, n = A.size ml = dims['l'] F = {'firstcall': True, 'singular': False} def factor(W, H = None, Df = None): if F['firstcall']: if type(G) is matrix: F['Gs'] = matrix(0.0, G.size) else: F['Gs'] = spmatrix(0.0, G.I, G.J, G.size) if mnl: if type(Df) is matrix: F['Dfs'] = matrix(0.0, Df.size) else: F['Dfs'] = spmatrix(0.0, Df.I, Df.J, Df.size) if (mnl and type(Df) is matrix) or type(G) is matrix or \ type(H) is matrix: F['S'] = matrix(0.0, (n,n)) F['K'] = matrix(0.0, (p,p)) else: F['S'] = spmatrix([], [], [], (n,n), 'd') F['Sf'] = None if type(A) is matrix: F['K'] = matrix(0.0, (p,p)) else: F['K'] = spmatrix([], [], [], (p,p), 'd') # Dfs = Wnl^{-1} * Df if mnl: base.gemm(spmatrix(W['dnli'], list(range(mnl)), list(range(mnl))), Df, F['Dfs'], partial = True) # Gs = Wl^{-1} * G. base.gemm(spmatrix(W['di'], list(range(ml)), list(range(ml))), G, F['Gs'], partial = True) if F['firstcall']: base.syrk(F['Gs'], F['S'], trans = 'T') if mnl: base.syrk(F['Dfs'], F['S'], trans = 'T', beta = 1.0) if H is not None: F['S'] += H try: if type(F['S']) is matrix: lapack.potrf(F['S']) else: F['Sf'] = cholmod.symbolic(F['S']) cholmod.numeric(F['S'], F['Sf']) except ArithmeticError: F['singular'] = True if type(A) is matrix and type(F['S']) is spmatrix: F['S'] = matrix(0.0, (n,n)) base.syrk(F['Gs'], F['S'], trans = 'T') if mnl: base.syrk(F['Dfs'], F['S'], trans = 'T', beta = 1.0) base.syrk(A, F['S'], trans = 'T', beta = 1.0) if H is not None: F['S'] += H if type(F['S']) is matrix: lapack.potrf(F['S']) else: F['Sf'] = cholmod.symbolic(F['S']) cholmod.numeric(F['S'], F['Sf']) F['firstcall'] = False else: base.syrk(F['Gs'], F['S'], trans = 'T', partial = True) if mnl: base.syrk(F['Dfs'], F['S'], trans = 'T', beta = 1.0, partial = True) if H is not None: F['S'] += H if F['singular']: base.syrk(A, F['S'], trans = 'T', beta = 1.0, partial = True) if type(F['S']) is matrix: lapack.potrf(F['S']) else: cholmod.numeric(F['S'], F['Sf']) if type(F['S']) is matrix: # Asct := L^{-1}*A'. Factor K = Asct'*Asct. if type(A) is matrix: Asct = A.T else: Asct = matrix(A.T) blas.trsm(F['S'], Asct) blas.syrk(Asct, F['K'], trans = 'T') lapack.potrf(F['K']) else: # Asct := L^{-1}*P*A'. Factor K = Asct'*Asct. if type(A) is matrix: Asct = A.T cholmod.solve(F['Sf'], Asct, sys = 7) cholmod.solve(F['Sf'], Asct, sys = 4) blas.syrk(Asct, F['K'], trans = 'T') lapack.potrf(F['K']) else: Asct = cholmod.spsolve(F['Sf'], A.T, sys = 7) Asct = cholmod.spsolve(F['Sf'], Asct, sys = 4) base.syrk(Asct, F['K'], trans = 'T') Kf = cholmod.symbolic(F['K']) cholmod.numeric(F['K'], Kf) def solve(x, y, z): # Solve # # [ H A' GG'*W^{-1} ] [ ux ] [ bx ] # [ A 0 0 ] * [ uy ] = [ by ] # [ W^{-T}*GG 0 -I ] [ W*uz ] [ W^{-T}*bz ] # # and return ux, uy, W*uz. # # If not F['singular']: # # K*uy = A * S^{-1} * ( bx + GG'*W^{-1}*W^{-T}*bz ) - by # S*ux = bx + GG'*W^{-1}*W^{-T}*bz - A'*uy # W*uz = W^{-T} * ( GG*ux - bz ). # # If F['singular']: # # K*uy = A * S^{-1} * ( bx + GG'*W^{-1}*W^{-T}*bz + A'*by ) # - by # S*ux = bx + GG'*W^{-1}*W^{-T}*bz + A'*by - A'*y. # W*uz = W^{-T} * ( GG*ux - bz ). # z := W^{-1} * z = W^{-1} * bz scale(z, W, trans = 'T', inverse = 'I') # If not F['singular']: # x := L^{-1} * P * (x + GGs'*z) # = L^{-1} * P * (x + GG'*W^{-1}*W^{-T}*bz) # # If F['singular']: # x := L^{-1} * P * (x + GGs'*z + A'*y)) # = L^{-1} * P * (x + GG'*W^{-1}*W^{-T}*bz + A'*y) if mnl: base.gemv(F['Dfs'], z, x, trans = 'T', beta = 1.0) base.gemv(F['Gs'], z, x, offsetx = mnl, trans = 'T', beta = 1.0) if F['singular']: base.gemv(A, y, x, trans = 'T', beta = 1.0) if type(F['S']) is matrix: blas.trsv(F['S'], x) else: cholmod.solve(F['Sf'], x, sys = 7) cholmod.solve(F['Sf'], x, sys = 4) # y := K^{-1} * (Asc*x - y) # = K^{-1} * (A * S^{-1} * (bx + GG'*W^{-1}*W^{-T}*bz) - by) # (if not F['singular']) # = K^{-1} * (A * S^{-1} * (bx + GG'*W^{-1}*W^{-T}*bz + # A'*by) - by) # (if F['singular']). base.gemv(Asct, x, y, trans = 'T', beta = -1.0) if type(F['K']) is matrix: lapack.potrs(F['K'], y) else: cholmod.solve(Kf, y) # x := P' * L^{-T} * (x - Asc'*y) # = S^{-1} * (bx + GG'*W^{-1}*W^{-T}*bz - A'*y) # (if not F['singular']) # = S^{-1} * (bx + GG'*W^{-1}*W^{-T}*bz + A'*by - A'*y) # (if F['singular']) base.gemv(Asct, y, x, alpha = -1.0, beta = 1.0) if type(F['S']) is matrix: blas.trsv(F['S'], x, trans='T') else: cholmod.solve(F['Sf'], x, sys = 5) cholmod.solve(F['Sf'], x, sys = 8) # W*z := GGs*x - z = W^{-T} * (GG*x - bz) if mnl: base.gemv(F['Dfs'], x, z, beta = -1.0) base.gemv(F['Gs'], x, z, beta = -1.0, offsety = mnl) return solve return factor def kkt_qr(G, dims, A): """ Solution of KKT equations with zero 1,1 block, by eliminating the equality constraints via a QR factorization, and solving the reduced KKT system by another QR factorization. Computes the QR factorization A' = [Q1, Q2] * [R1; 0] and returns a function that (1) computes the QR factorization W^{-T} * G * Q2 = Q3 * R3 (with columns of W^{-T}*G in packed storage), and (2) returns a function for solving [ 0 A' G' ] [ ux ] [ bx ] [ A 0 0 ] * [ uy ] = [ by ]. [ G 0 -W'*W ] [ uz ] [ bz ] A is p x n and G is N x n where N = dims['l'] + sum(dims['q']) + sum( k**2 for k in dims['s'] ). """ p, n = A.size cdim = dims['l'] + sum(dims['q']) + sum([ k**2 for k in dims['s'] ]) cdim_pckd = dims['l'] + sum(dims['q']) + sum([ int(k*(k+1)/2) for k in dims['s'] ]) # A' = [Q1, Q2] * [R1; 0] if type(A) is matrix: QA = +A.T else: QA = matrix(A.T) tauA = matrix(0.0, (p,1)) lapack.geqrf(QA, tauA) Gs = matrix(0.0, (cdim, n)) tauG = matrix(0.0, (n-p,1)) u = matrix(0.0, (cdim_pckd, 1)) vv = matrix(0.0, (n,1)) w = matrix(0.0, (cdim_pckd, 1)) def factor(W): # Gs = W^{-T}*G, in packed storage. Gs[:,:] = G scale(Gs, W, trans = 'T', inverse = 'I') pack2(Gs, dims) # Gs := [ Gs1, Gs2 ] # = Gs * [ Q1, Q2 ] lapack.ormqr(QA, tauA, Gs, side = 'R', m = cdim_pckd) # QR factorization Gs2 := [ Q3, Q4 ] * [ R3; 0 ] lapack.geqrf(Gs, tauG, n = n-p, m = cdim_pckd, offsetA = Gs.size[0]*p) def solve(x, y, z): # On entry, x, y, z contain bx, by, bz. On exit, they # contain the solution x, y, W*z of # # [ 0 A' G'*W^{-1} ] [ x ] [bx ] # [ A 0 0 ] * [ y ] = [by ]. # [ W^{-T}*G 0 -I ] [ W*z ] [W^{-T}*bz] # # The system is solved in five steps: # # w := W^{-T}*bz - Gs1*R1^{-T}*by # u := R3^{-T}*Q2'*bx + Q3'*w # W*z := Q3*u - w # y := R1^{-1} * (Q1'*bx - Gs1'*(W*z)) # x := [ Q1, Q2 ] * [ R1^{-T}*by; R3^{-1}*u ] # w := W^{-T} * bz in packed storage scale(z, W, trans = 'T', inverse = 'I') pack(z, w, dims) # vv := [ Q1'*bx; R3^{-T}*Q2'*bx ] blas.copy(x, vv) lapack.ormqr(QA, tauA, vv, trans='T') lapack.trtrs(Gs, vv, uplo = 'U', trans = 'T', n = n-p, offsetA = Gs.size[0]*p, offsetB = p) # x[:p] := R1^{-T} * by blas.copy(y, x) lapack.trtrs(QA, x, uplo = 'U', trans = 'T', n = p) # w := w - Gs1 * x[:p] # = W^{-T}*bz - Gs1*by blas.gemv(Gs, x, w, alpha = -1.0, beta = 1.0, n = p, m = cdim_pckd) # u := [ Q3'*w + v[p:]; 0 ] # = [ Q3'*w + R3^{-T}*Q2'*bx; 0 ] blas.copy(w, u) lapack.ormqr(Gs, tauG, u, trans = 'T', k = n-p, offsetA = Gs.size[0]*p, m = cdim_pckd) blas.axpy(vv, u, offsetx = p, n = n-p) blas.scal(0.0, u, offset = n-p) # x[p:] := R3^{-1} * u[:n-p] blas.copy(u, x, offsety = p, n = n-p) lapack.trtrs(Gs, x, uplo='U', n = n-p, offsetA = Gs.size[0]*p, offsetB = p) # x is now [ R1^{-T}*by; R3^{-1}*u[:n-p] ] # x := [Q1 Q2]*x lapack.ormqr(QA, tauA, x) # u := [Q3, Q4] * u - w # = Q3 * u[:n-p] - w lapack.ormqr(Gs, tauG, u, k = n-p, m = cdim_pckd, offsetA = Gs.size[0]*p) blas.axpy(w, u, alpha = -1.0) # y := R1^{-1} * ( v[:p] - Gs1'*u ) # = R1^{-1} * ( Q1'*bx - Gs1'*u ) blas.copy(vv, y, n = p) blas.gemv(Gs, u, y, m = cdim_pckd, n = p, trans = 'T', alpha = -1.0, beta = 1.0) lapack.trtrs(QA, y, uplo = 'U', n=p) unpack(u, z, dims) return solve return factor
Python
UTF-8
455
2.734375
3
[]
no_license
import heapq N, M = map(int, input().split()) AB = (list(map(int, input().split())) for _ in range(N)) AB = sorted(AB, key=lambda x: x[0]) hq = [] ind = 0 ans = 0 for lim in range(1, M + 1): for i in range(ind, N): if AB[i][0] == lim: AB[i][0], AB[i][1] = -AB[i][1], AB[i][0] heapq.heappush(hq, AB[i]) ind += 1 else: break if hq: ans += -heapq.heappop(hq)[0] print(ans)
Python
UTF-8
1,169
3.03125
3
[]
no_license
from sklearn.ensemble import AdaBoostClassifier from sklearn import datasets from sklearn.model_selection import train_test_split # классификатор опорных векторов from sklearn.svm import SVC from sklearn import metrics # загрузка датасета iris = datasets.load_iris() X = iris.data y = iris.target # разделение данных на обучающие и проверочные X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) # 70% обучающих и 30% тестовых # SVC в качестве базовой оценки svc = SVC(probability=True, kernel='linear') # классификатор adaboost abc = AdaBoostClassifier(n_estimators=50, base_estimator=svc, learning_rate=1) # обучение Adaboost классификатора model = abc.fit(X_train, y_train) # предсказание ответа для тестового набора данных y_pred = model.predict(X_test) # точность модели(как часто классификатор верно предсказывает ответы) print("Accuracy:", metrics.accuracy_score(y_test, y_pred))
Python
UTF-8
1,376
3.15625
3
[]
no_license
from __future__ import division, print_function # PHY407, Fall 2015, Q3 __author__ = "DUONG, BANG CHI" # Import modules from numpy import zeros, sin, pi from matplotlib.pyplot import plot, legend, xlabel, ylabel, title, show, xlim def T0(t): A = 10 B = 12 tau = 365 # days = 12 months return A + B*sin(2*pi*t/tau) L = 20 # Depth in meters D = 0.1 # Thermal diffusivity, m**2/days N = 100 # Number of divisions in grid a = L/N # Grid spacing h = 0.01 # Time-step #epsilon = h/1000 # Define an array for temperature T = zeros(N+1,float) # Temperature everywhere equal to 10C, except at the surface and the deepest point T[1:N]=10 # Iteration def iterate(T, t_min, t_max): # Main loop t = t_min c = h*D/a**2 while t < t_max: # Calculate the new values of T T[0] = T0(t) T[N] = 11 T[1:N] = T[1:N] + c*(T[2:N+1]+T[0:N-1]-2*T[1:N]) t += h return T T9 = iterate(T, 0, 365*9) T9_i = T9 t_min = 365*9 # end of the 9th year # Plot for i in range(4): for t_max in [t_min + i*(365//4)]: #t_max = t_min + 365//4 T9_i = iterate(T9_i, t_min, t_max) plot(T9_i, label = "the {}(st/nd/rd/th) 3-month intervals of the 10th year".format(i+1)) t_min = t_max legend(prop={'size':11}).draggable() xlabel("Depth (m)") ylabel("Temperature (degree C)") xlim(0,20) title("Thermal Diffusion in Earth's Crust") show()
Java
UTF-8
1,212
4
4
[]
no_license
import java.util.Random; @SuppressWarnings("javadoc") public class GuessingGame2 { private int secret; public GuessingGame2(int secret) { this.secret = secret; } public boolean guessWins(int guess) { return guess == this.secret; } public String messageForGuess(int guess) { if (guess > this.secret) { return "Too high!"; } else if (guess < this.secret) { return "Too low!"; } else { return "You've won!"; } } public int directionOfGuess(int guess) { if (guess > this.secret) { return -1; // make it smaller next time } else if (guess < this.secret) { return +1; // make it bigger next time } else { return 0; } } public static void main(String[] args) { Random rand = new Random(); GuessingGame2 game = new GuessingGame2(rand.nextInt(100)); int min = 0; int max = 100; int guess = 50; while (!game.guessWins(guess)) { guess = (min + max) / 2; int resp = game.directionOfGuess(guess); if (resp == 0) { break; } else if (resp == -1) { max = guess; } else { min = guess; } System.out.println("You guessed '" + guess + "': " + game.messageForGuess(guess)); } System.out.println("You got it: "+guess); } }
Markdown
UTF-8
1,060
3.25
3
[]
no_license
# thinkful-quiz-app This is a quiz app that I made as part of Thinkful's Frontend Web Development Course ## Introduction This is one of the earlier projects I made in the Thinkful coding bootcamp course. The focus of this project was to use jQuery to create a quiz app based on a subject of your choosing. I chose to make my quiz about movies, since I'm a big movie buff and a fan of movie-related trivia. ## Programming Skills Used This project uses jQuery to create an interactive application that responds to the user's actions (ie click events) to lead users through the quiz. After each question, the user is notified what the correct answer for that question was. At the end of the quiz, the user receives their score, and various messages will display depending on what score the user got. Later in the course, I went back to this project and added Gulp build tools to the project to automate my build tasks and compile my code into smaller files to help speed up page load. It was also a good way to practice and solidfy my understanding of Gulp.js.
Java
UTF-8
604
2.15625
2
[]
no_license
package com.qyer.javaapi.rest.service; import org.springframework.stereotype.Component; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** * Created by panqiang on 2017/5/14. */ @Component @Path("/") public class HomeServer { // This method is called if TEXT_PLAIN is request @GET @Produces(MediaType.TEXT_PLAIN) public String sayHomeGet() { return "qyer-api"; } @POST @Produces(MediaType.TEXT_PLAIN) public String sayHomePost() { return "qyer-api"; } }
JavaScript
UTF-8
894
2.890625
3
[]
no_license
'use strict'; const path = require('path'); const fs = require('fs'); // Based on your application's initial performance score, you may want to adjust this threshold. // 1 is 100%; 0.91 is 91% etc. const PERFORMANCE_THRESHOLD = 0.9; const [reportPath] = process.argv.slice(2); if (!reportPath) { throw new RangeError('Please specify JSON report path. Usage: node verify-performance-results.js <report-path>'); } const report = JSON.parse(fs.readFileSync(path.join(__dirname, '..', reportPath), 'utf8')); const score = report.categories.performance.score; const isScorePassing = !isNaN(score) && score >= PERFORMANCE_THRESHOLD; if (isScorePassing) { console.log(`Peformance test passed with a score of ${score}.`); process.exit(0); } else { console.log(`Peformance test failed with a score of ${score}. Minimum required score is ${PERFORMANCE_THRESHOLD}.`); process.exit(1); }
Java
UTF-8
829
3.53125
4
[]
no_license
package algorithm.chapter3.template.greedy; /** * 【45. 跳跃游戏 II】给定一个非负整数数组,你最初位于数组的第一个位置。 数组中的每个元素代表你在该位置可以跳跃的最大长度。 * 你的目标是使用最少的跳跃次数到达数组的最后一个位置。 示例: 输入: [2,3,1,1,4] 输出: 2 解释: 跳到最后一个位置的最小跳跃数是 2。   * 从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/jump-game-ii * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * * @author chying * */ public class LeetCode_45_519 { public int jump(int[] nums) { return 0; } }
Java
UTF-8
1,112
2.9375
3
[]
no_license
package ru.ifmo.ctddev.isaev; import java.io.Serializable; /** * Created by isae on 07.04.15. */ public enum Token implements LexicalUnit { LPAREN("(","("), RPAREN(")",")"), PLUS("+","+"), MINUS("-","-"), MUL("*","*"), END("$","$"), EPS("","eps"); String token; String graphName; Token(String token, String graphName) { this.token = token; this.graphName = graphName; } @Override public String getStringRepresentation() { return token; } public static Token fromChar(char curChar) { for (Token t : values()) { if (t != END && t != EPS) { if (t.token.equals(Character.toString(curChar))) { return t; } } } return null; } @Override public boolean equalsLexically(LexicalUnit other) { return this == other; } @Override public String getGraphRepresentation() { return graphName; } @Override public String toString() { return token == null ? "" : token; } }
C#
UTF-8
1,396
3.671875
4
[]
no_license
using System; namespace praca_domowa_5 { public class Menu { string name; Product[] products; public Menu() { this.name = "Food Hall"; this.products = new Product[] { new Product("Sushi", 33.59), new Product("Ramen", 31.50), new Product("Zielona herbata", 12.39), new Product("Hummus", 17.29), new Product("Vege burger", 29.99) }; } public void ShowMenu(int capacity) { if (capacity > 0) { Console.WriteLine("Czy chcesz jeszcze coś zamówić?"); } else { Console.WriteLine("Witamy w " + this.name + ", co podać?"); } for(int i = 0; i < 5; i++) { Console.WriteLine((i+1) + ". " + this.products[i].name + " - " + this.products[i].price + " zł."); } Console.WriteLine("6. Koniec zamówienia"); Console.WriteLine("7. Usuń z zamówienia"); } public Product ChooseProduct(int choice) { if (choice <= 0 || choice >= 8) { Console.WriteLine("Takiej pozycji raczej nie mamy w Menju, joł"); return null; } return this.products[--choice]; } } }
C++
UTF-8
3,986
3.5
4
[ "Apache-2.0" ]
permissive
#pragma once namespace lazy { template<class T> class Value { public: Value(const T& v) :value(v) {} template<class Enable = std::enable_if_t<std::is_arithmetic_v<T>>> /*explicit*/ operator T() const { return value; } template<class Enable = std::enable_if_t<std::is_invocable_v<T>>> auto operator()() const { return value(); } private: T value; }; template<typename T> concept LazyRequired = requires(T v) { std::is_arithmetic_v<T> || std::is_invocable_v<T>; }; // + template<LazyRequired T1, LazyRequired T2, bool IsInvocable1 = std::is_invocable_v<T1>, bool IsInvocable2 = std::is_invocable_v<T2>> auto operator+(const Value<T1>& value1, const T2& value2) { if constexpr (IsInvocable1) { if constexpr (IsInvocable2) { return Value([&] {return value1() + value2(); }); } else { return Value([&] {return value1() + static_cast<T2>(value2); }); } } else { if constexpr (IsInvocable2) { return Value([&] {return static_cast<T1>(value1) + value2(); }); } else { return Value([&] {return static_cast<T1>(value1) + value2; }); } } } // - template<LazyRequired T1, LazyRequired T2, bool IsInvocable1 = std::is_invocable_v<T1>, bool IsInvocable2 = std::is_invocable_v<T2>> auto operator-(const Value<T1>& value1, const T2& value2) { if constexpr (IsInvocable1) { if constexpr (IsInvocable2) { return Value([&] {return value1() - value2(); }); } else { return Value([&] {return value1() - static_cast<T2>(value2); }); } } else { if constexpr (IsInvocable2) { return Value([&] {return static_cast<T1>(value1) - value2(); }); } else { return Value([&] {return static_cast<T1>(value1) - value2; }); } } } // * template<LazyRequired T1, LazyRequired T2, bool IsInvocable1 = std::is_invocable_v<T1>, bool IsInvocable2 = std::is_invocable_v<T2>> auto operator*(const Value<T1>& value1, const T2& value2) { if constexpr (IsInvocable1) { if constexpr (IsInvocable2) { return Value([&] {return value1() * value2(); }); } else { return Value([&] {return value2 == 0 ? 0 : value1() * static_cast<T2>(value2); }); } } else { if constexpr (IsInvocable2) { return Value([&] {return value1 == 0 ? 0 : static_cast<T1>(value1) * value2(); }); } else { return Value([&] {return static_cast<T1>(value1) * value2; }); } } } // / template<LazyRequired T1, LazyRequired T2, bool IsInvocable1 = std::is_invocable_v<T1>, bool IsInvocable2 = std::is_invocable_v<T2>> auto operator/(const Value<T1>& value1, const T2& value2) { if constexpr (IsInvocable1) { if constexpr (IsInvocable2) { return Value([&] {return value1() / value2(); }); } else { return Value([&] {return value1() / static_cast<T2>(value2); }); } } else { if constexpr (IsInvocable2) { return Value([&] {return value1 == 0 ? 0 : static_cast<T1>(value1) / value2(); }); } else { return Value([&] {return static_cast<T1>(value1) / value2; }); } } } template<LazyRequired T1, LazyRequired T2, bool IsInvocable1 = std::is_invocable_v<T1>, bool IsInvocable2 = std::is_invocable_v<T2>> auto pow(const T1& base, const T2& index) { if constexpr (IsInvocable1) { if constexpr (IsInvocable2) { return Value([&] {return std::pow(base(), index()); }); } else { return Value([&] {return index == 0 ? 1 : std::pow(base(), index); }); } } else { if constexpr (IsInvocable2) { return Value([&] {return base == 1 ? 1 : std::pow(base, index()); }); } else { return Value([&] {return std::pow(base, index); }); } } } template<LazyRequired T, bool IsArithmetic = std::is_arithmetic_v<T>> auto log(const T& value) { if constexpr (IsArithmetic) { return Value([&] {return value == 1 ? 0 : std::log(value); }); } else { return Value([&] {return std::log(value()); }); } } }
C++
UTF-8
5,363
2.9375
3
[]
no_license
// // Created by MARTIN Benoît on 03/01/2019. // #ifndef MEMORY_CHAINED_BLOCK_ALLOCATOR_H #define MEMORY_CHAINED_BLOCK_ALLOCATOR_H #include <memory> #include <cassert> #include <forward_list> #ifndef NDEBUG #include <iostream> #endif namespace root88 { namespace memory { /** * ChainedBlockAllocator * STL compliant allocator * * @tparam _T type * * Chained blocks of * | 1 | 2 | 4 | 8 | 16 | 32 | 64 | ... | (1<<BLOCK_LIST_SIZE) * B B B B * B B * B */ template <typename _T> class ChainedBlockAllocator { private: using BlockList = std::forward_list<std::unique_ptr<_T[]>>; using blockListIndex_t = uint8_t; static constexpr blockListIndex_t BLOCK_LIST_SIZE = 64; public: class Test; typedef _T value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef _T* pointer; typedef const _T* const_pointer; typedef _T& reference; typedef const _T& const_reference; ChainedBlockAllocator() : unallocatedBlockListArray(new BlockList[BLOCK_LIST_SIZE]) { #ifndef NDEBUG std::cout << "ChainedBlockAllocator::ChainedBlockAllocator()" << std::endl; #endif // init(); } /** * Copy constructor. * The resulting instance will have the same number of allocated blocks. * Allocated values are not copied. * @param other allocator from which the structure will be copied. */ ChainedBlockAllocator(const ChainedBlockAllocator& other) : ChainedBlockAllocator() { #ifndef NDEBUG std::cout << "ChainedBlockAllocator::ChainedBlockAllocator(const ChainedBlockAllocator&)" << std::endl; #endif for(blockListIndex_t i=0; i<BLOCK_LIST_SIZE; ++i) { auto nbBlocks = std::distance(other.unallocatedBlockListArray[i].begin(), other.unallocatedBlockListArray[i].end()); for(; nbBlocks>0; --nbBlocks, allocateNewBlock(i)); } } ChainedBlockAllocator(ChainedBlockAllocator&&) = delete; ~ChainedBlockAllocator() noexcept { #ifndef NDEBUG std::cout << "ChainedBlockAllocator::~ChainedBlockAllocator()" << std::endl; #endif // for(blockListIndex_t i=0; i<BLOCK_LIST_SIZE; ++i) { // unallocatedBlockListArray[i].clear(); // } }; pointer allocate(size_type n, __attribute__((unused)) const_pointer hint=nullptr) { #ifndef NDEBUG std::cout << "ChainedBlockAllocator::allocate(n=" << n << ")" << std::endl; #endif blockListIndex_t index = indexFromBlockSize(n); auto& blockList = unallocatedBlockListArray[index]; if(blockList.empty()) { allocateNewBlock(index); } assert(not blockList.empty()); _T* p = blockList.front().release(); assert(nullptr != p); blockList.pop_front(); return p; } void deallocate(pointer p, size_type n) { #ifndef NDEBUG std::cout << "ChainedBlockAllocator::deallocate(" << static_cast<void*>(p) << ", " << n << ")" << std::endl; #endif blockListIndex_t index = indexFromBlockSize(n); size_t blockSize = blockSizeFromIndex(index); unallocatedBlockListArray[index].emplace_front(new (p) _T[blockSize]); } template <typename _U> struct rebind { typedef ChainedBlockAllocator<_U> other; }; void construct(pointer p, const_reference clone) { new (p) _T(clone); } void destroy(pointer p) { p->~_T(); } pointer address(reference x) const { return &x; } const_pointer address(const_reference x) const { return &x; } bool operator==(const ChainedBlockAllocator &rhs) { return unallocatedBlockListArray.get() == rhs.unallocatedBlockListArray.get(); } bool operator!=(const ChainedBlockAllocator &rhs) { return !operator==(rhs); } private: void allocateNewBlock(const blockListIndex_t index) { assert(index < BLOCK_LIST_SIZE); const size_t blockSize = blockSizeFromIndex(index); #ifndef NDEBUG std::cout << "ChainedBlockAllocator::allocateNewBlock(index=" << unsigned(index) << "): blockSize=" << blockSize << std::endl; #endif unallocatedBlockListArray[index].emplace_front(new _T[blockSize]); } /** * Return an index to the inner blockListArray. Value will be between 0 and BLOCK_LIST_SIZE-1 * @param size block size * @return index */ inline blockListIndex_t indexFromBlockSize(size_t size) const noexcept { blockListIndex_t index=0; // size >> index // while(size >>= 1) { // ++index; // } for(;size >>= 1; ++index); assert(index < BLOCK_LIST_SIZE); return index; } inline size_t blockSizeFromIndex(const blockListIndex_t index) const noexcept { #ifndef NDEBUG std::cout << "ChainedBlockAllocator::blockSizeFromIndex(index=" << (unsigned)index << "): blockSize=" << (size_t(1) << index) << std::endl; #endif return size_t(1) << index; } void init(const blockListIndex_t maxIndex=BLOCK_LIST_SIZE/2) { for(blockListIndex_t i=0; i<maxIndex; ++i) { allocateNewBlock(i); } } private: std::unique_ptr<BlockList[]> unallocatedBlockListArray; }; } // namespace allocator } // namespace root88 #endif //MEMORY_CHAINED_BLOCK_ALLOCATOR_H
PHP
UTF-8
1,823
2.984375
3
[ "MIT" ]
permissive
<?php namespace vps\tools\helpers; /** * Class RemoteFileHelper * @package vps\tools\helpers */ class RemoteFileHelper extends \yii\helpers\BaseFileHelper { /** * Checks if file is local. * ```php * RemoteFileHelper::isLocal('https://google.com'); * // return false * ``` * @param $path * @return boolean */ public static function isLocal ($path) { return file_exists($path); } /** * Checks whether file exists. * ```php * RemoteFileHelper::exists('https://google.com'); * // return true * ``` * @param string $path Path to file * @return boolean Whether file exists. */ public static function exists ($path) { if (file_exists($path)) return true; $c = curl_init($path); curl_setopt($c, CURLOPT_NOBODY, true); curl_setopt($c, CURLOPT_FOLLOWLOCATION, true); curl_exec($c); $code = curl_getinfo($c, CURLINFO_HTTP_CODE); curl_close($c); return ( $code == 200 ); } /** * Saves remote file by chunks. * ```php * RemoteFileHelper::save('https://google.com', 'google.html'); * // return true * ``` * @param string $sourcepath * @param string $targetpath * @param integer $chunksize Chunk size in bytes. Default is 1MB. * @return boolean Whether file is successfully saved. */ public static function save ($sourcepath, $targetpath, $chunksize = 1048576) { if (file_exists($targetpath)) unlink($targetpath); if (self::exists($sourcepath)) { $remote = fopen($sourcepath, 'rb'); $local = fopen($targetpath, 'w'); while (!feof($remote)) { $data = fread($remote, $chunksize); fwrite($local, $data, strlen($data)); } return fclose($remote); } trigger_error('File path does not exist.', E_USER_WARNING); return false; } }
Java
UTF-8
614
2.6875
3
[]
no_license
package net.test; import java.util.Calendar; import java.util.HashMap; import java.util.Map; public class Solution { Map<String, Integer> dayIndex = new HashMap<String, Integer>(); Map<String, Integer> monthIndex = new HashMap<String, Integer>(); Map<String, Integer> monthLength = new HashMap<String, Integer>(); int[] monthLenght = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; public int solution(int Y, String A, String B, String W) { // write your code in Java SE 8 if(Y < 2001 || Y > 2099){ return 0; } Calendar cal = Calendar.Builder(); cal.set(Y, A); } }
Python
UTF-8
2,217
2.65625
3
[]
no_license
from app import db import os import shutil class SolutionFile(db.Model): __tablename__ = "solution_file" id = db.Column(db.Integer, index=True, primary_key=True) name = db.Column(db.String(128), index=True) solution_id = db.Column(db.Integer, db.ForeignKey("solution.id")) solution = db.relationship("Solution", back_populates="files") def __init__(self, **kwargs): super(SolutionFile, self).__init__(**kwargs) file = kwargs.get("file") if file: self.create_file(file) def create_file(self, file): file.save(self.relative_file_path) def delete_file(self): if os.path.exists(self.relative_file_path): os.remove(self.relative_file_path) @property def file_path(self): return self.solution.solutions_dir + "/" + str(self.id) @property def relative_file_path(self): return self.file_path[1:] @property def content(self): try: return open(self.relative_file_path, "r").read() except UnicodeDecodeError: return "Unable to display content." class Solution(db.Model): __tablename__ = "solution" id = db.Column(db.Integer, index=True, primary_key=True) name = db.Column(db.String(128), index=True) description = db.Column(db.String(4096)) cohort_id = db.Column(db.Integer, db.ForeignKey("cohort.id")) cohort = db.relationship("Cohort", back_populates="solutions") files = db.relationship("SolutionFile", back_populates="solution") def create_dir(self): cohort_solutions_dir = "/".join(self.relative_solutions_dir.split("/")[:-1]) if not os.path.isdir(cohort_solutions_dir): os.mkdir(cohort_solutions_dir) if not os.path.isdir(self.relative_solutions_dir): os.mkdir(self.relative_solutions_dir) def delete_dir(self): if os.path.isdir(self.relative_solutions_dir): shutil.rmtree(self.relative_solutions_dir) @property def solutions_dir(self): return "/static/protected/solutions/" + str(self.cohort_id) + "/" + str(self.id) @property def relative_solutions_dir(self): return self.solutions_dir[1:]
Python
UTF-8
496
3.546875
4
[ "MIT" ]
permissive
class Vocab: def __init__(self, name): self.name = name self.word_index = {} self.word_count = {} self.index_word = {0: "SOS", 1: "EOS"} self.num_words = 2 def add_sentence(self, sentence): for word in sentence.split(' '): self.add_word(word) def add_word(self, word): if word not in self.word_index: self.word_index[word] = self.num_words self.word_count[word] = 1 self.index_word[self.num_words] = word self.num_words += 1 else: self.word_count[word] += 1
Java
UTF-8
548
2.734375
3
[]
no_license
package apm.muei.distancenevermatters.entities; public class Dice { private Long id; private String name; private int value; private int img; public Dice(Long id, String name, int value, int img) { this.id = id; this.name = name; this.value = value; this.img = img; } public Long getId() { return id; } public String getName() { return name; } public int getValue() { return value; } public int getImg() { return img; } }
Java
UTF-8
5,609
2.078125
2
[]
no_license
package medoffice.entity; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; @Entity @Table(name = "visit_hpi") public class VisitHpi implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @Column(name = "visit_id") private Integer visitId; @JoinColumn(name = "visit_id", insertable = false, updatable = false) @ManyToOne(fetch = FetchType.LAZY) private Visit visit; @Column(name = "location") private String location; @Column(name = "quality") private String quality; @Column(name = "severity") private Integer severity; @Column(name = "duration") private String duration; @Column(name = "timing") private String timing; @Column(name = "context") private String context; @Column(name = "modifying_factors") private String modifyingFactors; @Column(name = "associated_signs_and_symptoms") private String associatedSignsAndSymptoms; @Column(name = "radiation") private String radiation; @Column(name = "free_form_text") private String freeFormText; @Transient private boolean persisted = true; public Integer getVisitId() { return visitId; } public void setVisitId(Integer visitId) { this.visitId = visitId; } public Visit getVisit() { return visit; } public void setVisit(Visit visit) { this.visit = visit; } public boolean emptyData() { return (getHpiTotal() == 0 && freeFormText == null); } public int getHpiTotal() { int total = 0; if (location != null && !location.isEmpty()) { total++; } if (quality != null && !quality.isEmpty()) { total++; } if (severity != null) { total++; } if (duration != null && !duration.isEmpty()) { total++; } if (timing != null && !timing.isEmpty()) { total++; } if (context != null && !context.isEmpty()) { total++; } if (modifyingFactors != null && !modifyingFactors.isEmpty()) { total++; } if (associatedSignsAndSymptoms != null && !associatedSignsAndSymptoms.isEmpty()) { total++; } if (radiation != null && !radiation.isEmpty()) { total++; } return total; } public String getHpiLevel() { String level = null; int total = getHpiTotal(); if (total == 0) { level = "None"; } else if (total >= 1 && total <= 3) { level = "Brief"; } else if (total >= 4) { level = "Extended"; } return level; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getQuality() { return quality; } public void setQuality(String quality) { this.quality = quality; } public Integer getSeverity() { return severity; } public void setSeverity(Integer severity) { this.severity = severity; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public String getTiming() { return timing; } public void setTiming(String timing) { this.timing = timing; } public String getContext() { return context; } public void setContext(String context) { this.context = context; } public String getModifyingFactors() { return modifyingFactors; } public void setModifyingFactors(String modifyingFactors) { this.modifyingFactors = modifyingFactors; } public String getAssociatedSignsAndSymptoms() { return associatedSignsAndSymptoms; } public void setAssociatedSignsAndSymptoms(String associatedSignsAndSymptoms) { this.associatedSignsAndSymptoms = associatedSignsAndSymptoms; } public String getRadiation() { return radiation; } public void setRadiation(String radiation) { this.radiation = radiation; } public String getFreeFormText() { return freeFormText; } public void setFreeFormText(String freeFormText) { this.freeFormText = freeFormText; } public boolean isPersisted() { return persisted; } public void setPersisted(boolean persisted) { this.persisted = persisted; } @Override public int hashCode() { int hash = 0; hash += (visitId != null ? visitId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof VisitHpi)) { return false; } VisitHpi other = (VisitHpi) object; if ((this.visitId == null && other.visitId != null) || (this.visitId != null && !this.visitId.equals(other.visitId))) { return false; } return true; } @Override public String toString() { return "medoffice.entity.VisitHpi[visitId=" + visitId + "]"; } }
Java
UTF-8
110
1.84375
2
[]
no_license
package lambdaMethodRef; public interface ConvertBeta { String convert(String str, int a, int b); }
Java
UTF-8
89
1.726563
2
[]
no_license
class ArrayUtilities { static arrayToList(int[] args) { int firstInt = args[0] } }
JavaScript
UTF-8
27,016
2.75
3
[]
no_license
function onPageLoad () { if (window.location.search.length > 0) { console.log("code exists"); handleRedirect(); } } async function createPlaylist(data) { //make create playlist request first let userid = window.localStorage.getItem("userid"); let username = window.localStorage.getItem("username"); let endpoint = `https://api.spotify.com/v1/users/${userid}/playlists`; let query = ""; let body = { "name": `${username}'s Top 50 songs`, "public": 'true', "description": `A playlist of ${username}'s top 50 songs of all time.` }; let playlist = await callAPI("POST", endpoint, "", body); console.log(playlist); //insert items console.log(playlist.id); console.log(data); endpoint = `https://api.spotify.com/v1/playlists/${playlist.id}/tracks`; query = ""; let uris = new Array(); for (let song of data.items) { uris.push(song.uri); //console.log(song.uri); } body = { "uris": uris } let snapshot = await callAPI("POST", endpoint, "", body); console.log(playlist); console.log(snapshot); let istream = document.querySelector("#playlist-embed"); istream.innerHTML = `<iframe src='https://open.spotify.com/embed/playlist/${playlist.id}' id="playlist" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>`; } function renderList(data, type) { if (type === "artists") { //first let pos = document.querySelector("#first > p"); let img = document.querySelector("#first > img"); pos.innerHTML = data.items[0].name; img.src = data.items[0].images[0].url; //second pos = document.querySelector("#second > p"); img = document.querySelector("#second > img"); pos.innerHTML = data.items[1].name; img.src = data.items[1].images[0].url; //third pos = document.querySelector("#third > p"); img = document.querySelector("#third > img"); pos.innerHTML = data.items[2].name; img.src = data.items[2].images[0].url; let list = document.querySelector("#rest-of-list"); list.innerHTML = ""; for (i = 3; i < data.items.length; i++) { //console.log(data.items[i].name); list.innerHTML += `<li>${data.items[i].name}</li>` } } else if (type === "tracks") { //first let pos = document.querySelector("#first > p"); let img = document.querySelector("#first > img"); pos.innerHTML = data.items[0].name; img.src = data.items[0].album.images[0].url; //second pos = document.querySelector("#second > p"); img = document.querySelector("#second > img"); pos.innerHTML = data.items[1].name; img.src = data.items[1].album.images[0].url; //third pos = document.querySelector("#third > p"); img = document.querySelector("#third > img"); pos.innerHTML = data.items[2].name; img.src = data.items[2].album.images[0].url; let list = document.querySelector("#rest-of-list"); list.innerHTML = ""; for (i = 3; i < data.items.length; i++) { //console.log(data.items[i].name); list.innerHTML += `<li>${data.items[i].name}</li>` } } } async function getTop(type, time_range, limit, callback) { let topItems; //var access_token = localStorage.getItem("access_token"); let endpoint = `https://api.spotify.com/v1/me/top/${type}`; let query = `?time_range=${time_range}&limit=${limit}`; topItems = await callAPI("GET", endpoint, query); console.log(endpoint); callback(topItems, type); console.log("Top 10 " + type + ": "); console.log(topItems); } function getImages(data) { let images = { artists: new Array(), albums: new Array() } for (let group of data) { for (let item of group.items) { images.albums.push(item.album.images[0]); images.artists.push(item.album) } } //returns an object containing an array of artist images and album images } function getDecades(data) { let dates = getReleaseDates(data); let decades = new Array(); for (let date of dates) { //console.log(group); let year = date.slice(0, 4); let decade = Math.floor(year/10) * 10; decades.push(decade); //console.log(item.album.release_date); } console.log("Decades: "); console.log(decades); let decadeHead = new Array(); let frequency = new Array(); decades.sort(function (a, b) { if (a > b) return 1 else if (a < b) return -1 else return 0; }); for(let group of decades){ let key=group; let identicalDecades = decades.filter(function(group){ return key === group; }); //console.log(identicalDecades); let index = decades.indexOf(group); let howmany = identicalDecades.length; decades.splice(index+1,howmany-1); decadeHead.push(group+"'s"); frequency.push(identicalDecades.length); } console.log(decadeHead); console.log(frequency); //sort decadeHead decadeHead.sort(function (a, b) { let start = decadeHead.indexOf(a); let end = decadeHead.indexOf(b); if (frequency[start] > frequency[end]) return 1 else if (frequency[start] < frequency[end]) return -1 else return 0 }); //sort frequency frequency.sort(function (a, b) { if (a > b) return 1 else if (a < b) return -1 else return 0 }) let decadeChart=document.getElementById('decadeChart').getContext('2d'); let decChart= new Chart(decadeChart,{ type:'pie', data:{ labels:decadeHead, datasets:[{ label:'Decades', data:frequency, backgroundColor:[ "#FF0000", "#800000", "#FFFF00", "#808000", "#00FF00", "#008000", "#00FFFF", "#008080", "#0000FF", "#000080", "#FF00FF", "#800080", "#000000", "#808080", "#C0C0C0" ] }] }, options:{ responsive:true, maintainAspectRatio:false, plugins:{ title:{ display:true, text:'Albums Added per Decade', font:{ family:"'Open-Sans', sans-serif", size:20 }, color:'white' }, legend:{ display:true, labels:{ font:{ family:"'Open-Sans', sans-serif", size:15 }, color:'white', boxWidth: 15 } } } } }); return decades; } async function getMonthsDiscovery(year, callback) { let items = await getEntireLibrary('albums', getArtistDiscovery); console.log(callback); console.log(items); return items; } function getAlbumDiscovery(data) { console.log("Albums: "); let albums = new Array(); for (let group of data) { for (let item of group.items) { //let date = new Date(item.added_at); //console.log(date.getMonth()); let album = { name: item.album.name }; let date = new Date(item.added_at); album.date_added = date; albums.push(album); } } albums.sort(function (a, b) { if (a.date_added > b.date_added) return 1; else if (a.date_added < b.date_added) return -1; else return 0; }); let albumsCopy = [...albums]; console.log(albumsCopy); var years = new Array(); let freq= new Array(); let start = 0; for (album of albums) { //let date = artist.date_added; //let x = date.getFullYear(); //console.log(artist.date_added.getFullYear()); let year = { year: album.date_added.getFullYear(), months: new Array() } let albumYear = albums.filter(function (album) { return album.date_added.getFullYear() === year.year; }); for (i = 0; i < 12; i++) { //year.months[i].artists = new Array(); let albumMonth = albumYear.filter(function (album) { return album.date_added.getMonth() === i; }); year.months.push(albumMonth.length); freq.push(albumMonth.length); } //console.log(artists.indexOf(artist)); //console.log(artistsYear.length); console.log(year); albums.splice(albums.indexOf(album), albumYear.length-1); years.push(year); //artistsCopy.splice(artistsCopy.indexOf(artist), years.length); } //console.log(years); return years; } function getArtistDiscovery(data) { //data should be all albums var artists = new Array(); for (let group of data){ for (let item of group.items) { let artist = { name: item.album.artists[0].name, album_name: item.album.name, }; let date = new Date(item.added_at); //artist.month = date.getMonth(); artist.date_added = date; //january has a value of zero artists.push(artist); //console.log(date); } } //next, repeatedly make a new array containing only albums by a single artist //then find the instance with earliest date and push it into an array //sort alphabetically artists.sort(function (a, b) { if (a.name > b.name) return 1 else if (a.name < b.name) return -1 else return 0; }); for (let artist of artists) { let name = artist.name; let identicalArtists = artists.filter(function (artist) { return name === artist.name; }); //now sort identicalArtists by date identicalArtists.sort(function (a,b) { if (a.date_added > b.date_added) return 1 else if (a.date_added < b.date_added) return -1 else return 0; }); let index = artists.indexOf(artist); let howmany = identicalArtists.length; artists.splice(index+1, howmany-1); artists.splice(index, 1, identicalArtists[0]); //console.log(identicalArtists); } //at this point, artists is now an array of the first album the user saved from a particular artist //each object contains the album, artist and date added //now create an array of year objects, each year object has an array of month objects, //each month object has a frequency of artists in that month, and an array of artist objects discovered artists.sort(function (a, b) { if (a.date_added > b.date_added) return 1; else if (a.date_added < b.date_added) return -1; else return 0; }); let artistsCopy = [...artists]; console.log(artistsCopy); var years = new Array(); let freq= new Array(); let start = 0; for (artist of artists) { //let date = artist.date_added; //let x = date.getFullYear(); //console.log(artist.date_added.getFullYear()); let year = { year: artist.date_added.getFullYear(), months: new Array() } let artistsYear = artists.filter(function (artist) { return artist.date_added.getFullYear() === year.year; }); for (i = 0; i < 12; i++) { //year.months[i].artists = new Array(); let artistsMonth = artistsYear.filter(function (artist) { return artist.date_added.getMonth() === i; }); year.months.push(artistsMonth.length); freq.push(artistsMonth.length); } //console.log(artists.indexOf(artist)); //console.log(artistsYear.length); console.log(year); artists.splice(artists.indexOf(artist), artistsYear.length-1); years.push(year); //artistsCopy.splice(artistsCopy.indexOf(artist), years.length); } console.log("Artists: "); //console.log(artists); //console.log(years); console.log(freq); //return freq; return years; } function getDatesAdded (data) { let dates = new Array(); for (let group of data){ for (let item of group.items) { let date = item.added_at; dates.push(date); //console.log(date); } } //dates is an array of date objects //each date is the date an album was added console.log(dates); return dates; } function getReleaseDates (data) { //dateType is either "release" or "added" let dates = new Array(); for (let group of data) { //console.log(group); for (let item of group.items) { let date = item.album.release_date; dates.push(date); //console.log(item.album.release_date); } } console.log("Release Dates: "); console.log(dates); return dates; } async function getGenres(id) { let endpoint = "https://api.spotify.com/v1/artists/" + id; let artist = await callAPI("GET", endpoint, ""); let genre = artist.genres; return genre; } async function getAllGenres (data) { //data is an array of all albums let artists = getAllArtists(data); let allGenres = new Array(); let endpoint = "https://api.spotify.com/v1/artists?ids="; //array of ids for (let i = 0; i < artists.length; i += 50) { let query = new Array(); let x = 0; while (x < 50 && x+i < artists.length) { query.push(artists[x+i].id); x++; } query.join(); let temp = await callAPI("GET", endpoint, query); console.log(temp.artists); for (let artist of temp.artists) { for (genre of artist.genres) { allGenres.push(genre); } } } //console.log(allGenres); allGenres.sort(); //get an array of all unique genres let genres = allGenres.filter(function (genre) { return genre; }); let genreHead = new Array(); let Freq = new Array(); for (let genre of genres) { let key = genre; let identicalGenres = genres.filter(function (genre) { return key === genre; }); let index = genres.indexOf(genre); let howmany = identicalGenres.length; genres.splice(index+1, howmany-1); //genreHead.push(genre); //Freq.push(identicalGenres.length); //genres.push(identicalGenres[0]); //console.log(identicalGenres); } console.log(allGenres); console.log(genres); //array of generic genres const genreList = [ "pop", "jazz", "country", "rock", "folk", "rap", "hip hop", "reggae", "dancehall", "brazilian", "indie", "ambient", "r&b", "dance", "soul", "world", "blues", "funk", "edm", ]; //code to get array of simple genres in library let simpleGenres = new Array(); let other = new Array(); for (let genre of genreList) { let temp = genres.filter(function (a) { //return a.includes(genre) if (a.includes(genre)) { //genres.splice(genres.indexOf(a), 1); //console.log(a); return true; } return false; }) //to prevent empty genres if (temp.length > 0) { Freq.push(temp.length); genreHead.push(genre); simpleGenres.push(temp); } } //other category //genreHead.push("Other"); //Freq.push(genres.length); console.log(simpleGenres); console.log(genres); console.log(genreHead); console.log(Freq); //sort genreHead genreHead.sort(function (a, b) { let start = genreHead.indexOf(a); let end = genreHead.indexOf(b); if (Freq[start] > Freq[end]) return -1 else if (Freq[start] < Freq[end]) return 1 else return 0 }); //sort frequency Freq.sort(function (a, b) { if (a > b) return -1 else if (a < b) return 1 else return 0 }) let genreChart=document.getElementById('genreChart').getContext('2d'); let genChart= new Chart(genreChart,{ type:'pie', data:{ labels:genreHead, datasets:[{ label:'Genre', data:Freq, backgroundColor:[ '#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4', '#46f0f0', '#f032e6', '#bcf60c', '#fabebe', '#008080', '#e6beff', '#9a6324', '#fffac8', '#800000', '#aaffc3', '#808000', '#ffd8b1', '#000075', '#808080', '#000000' ] }] }, options:{ responsive:true, maintainAspectRatio:false, plugins:{ title:{ display:true, text:'Genres', font:{ family:"'Open Sans', sans-serif", size:20 }, color:'white' }, legend:{ display:true, labels:{ font:{ family:"'Open Sans', sans-serif", size:15 }, boxWidth:15, color:'white' }, position:"bottom" } } } }); } function getAllArtists (data) { let artists = new Array(); for (let group of data) { for (let item of group.items) { //console.log(item.album.artists[0]); artists.push(item.album.artists[0]); } } //sort alphabetically artists.sort(function (a, b) { if (a.name > b.name) return 1 else if (a.name < b.name) return -1 else return 0; }); //handle duplicates for (let artist of artists) { let name = artist.name; let identicalArtists = artists.filter(function (artist) { return name === artist.name; }); let index = artists.indexOf(artist); let howmany = identicalArtists.length; artists.splice(index+1, howmany-1); artists.splice(index, 1, identicalArtists[0]); //console.log(identicalArtists); } return artists; } //implement functionality to get all artists async function getEntireLibrary (type, callback) { //type can be either albums or tracks let total = await getNumItems(type); console.log(total); //it is impossible to get all albums in a single request (max is 50 per) //so, increment by 50 until total is reached let offset = 0; let endpoint = 'https://api.spotify.com/v1/me/' + type; let items = []; while (offset < total) { let query = `?limit=50&offset=${offset}`; let temp = await callAPI("GET", endpoint, query); items = items.concat(temp); //console.log(temp); offset += 50; } //use next value /* let query = `?limit=50&offset=${offset}`; let items = await callAPI ("GET", endpoint, query); console.log(items); while (items.next != null) { let url = new URL(items.next); query = "?" + new URLSearchParams(url.search); temp = await callAPI ("GET", endpoint, query); console.log(temp); items = items.concat(temp); //console.log(items); } */ console.log(items); let processedItems = callback(items); return processedItems; //items is an array of all tracks/albums (grouped by 50 or less) //each index in items array contains 50 or less items } async function getNumItems(type) { let endpoint = 'https://api.spotify.com/v1/me/' + type; let query = `?limit=1`; let item = await callAPI("GET", endpoint, query); console.log(item); return item.total; } access_token = localStorage.getItem("access_token"); function refreshAccessToken () { refresh_token = localStorage.getItem("refresh_token"); let body = "grant_type=refresh_token"; body += "&refresh_token=" + refresh_token; body += "&client_id=" + client_id; callAuthApi(body); } async function callAPI(method, endpoint, query, body) { let response = await fetch (endpoint+query, { headers: { 'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/json' }, body: JSON.stringify(body), method: method }) .catch (function (error) { console.log("Fetch Error: " + error); }) let data = await response.json(); console.log(`At CallAPI: ${endpoint}: ` + response.status); if (response.status === 401) { refreshAccessToken(); } return data; } function handleRedirect() { let code = getCode(); console.log(code); fetchAccessToken(code); window.history.pushState("", "", redirect_uri); } const client_id = localStorage.getItem("client_id"); const redirect_uri = localStorage.getItem("redirect_uri"); const verifier = localStorage.getItem("verifier"); //const scopes = "user-read-private user-library-read user-top-read playlist-modify-private playlist-modify-public"; function fetchAccessToken(code) { let body = "client_id=" + client_id; body += "&grant_type=authorization_code"; body += "&code=" + code; body += "&redirect_uri=" + encodeURI(redirect_uri); body += "&code_verifier=" + verifier; callAuthApi(body); } const token = "https://accounts.spotify.com/api/token"; function callAuthApi(body) { let xhr = new XMLHttpRequest(); xhr.open("POST", token, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //xhr.setRequestHeader("Authorization", "Basic " + btoa(client_id + ":" + client_secret)); xhr.send(body); xhr.onload = handleAuthResponse; } function handleAuthResponse() { if (this.status === 200) { var data = JSON.parse(this.responseText); console.log(data); var data = JSON.parse(this.responseText); if (data.access_token != undefined) { access_token = data.access_token; localStorage.setItem("access_token", access_token); } if (data.refresh_token != undefined) { refresh_token = data.refresh_token; localStorage.setItem("refresh_token", refresh_token); } //onPageLoad(); getUsername(); } else if (this.status === 401) { console.log('At handleAuthResponse: ' + this.status); refreshAccessToken(); } else if (this.status === 400) { //window.alert(this.responseText); window.location.href = "/index.html"; } else { console.log('At handleAuthResponse: ' + this.responseText); //alert(this.responseText); } } async function getUsername() { let endpoint = "https://api.spotify.com/v1/me"; let profile = await callAPI("GET", endpoint, ""); console.log(profile); window.localStorage.setItem("username", profile.display_name); window.localStorage.setItem("userid", profile.id); //let logout = document.querySelector("#logout"); //logout.innerHTML += ` (${profile.display_name})`; //<img src="${profile.images[0].url}" style="height:25% width:25%">`; //return profile.display_name; } function getCode () { let code = null; const qString = window.location.search; //console.log(qString); if (qString.length > 0) { const urlParams = new URLSearchParams (qString); code = urlParams.get('code'); } //console.log("code"); return code; } // HAMBURGER CODE console.log(window.navigator.cookieEnabled); console.log(window.navigator.online); console.log(navigator.appVersion); console.log(navigator.userAgent) console.log(navigator.platform); console.log(window.location.href); console.log(window.location.protocol); console.log(window.location.hostname); function redirect(url){ window.location.assign(url); } /* window.onload = function(event){ console.log("Page has loaded"); } */ const sidebar = document.querySelector('.sidebar'); const navLinks = document.querySelector('.nav-links'); const Links = document.querySelector('.nav-links li'); sidebar.addEventListener('click', ()=> { navLinks.classList.toggle('open'); });
TypeScript
UTF-8
599
2.84375
3
[]
no_license
import * as React from "react"; export function memo<Params extends any[], Retn extends any>(factory: (...args: Params) => Retn) { return (...args: Params): Retn => React.useMemo(() => factory(...args), args); } export function callback<Params extends any[], Retn extends (...args: any[]) => any>(factory: (...args: Params) => Retn) { return (...args: Params) => React.useCallback(factory(...args), args); } export function effect<Params extends any[]>(factory: (...args: Params) => ((() => void) | void)) { return (...args: Params) => React.useEffect(() => factory(...args), args); }
Markdown
UTF-8
2,454
2.765625
3
[ "MIT" ]
permissive
[![NPM](https://nodei.co/npm/marked-man.png?downloads=true)](https://nodei.co/npm/marked-man/) marked-man(1) -- markdown to roff ================================= SYNOPSIS -------- ``` marked-man README.md > doc/marked-man.1 ``` See [marked README](https://github.com/chjj/marked) for documentation about how to use marked. Note that `marked-man --format=html` is the same as `marked`. DESCRIPTION ----------- `marked-man` wraps `marked` to extend it with groff output support in order to create Unix manual pages for use with `man`. OPTIONS ------- `marked-man` invokes `marked --gfm --sanitize`, and you can pass additional options through. The `--breaks` option, which retains intra-paragraph line breaks, can be helpful to match default ronn behavior. `marked-man` adds some options to `marked`'s existing options: * `--format <format>` Sets the output format. Outputs html if different from `roff`. Defaults to `roff`. * `--name <name>` The name shown in the manpage header, if it isn't given in the ronn header like in this README. Defaults to empty string. * `--section <section>` The section number shown in the manpage header, if it isn't given in the ronn header like in this README. Defaults to empty string. * `--version <version>` The version shown in the manpage footer. Defaults to empty string. Breaking change in marked-man 0.7.0: this flag is converted to manVersion option, to avoid conflict with marked. * `--manual <manual>` The manual-group name shown in the manpage header. Defaults to empty string. * `--date <date>` The date shown in the manpage header. Defaults to now, must be acceptable to `new Date(string or timestamp)`. INSTALLATION ------------ From the [npm registry](https://npmjs.com): * locally (`--save`, `--save-dev`, or `--save-optional` add `marked-man` to your `package.json` file as a runtime, development-time, or optional runtime dependency, respectively) npm install marked-man [--save|--save-dev|--save-optional] * globally (puts `marked-man` in your system's path): [sudo] npm install marked-man -g EXAMPLE ------- To view this README as a man page, run something like the following: marked-man --version v0.1.0 --manual 'Man Utilities' README.md | man /dev/stdin SEE ALSO -------- [Ronn](https://github.com/rtomayko/ronn) REPORTING BUGS -------------- See [marked-man repository](https://github.com/kapouer/marked-man).
C++
UTF-8
1,510
2.875
3
[]
no_license
#ifndef STRATEGISTSSTUFF_H #define STRATEGISTSSTUFF_H #include "Strategists/samplestrategist.h" #include "Strategists/Strategy_Ball.h" #include "Strategists/Strategy_Guard.h" #include "Strategists/robot_zap.h" #include "Strategists/3v3/goalkeeper3v3.h" #include "Strategists/3v3/striker3v3.h" #include "Strategists/strategy_pointdc.h" typedef enum{ SAMPLE,KICK_BALL,GUARD_BALL,ZAP,POINT,GOALKEEPER,STRIKER, }StrategistType; static StrategistType assignStrategistType( int _index ) { StrategistType _temp; switch(_index) { case 0: _temp = SAMPLE; break; case 1: _temp = KICK_BALL;break; case 2: _temp = GUARD_BALL;break; case 3: _temp = ZAP;break; case 4: _temp = POINT;break; case 5: _temp = GOALKEEPER;break; case 6: _temp = STRIKER;break; default: break; } return _temp; } class StrategistFactory{ public: StrategistFactory() {} Robot_Strategist* newStrategist( StrategistType _type ) { switch(_type) { case SAMPLE: return new SampleStrategist; break; case KICK_BALL: return new Strategy_Ball; break; case GUARD_BALL:return new Strategy_Guard; break; case ZAP: return new ZapStrategist; break; case POINT: return new strategy_pointdc;break; case GOALKEEPER: return new goalkeeper3v3;break; case STRIKER :return new striker3v3;break; default: return NULL; } } }; #endif // STRATEGISTSSTUFF_H
Markdown
UTF-8
4,470
3.25
3
[ "CC0-1.0" ]
permissive
# How to convert your (/) root partition to btrfs This how to describes the procedure to convert your linux root partition from ext4 to btrfs. Use Case: Over a period of time, we make multiple changes to the OS, customize multiple applications and lose track of all the changes. Reinstalling the OS is really out of question. If you rely on tools like Timeshift to restore your OS, converting the root filesystem to btrfs is impossible without beginning from fresh. The below steps allows you to continue using your OS with btrfs without the pain of re-installing all the software and customizing them all over again. Requirements: 1.Ability to work in command line and edit files with console text editors like nano, vi etc. 2.Timeshift backup of your system on an external drive or on a partition different from /. 3.Linux Mint LiveCD or USB boot image. 4.Backup of all your data folder, home folder etc on an external drive. Tested with Linux Mint20.0, which was upgraded earlier from 19.3 and the original installation was 19.2. References: https://www.addictivetips.com/ubuntu-linux-tips/ubuntu-btrfs/ - To install with btrfs as root Time needed: The entire process may take a few hours, as you need to finish the OS installation once and do a Timeshift restoration once. Warning: Do not format other partitions like /boot/efi, /home/ and /data during installation. If your home and data are on your root partition, they need to be restored later. The entire root partition will be formatted and wiped clean. **If you do not understand the implication or do not have backup/restoration knowledge, do not proceed.** Remember to test your timeshift backup of the OS atleast once by restoring it to a different partition and do a test drive on the restored OS along with your data to avoid regrets later. Do remember to test your data/home backup and restoration procedure before you proceed further. Even though those partitions are untouched, it is better to test and understand the process of restoration once, incase something goes wrong. The entire steps below depend on the above Timeshift backup and you are going to **wipe your entire OS installation** before you complete the conversion of root partition to btrfs. If your backup/restoration does not work, fix it first or learn to do it first before you proceed further. Note: change x and y in the device names i.e /dev/sdxy to suit your needs like /dev/sda1. Step1 Install the OS from liveCD with /dev/sdxy as the root partition. Remember to set the (/) root partition filesystem to btrfs during installation. Complete the installation. Verify the working of OS once before you proceed to Step 2. Step2 Now once again boot from the liveCD, but this time, use timeshift to restore from the backup that you created and tested earlier. Once the restore is completed, reboot the system. For Academic interest only. Skip and you can go to step3 directly When you try to use the system using regular boot up sequence, your system will not work. The reason being, the entries for (/) root partition in the restored /etc/fstab have your ext4 filesystem based values, but your (/) root partition is on btrfs now. The (/) root partition will be mounted in read only mode and you’ve to work in the recovery mode only for now. Reboot the system again. Step3 Choose the recovery menu from the grub and drop in to the root shell. Perform the below steps as root user. 3.1 Create a temporary folder tmproot on /run, which is the only writable folder for you now. #mkdir /run/tmproot 3.2 Mount your root partition on the folder as #mount /dev/sdxy /run/tmproot 3.3 Find your new device UUID by using the command lsblk -f #lsblk -f 3.4 Edit your fstab file in /run/tmproot/etc/fstab and comment out the old entry for (/) root. Create a new entry by replacing the three options i.e filesystem UUID, type and options for (/) root. The new /etc/fstab entry for (/) root will look like below after you’ve made the changes..(a truncated output of fstab given below for clarity) #cat /run/tmproot/etc/fstab # <file system> <mount point> <type> <options> <dump> <pass> #UUID=1f16d419-121a-4b71-83e8-f6e38d969dbd / ext4 errors=remount-ro 0 1 UUID=7c23009f-f0b0-4561-b576-031771763a32 / btrfs defaults,subvol=@ 0 0 3.5 Reboot your OS. Now you have successfully converted your ext4 (/) root partition to btrfs filesystem.
Java
UTF-8
362
2.046875
2
[]
no_license
package org.midas.as; import org.midas.MidasException; public class AgentServerException extends MidasException { public AgentServerException(){} public AgentServerException(Throwable arg0){super(arg0);} public AgentServerException(String message){super(message);} public AgentServerException(String arg0, Throwable arg1){super(arg0, arg1);} }
C#
UTF-8
5,648
2.984375
3
[ "MIT" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.IO; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; namespace app { public class Program { private static readonly HttpClient _httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(10) }; private static readonly string _gatewayUrl = $"http://{Environment.GetEnvironmentVariable("gateway_dnsname")}"; private static readonly string _bikesUrl = $"http://{Environment.GetEnvironmentVariable("bikes_dnsname")}"; private static readonly string _usersUrl = $"http://{Environment.GetEnvironmentVariable("users_dnsname")}"; public static void Main(string[] args) { using (_httpClient) { _WaitForServiceReadiness().Wait(); _PopulateDatabase().Wait(); Console.WriteLine("Shutting down."); } } private async static Task _WaitForServiceReadiness() { Console.WriteLine($"gatewayUrl: {_gatewayUrl}"); Console.WriteLine($"bikesUrl: {_bikesUrl}"); Console.WriteLine($"usersUrl: {_usersUrl}"); while (true) { Console.WriteLine("Checking to see if services are up..."); // Check bikes bool bikesReady = false; try { bikesReady = (await _httpClient.GetAsync($"{_bikesUrl}/hello")).IsSuccessStatusCode; } catch { } if (!bikesReady) { Console.WriteLine("Bikes not ready :("); Console.WriteLine($"{_bikesUrl}/hello"); } // Check users bool usersReady = false; try { usersReady = (await _httpClient.GetAsync($"{_usersUrl}/hello")).IsSuccessStatusCode; } catch { } if (!usersReady) { Console.WriteLine("Users not ready :("); Console.WriteLine($"{_usersUrl}/hello"); } // Check gateway bool gatewayReady = false; try { gatewayReady = (await _httpClient.GetAsync($"{_gatewayUrl}/hello")).IsSuccessStatusCode; } catch { } if (!gatewayReady) { Console.WriteLine("Gateway not ready :("); Console.WriteLine($"{_gatewayUrl}/hello"); } if (bikesReady && usersReady && gatewayReady) { // Success! Console.WriteLine("Services are up!"); break; } var sleep = TimeSpan.FromSeconds(10); Console.WriteLine($"Sleeping for {sleep.TotalSeconds} seconds and trying again..."); await Task.Delay(sleep); } } private async static Task _PopulateDatabase() { Console.WriteLine("Populating databases..."); // Read JSON directly from a file JObject data = JObject.Parse(File.ReadAllText(@"data.json")); JToken customers = (JToken)data.SelectToken("customers"); JToken vendors = (JToken)data.SelectToken("vendors"); JToken bikes = (JToken)data.SelectToken("bikes"); // Add users and bikes Console.WriteLine("\n********************************************\nADDING USERS"); foreach (var customer in customers) { Console.WriteLine("Adding user: " + customer.ToString()); var response = await _httpClient.PostAsync(_gatewayUrl + "/api/user/", new StringContent(customer.ToString(), Encoding.UTF8, "application/json")); if (!response.IsSuccessStatusCode) { Console.WriteLine("Failed to add : " + customer.ToString()); Console.WriteLine(response.StatusCode + " " + await response.Content.ReadAsStringAsync()); } } Console.WriteLine("\n********************************************\nADDING VENDORS"); foreach (var vendor in vendors) { Console.WriteLine("Adding vendor: " + vendor.ToString()); var response = await _httpClient.PostAsync(_gatewayUrl + "/api/user/vendor", new StringContent(vendor.ToString(), Encoding.UTF8, "application/json")); if (!response.IsSuccessStatusCode) { Console.WriteLine("Failed to add : " + vendor.ToString()); Console.WriteLine(response.StatusCode + " " + await response.Content.ReadAsStringAsync()); } } Console.WriteLine("\n********************************************\nADDING BIKES"); foreach (var bike in bikes) { Console.WriteLine("Adding bike: " + bike.ToString()); var response = await _httpClient.PostAsync(_gatewayUrl + "/api/bike", new StringContent(bike.ToString(), Encoding.UTF8, "application/json")); if (!response.IsSuccessStatusCode) { Console.WriteLine("Failed to add : " + bike.ToString()); Console.WriteLine(response.StatusCode + " " + await response.Content.ReadAsStringAsync()); } } Console.WriteLine("Finished populating databases."); } } }
Java
UTF-8
1,179
2.328125
2
[ "MIT" ]
permissive
package com.example.myapplication4.book.brief; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.room.Embedded; import androidx.room.Entity; import androidx.room.Fts4; import androidx.room.Ignore; import androidx.room.PrimaryKey; @Fts4 @Entity public class BookBriefDataBean { @PrimaryKey(autoGenerate = true) public int rowid; public String id; public String title; public String image; @Embedded public BookScore rating; public String bookSmallType; @Override public boolean equals(@Nullable Object obj) { if (obj != null) { return this.toString().equals(obj.toString()); } else { return false; } } @NonNull @Override public String toString() { return title + " " + rating.toString() + " " + image; } public static class BookScore{ @Ignore public int max; @Ignore public int numRaters; public String average; @Ignore public int min; @NonNull @Override public String toString() { return average; } } }
Markdown
UTF-8
3,156
2.765625
3
[ "MIT" ]
permissive
# Purescript-Simple-JSON [<img alt="build status" src="https://img.shields.io/github/workflow/status/justinwoo/purescript-simple-json/ci?logo=github&style=for-the-badge" height="20">](https://github.com/justinwoo/purescript-simple-json/actions?query=workflow%3Aci) [<img alt="documentation status" src="https://img.shields.io/readthedocs/purescript-simple-json/latest?logo=read-the-docs&style=for-the-badge" height="20">](https://readthedocs.org/projects/purescript-simple-json/badge/?version=latest) A simple Foreign/JSON library based on the Purescript's RowToList feature. ## Quickstart Get going quickly with the Quickstart section of the guide: <https://purescript-simple-json.readthedocs.io/en/latest/quickstart.html> You may also be interested in this presentation about how Simple-JSON works well with PureScript-Record: <https://speakerdeck.com/justinwoo/easy-json-deserialization-with-simple-json-and-record>. Note that the slides are based on an older version of the library and on PureScript 0.11.6, and it is not necessary to understand these slides to get started. ## Dependencies This purerl port of simple-json assumes that the `jsx` application is available, you may e.g. want to add this to your `rebar.conf`. ## Usage In brief: ```purs type MyJSON = { apple :: String , banana :: Int , cherry :: Maybe Boolean } decodeToMyJSON :: String -> Either (NonEmptyList ForeignError) MyJSON decodeToMyJSON = SimpleJSON.readJSON ``` See the [API Docs](https://pursuit.purescript.org/packages/purescript-simple-json/) or the [tests](test/Main.purs) for usage. There is also a guide for how to use this library on [Read the Docs](https://purescript-simple-json.readthedocs.io/en/latest/). ## Warning: `Maybe` This library will decode `undefined` and `null` as `Nothing` and write `Nothing` as `undefined`. Please use the `Nullable` type if you'd like to read and write `null` instead. Please take caution when using `Maybe` as this default may not be what you want. ## FAQ ### How do I use this with Affjax? Please see this page in the guide: <https://purescript-simple-json.readthedocs.io/en/latest/with-affjax.html> ### How do I change how some fields of my JSON objects are read? Please see this page in the guide: <https://purescript-simple-json.readthedocs.io/en/latest/inferred-record-types.html> ### How do I work with `data` Types? Please see this page in the guide: <https://purescript-simple-json.readthedocs.io/en/latest/generics-rep.html> ### Why won't you accept my Pull Request? Please read this appeal from another open source author: <https://github.com/benbjohnson/litestream#open-source-not-open-contribution> ### How should I actually use this library? James Brock has informed me that people still do not understand that this library should be used not as a library. If you do not like any of the behavior in this library or would like to opt out of some behaviors, you should copy this library into your own codebase. Please see that this libraries does not actually contain many lines of code and you should be able to learn how to construct this library from scratch with a few days of reading.
C#
UTF-8
2,000
2.59375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TestCommon; namespace A8 { public class Q3PacketProcessing : Processor { public Q3PacketProcessing(string testDataName) : base(testDataName) { } public override string Process(string inStr) => TestTools.Process(inStr, (Func<long, long[], long[], long[]>)Solve); public long[] Solve(long bufferSize, long[] arrivalTimes, long[] processingTimes) { List<(long, long)> requests = new List<(long, long)>(); for (long i = 0; i < arrivalTimes.Length; i++) requests.Add((arrivalTimes[i], processingTimes[i])); buffer buffer = new buffer(bufferSize); List<long> responses = new List<long>(); foreach ((long, long) request in requests) responses.Add(buffer.response(request)); return responses.ToArray(); } } public class buffer { public long Size; public List<long> finishingTimes; public long response((long, long) request) { long startTime; while ((finishingTimes.Count > 0) && (finishingTimes[0] <= request.Item1)) finishingTimes.RemoveAt(0); if (finishingTimes.Count < Size) { if (finishingTimes.Count == 0) { finishingTimes.Add(request.Item1 + request.Item2); return request.Item1; } else { startTime = finishingTimes.Last(); finishingTimes.Add(startTime + request.Item2); return startTime; } } else return -1; } public buffer(long size) { Size = size; finishingTimes = new List<long>(); } } }
Java
UTF-8
6,034
2.21875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.timesheet.changeprofile; import com.timesheet.bean.Employee; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.text.ParseException; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.sql.DataSource; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; /** * * @author prodigy */ public class ProfileServiceImpl extends HttpServlet implements ProfileService { HttpServletRequest request; protected SimpleJdbcTemplate jdbcTemplate = null; public void setDataSource(final DataSource dataSource) { this.jdbcTemplate = new SimpleJdbcTemplate(dataSource); } public SimpleJdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(SimpleJdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public Employee getByPk(String emp_id) { try { Employee employee = new Employee(); String selectbypk = "SELECT * FROM employee_master WHERE EMP_ID = '" + emp_id + "'"; // System.out.println("RegistrationServiceImpl class into getByPk() method is called :: The query is=" + selectbypk); employee = (Employee) jdbcTemplate.queryForObject(selectbypk, new EmployeeRowMapper()); return employee; } catch (DataAccessException dae) { dae.printStackTrace(); return null; } } public String Insert_fmt_date(String dat) { try { SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy"); Date dt = sdf.parse(dat); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd"); String fmt_date = sdf1.format(dt); return fmt_date; } catch (ParseException ex) { ex.printStackTrace(); return null; } } public static String getDD_MM_YYYY(Date enteredDate) { String ansdate = null; try { //System.out.println("Into The getDD_MM_YYYY() method..." + enteredDate); SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy"); ansdate = sdf1.format(enteredDate); return ansdate; } catch (Exception e) { e.printStackTrace(); return null; } } public List<Employee> checkUserId(String userid) { try { String query = "select emp_id from employee_master where emp_id='" + userid + "'"; List<Employee> e = jdbcTemplate.getJdbcOperations().query(query, new UserRowMapper()); return e; } catch (DataAccessException dae) { dae.printStackTrace(); return null; } } private static class UserRowMapper implements ParameterizedRowMapper<Employee> { public Employee mapRow(ResultSet rs, int rownum) throws SQLException { Employee employee = new Employee(); employee.setUserid(rs.getString("emp_id")); employee.setEmp_id(rs.getString("emp_id")); return employee; } } public boolean changeprofile(String emp_id, String userid, String emp_fname, String fname, String emp_lname, String gender, String emp_email, String emp_address, String emp_phone, String emp_mobile, String emp_birthdate) { try { String update = "update employee_master set emp_id='" + userid + "', emp_fname='" + fname + "',emp_lname='" + emp_lname + "',gender='" + gender + "',emp_email='" + emp_email + "',emp_address=?,emp_phone='" + emp_phone + "',emp_mobile='" + emp_mobile + "',emp_birthdate='" + emp_birthdate + "' where emp_id='" + emp_id + "'"; jdbcTemplate.update(update, new Object[]{emp_address}); //jdbcTemplate.getJdbcOperations().update(update); return true; } catch (DataAccessException dae) { dae.printStackTrace(); return false; } } private static class EmployeeRowMapper implements ParameterizedRowMapper<Employee> { public Employee mapRow(ResultSet rs, int rownum) throws SQLException { Employee employee = new Employee(); employee.setEmp_id(rs.getString("emp_id")); employee.setEmp_password(rs.getString("emp_password")); employee.setEmp_fname(rs.getString("emp_fname")); employee.setEmp_lname(rs.getString("emp_lname")); employee.setGender(rs.getString("gender")); employee.setEmp_email(rs.getString("emp_email")); employee.setEmp_address(rs.getString("emp_address")); employee.setEmp_phone(rs.getString("emp_phone")); employee.setEmp_mobile(rs.getString("emp_mobile")); employee.setEmp_birthdate(getDD_MM_YYYY(rs.getDate("emp_birthdate"))); return employee; } } public List<Employee> checkFName(String empfname){ try{ String query = "SELECT emp_fname FROM employee_master WHERE emp_fname='"+empfname+"'"; List<Employee> e = jdbcTemplate.getJdbcOperations().query(query, new FNameRowMapper()); return e; }catch(DataAccessException dae ){ // System.out.println("dae error in checkFName: "+dae); return null; } } private static class FNameRowMapper implements RowMapper{ public Object mapRow(ResultSet rs, int rownum) throws SQLException { Employee employee = new Employee(); employee.setEmp_fname(rs.getString("emp_fname")); employee.setFname(rs.getString("emp_fname")); return employee; } } }
JavaScript
UTF-8
7,505
3.4375
3
[]
no_license
function cambia(){ var capa = document.getElementById("principalCurses"); borraHijos(capa); var nodoTexto = document.createTextNode("HAS PULSADO EL BOTON PULSAR Y HAS HECHO MAGIA!!!!"); var nodoElement = document.createElement("h2"); nodoElement.appendChild(nodoTexto); capa.appendChild(nodoElement); console.log("FIN PRUEBA"); } function borraHijos(elemento){ //alert(elemento.innerHTML); var hijos = elemento.childNodes; //alert(hijos.length); for(var i=0; i < hijos.length ; i++){ elemento.removeChild(hijos[i]); } } function cambiaDos(){ var capa = document.getElementById("principalTemas"); borraHijos(capa); var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText) pintaTabla(this.responseText); }else{ console.log(this.readyState + " " + this.status); } }; //xhttp.open("GET", "http://localhost/DavidAngulo/crudJson/readEntity.php", true); xhttp.open("GET", "readTema.php", true); xhttp.send(); } function pintaTabla(respuesta){ var respuestaJSON = JSON.parse(respuesta); console.log(respuesta) var capa = document.getElementById("principalTemas"); if(respuestaJSON["estado"] == "ok"){ console.log("VAMOS BIEN"); var arrTemas = respuestaJSON["temas"]; for(var i = 0; i < arrTemas.length; i++){ //console.log(arrTemas[i]) var fila = document.createElement("div"); fila.setAttribute("ID","tema_"+ arrTemas[i].ID ); fila.setAttribute("class","tema"); // fila.setAttribute("onclick","prueba(this)"); var id = document.createElement("h2"); var texto = document.createTextNode(arrTemas[i].ID); id.appendChild(texto); id.setAttribute("ID","ID"+ arrTemas[i].ID ); var nombre = document.createElement("h2"); var textonum = document.createTextNode(arrTemas[i].Nombre); nombre.appendChild(textonum); nombre.setAttribute("Nombre","Nombre"+ arrTemas[i].ID ); var instrumental = document.createElement("h2"); var textoequipo = document.createTextNode(arrTemas[i].Instrumental); instrumental.appendChild(textoequipo); instrumental.setAttribute("Instrumental","Instrumental"+ arrTemas[i].ID ); var instrumentalId = document.createElement("h2"); var textoequipo = document.createTextNode(arrTemas[i].ID_Instrumental); instrumentalId.appendChild(textoequipo); instrumentalId.setAttribute("ID_Instrumental","ID_Instrumental"+ arrTemas[i].ID_Instrumental); fila.appendChild(id); fila.appendChild(nombre); fila.appendChild(instrumental); fila.appendChild(instrumentalId) capa.appendChild(fila); } }else{ console.log("VAMOS MAL"); } } function limpia() { document.getElementById('principalTemas').innerHTML=''; } function insertarTema(){ var tema = {}; tema.ID = document.getElementById("ID").value; tema.Nombre = document.getElementById("Nombre").value; tema.Instrumental = document.getElementById("Instrumental").value; tema.ID_Instrumental = document.getElementById("ID_Instrumental").value; console.log(tema); var peticion = {}; peticion.peticion = "add"; peticion.tema = tema; console.log("esta es la peticion") console.log(peticion); peticionJSON = JSON.stringify(peticion); console.log(peticionJSON); var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance xmlhttp.open("POST", "writeTema.php"); xmlhttp.setRequestHeader("Content-Type", "application/json"); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText) var respuestaJSON = JSON.parse(this.responseText); alert(this.readyState + "" + this.status) if(respuestaJSON["estado"] == "ok"){ alert("INSERTADO CORRECTAMENTE. ID: " + respuestaJSON["lastId"] ); limpia() cambiaDos() }else{ alert(respuestaJSON["mensaje"]); } }else{ console.log(this.readyState + " " + this.status); if (this.readyState == 4 && this.status == 404) { alert("URL INCORRECTA"); } } }; xmlhttp.send(peticionJSON); } function updateTema(){ var tema = {}; tema.ID = document.getElementById("ID").value; tema.Nombre = document.getElementById("Nombre").value; tema.Instrumental = document.getElementById("Instrumental").value; tema.ID_Instrumental = document.getElementById("ID_Instrumental").value; console.log(tema); var peticion = {}; peticion.peticion = "add"; peticion.tema = tema; console.log("esta es la peticion") console.log(peticion); peticionJSON = JSON.stringify(peticion); console.log(peticionJSON); var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance //xmlhttp.open("POST", "http://localhost/davidangulo/crudJson/writeEntity.php"); xmlhttp.open("POST", "updateTema.php"); xmlhttp.setRequestHeader("Content-Type", "application/json"); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText) var respuestaJSON = JSON.parse(this.responseText); alert(this.readyState + "" + this.status) if(respuestaJSON["estado"] == "ok"){ alert("INSERTADO CORRECTAMENTE. ID: " + respuestaJSON["lastId"] ); limpia() cambiaDos() }else{ alert(respuestaJSON["mensaje"]); } }else{ console.log(this.readyState + " " + this.status); if (this.readyState == 4 && this.status == 404) { alert("URL INCORRECTA"); } } }; xmlhttp.send(peticionJSON); } function deleteTema() { alert("has pulsado eliminar") var tema = {}; tema.ID = document.getElementById("ID_Delete").value; var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance //xmlhttp.open("POST", "http://localhost/davidangulo/crudJson/writeEntity.php"); xmlhttp.open("POST", "deleteTema.php"); // alert("Putada premo") xmlhttp.setRequestHeader("Content-Type", "application/json"); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText) var respuestaJSON = JSON.parse(this.responseText); alert(this.readyState + "" + this.status) if (respuestaJSON["estado"] == "ok") { alert("INSERTADO CORRECTAMENTE. ID: " + respuestaJSON["lastId"]); limpia() cambiaDos() } else { alert(respuestaJSON["mensaje"]); } } else { console.log(this.readyState + " " + this.status); if (this.readyState == 4 && this.status == 404) { alert("URL INCORRECTA"); } } } }; console.log("JS CARGADO");
PHP
UTF-8
178
2.71875
3
[]
no_license
<?php include_once 'Product.php'; class ProductAA extends Product { /** * @return void */ public function writeln() { print "ProductAA \n"; } }
Markdown
UTF-8
6,250
2.65625
3
[]
no_license
# 输入文字 ## 输入文字的两种方式 对于输入文字,发现之前的可以工作的代码: ```python self.driver(text=locator["text"]).set_text(text,timeout=WaitFind) ``` 会出现:无法完整输入内容 具体现象:中文输入法中,输入了字母,但是丢失了数字 的效果: ![android_input_text_abnormal](../assets/img/android_input_text_abnormal.png) 且输入法此时已经也被换了(换成了 FastInputIME 或 系统自带(华为Swype) 输入法了) 注: ```python self.driver(text=locator["text"]).set_text(text,timeout=WaitFind) ``` 内部是调用的uiautomator2的session的set_text: 文件:`/Users/limao/.pyenv/versions/3.8.0/lib/python3.8/site-packages/uiautomator2/session.py` ```python def set_text(self, text, timeout=None): self.must_wait(timeout=timeout) if not text: return self.jsonrpc.clearTextField(self.selector) else: return self.jsonrpc.setText(self.selector, text) ``` (除了额外支持timeout参数外) 而换用另外的: ### `xpath`的`set_text` ```python searchElementSelector = self.driver.xpath(searchKeyText) searchElementSelector.set_text(text) ``` 内部调用的: 文件:`/Users/limao/.pyenv/versions/3.8.0/lib/python3.8/site-packages/uiautomator2/xpath.py` ```python def set_text(self, text: str = ""): el = self.get() self._parent.send_text() # switch ime el.click() # focus input-area self._parent.send_text(text) ``` ### `send_keys` ```python self.driver.send_keys(text) self.driver.set_fastinput_ime(False) # 关掉FastInputIME输入法,切换回系统默认输入法(此处华为手机默认输入法是华为Swype输入法) ``` 其中,是否加上 打开FastInputIME ```python self.driver.set_fastinput_ime(True) # # 切换成FastInputIME输入法 self.driver.send_keys(text) self.driver.set_fastinput_ime(False) # 关掉FastInputIME输入法,切换回系统默认输入法(此处华为手机默认输入法是华为Swype输入法) ``` 经测试,感觉没区别。 结果都是: * 可以成功输入文字 * 此处的:gh_cfcfcee032cc * 但是输入法会被切换掉 * 我之前设置的是:百度的输入法 * ![android_input_method_baidu](../assets/img/android_input_method_baidu.png) * 对应着,输入文字之前,应该是 * ![android_popup_keyboard_pinyin](../assets/img/android_popup_keyboard_pinyin.png) * 会被换成:当前系统默认自带输入法 * 当前系统是:华为的畅享6S手机 DIG-AL00 * 自带输入法是:华为Swype输入法 * ![android_input_method_huawei_swype](../assets/img/android_input_method_huawei_swype.png) * 效果是: * ![android_input_text_keyboard](../assets/img/android_input_text_keyboard.png) 结论: * 基本上实现了自己的:要输入文字的目的 * 但是:却把之前设置的(百度)输入法切换成系统的(华为)输入法了。 * 问题不大,但是很不爽 * 但是没办法改变和保留原有输入法 ## set_text导致输入法切换,需要恢复 最终整理出函数: ```python def selectorSetText(u2Dev, curXpathSelector, inputText): selectorSetTextResp = curXpathSelector.set_text(inputText) logging.info("selectorSetTextResp=%s", selectorSetTextResp) # selectorSetTextResp=None # 在set_text后,输入法会变成FastInputIME输入法 # 用下面代码可以实现:关掉FastInputIME输入法,切换回系统默认输入法 u2Dev.set_fastinput_ime(False) ``` ## 用set_text输入字符串:小米安全键盘 影响输入,可以考虑禁止掉 代码本身: ```python passwordStr = "请输入密码" passwordXpath = """//android.widget.EditText[@text="%s" and @index="2" and @clickable="true"]""" % passwordStr passwordSelector = u2Dev.xpath(passwordXpath) if passwordSelector.exists: logging.info("Found %s", passwordStr) # pwdClickResp = passwordSelector.click() # logging.debug("pwdClickResp=%s", pwdClickResp) # doScreenshot(u2Dev) selectorSetText(u2Dev, passwordSelector, Vivo_Password) def selectorSetText(u2Dev, curXpathSelector, inputText): selectorSetTextResp = curXpathSelector.set_text(inputText) logging.info("selectorSetTextResp=%s", selectorSetTextResp) # selectorSetTextResp=None doScreenshot(u2Dev) # 在set_text后,输入法会变成FastInputIME输入法 # 用下面代码可以实现:关掉FastInputIME输入法,切换回系统默认输入法 u2Dev.set_fastinput_ime(False) ``` 是可以输入密码=字符串的 但是 * 之前开启了:小米安全键盘 * 导致:输入不顺利 * 小米安全键盘 会弹出显示 消失掉,多次之后 * (等待1,2秒后)触发异常: * `/Users/limao/dev/xxx/crawler/appAutoCrawler/AppCrawler/venv/lib/python3.8/site-packages/uiautomator2/__init__.py:1646: Warning: set FastInputIME failed. use "d(focused=True).set_text instead"` * `warnings.warn(` * 最终才能输入密码 * 解决办法:关闭 小米安全键盘 * 步骤: * 系统设置-》更多设置-》语言与输入法-》安全键盘-》取消勾选:开启安全键盘 * ![xiaomi_disable_security_keyboard](../assets/img/xiaomi_disable_security_keyboard.png) ## 以为输入框set_text输入文字无效 某次调试代码,以为是:uiautomator的UiObject或XPathSelector的set_text不生效问题 其实不是这个原因,而是点击了页面元素本身后,应该进去新的界面(输入法弹框界面,用于输入内容) 所以应该把代码: ```python inputUiObj = d(resourceId="com.android.browser:id/b4h", className="android.widget.TextView") inputUiObj.set_text(BaiduHomeUrl) ``` 换成: ```python inputUiObj = d(resourceId="com.android.browser:id/b4h", className="android.widget.TextView") inputUiObj.click() ``` 或: ```python inputXpathSelector = d.xpath("//android.widget.TextView[@resource-id='com.android.browser:id/b4h']”) inputXpathSelector.click() ``` 去触发新界面,即可。 -》后续再去定位搜索框,输入内容(百度首页地址),进入百度首页
Ruby
UTF-8
2,067
2.828125
3
[ "MIT" ]
permissive
# typed: ignore # This file contains a fake implementation of the subset of `sorbet-runtime` # used by Braid that performs no runtime checks. See the "Type checking" # section of development.md for background. require 'singleton' # Create our fake module at `Braid::T` so that if someone loads Braid into the # same Ruby interpreter as other code that needs the real sorbet-runtime, we # don't break the other code. (We don't officially support loading Braid as a # library, but we may as well go ahead and put this infrastructure in place.) # Code in the `Braid` module still uses normal references to `T`, so the Sorbet # static analyzer (which doesn't read this file) doesn't see anything out of the # ordinary, but those references resolve to `Braid::T` at runtime according to # Ruby's constant lookup rules. module Braid module T module Sig def sig; end end def self.let(value, type) value end # NOTICE: Like everything else in the fake Sorbet runtime (e.g., `sig`), # these do not actually perform runtime checks. Currently, if you want a # runtime check, you have to implement it yourself. We considered defining # wrapper functions with different names to make this clearer, but then we'd # lose the extra static checks that Sorbet performs on direct calls to # `T.cast` and `T.must`. def self.cast(value, type) value end def self.must(value) value end def self.unsafe(value) value end def self.bind(value, type); end class FakeType include Singleton end FAKE_TYPE = FakeType.instance def self.type_alias FAKE_TYPE end def self.nilable(type) FAKE_TYPE end def self.untyped FAKE_TYPE end def self.noreturn FAKE_TYPE end def self.any(*types) FAKE_TYPE end Boolean = FAKE_TYPE module Array def self.[](type) FAKE_TYPE end end module Hash def self.[](key_type, value_type) FAKE_TYPE end end end end
Python
UTF-8
733
2.5625
3
[]
no_license
import idx2numpy import cPickle, gzip, numpy import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #sess = tf.InteractiveSession() mnist = input_data.read_data_sets('MNIST_data', one_hot=True) print mnist exit() node1 = tf.constant(3.0, tf.float32) node2 = tf.constant(4.0) # also tf.float32 implicitly print(node1, node2) sess = tf.Session() print(sess.run([node1, node2])) node3 = tf.add(node1, node2) print("node3: ", node3) print("sess.run(node3): ",sess.run(node3)) exit() # Load the dataset f = gzip.open('mnist.pkl.gz', 'rb') train_set, valid_set, test_set = cPickle.load(f) f.close() train_set, train_tags = train_set val_set, val_tags = valid_set test_set, test_tags = test_set
Python
UTF-8
674
3.015625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Wed Feb 6 19:07:08 2019 @author: ecorrea """ #P074: indexação booleana import numpy as np vet_filmes = np.array(['Procura Insaciável (1971)', 'Um Estranho no Ninho (1975)', 'Hair (1979)', 'Na Época do Ragtime (1981)', 'Amadeus (1984)', 'Valmont - Uma História de Seduções (1989)', 'O Povo Contra Larry Flint (1996)', 'O Mundo de Andy (1999)', 'Sombras de Goya (2006)', 'Dobre placená procházka (2009)']) vet_notas = np.array([7.4, 8.7, 7.6, 7.3, 8.3, 7.0, 7.3, 7.4, 6.9, 6.7]) vet_selecionados = vet_filmes[vet_notas > 7.5] print(vet_selecionados)
Shell
UTF-8
1,634
3.421875
3
[]
no_license
#!/usr/bin/env bash set -euo pipefail IFS=$'\n\t' source /usr/local/lib/my-notmuch-utils/commons.sh LOCKFILE=/tmp/sync-mails-dotfile echo "Start Sync Mails!" echo "Check lockfile $LOCKFILE" $dotlockfile_command -r 10 -l -p "$LOCKFILE" [[ $? -ne 0 ]] && { sendWarning "Sync Mail" "Previous sync lasts too long!"; } echo "Lockfile check OK!" echo "Start mbsync!" set +e $mbsync_command -c ~/.config/isync/mbsyncrc -a [[ $? -ne 0 ]] && { sendWarning "Sync Mail" "mbsync throws error!"; } set -e echo "Finish mbsync!" echo "Start offlineimap!" set +e $offlineimap_command -c ~/.config/offlineimap/offlineimap.conf set -e [[ $? -ne 0 ]] && { sendWarning "Sync Mail" "offlineimap throws error!"; } echo "Finish offlineimap!" echo "Start notmuch new!" lock_notmuch 1 if [[ $? -eq 0 ]]; then $notmuch_command new [[ $? -ne 0 ]] && { sendWarning "Sync Mail" "Notmuch throws error!"; } echo "Finish notmuch new!" else sendWarning "Sync Mail" "Notmuch seems to be locked by others" fi unlock_notmuch echo "Finish notmuch new!" echo "Unlock lockfile!" $dotlockfile_command -u "$LOCKFILE" echo "Unlock lockfile finished!" echo "Check New Mails" while read -r -d $'\0' oneFolder do NEW="new" if test "x${oneFolder##*/}" = "x$NEW" ; then mailbox="${oneFolder%/new}" account="${mailbox%/*}" mailbox="${mailbox##*/}" account="${account##*/}" [[ -n "$(ls $oneFolder)" ]] && \ $notify_send_command "New Mail(s) in $account/$mailbox " -t 5000 fi done < <(find "$MAIL_ROOT" -type d -path "$MAIL_ROOT/.notmuch" -prune -o -type d -print0) echo "Finish Sync Mails!"
Java
UTF-8
1,225
2.546875
3
[ "MIT" ]
permissive
package com.refinedmods.refinedstorage.api.network; import com.refinedmods.refinedstorage.api.util.Action; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import java.util.Collection; import java.util.function.Consumer; /** * Represents a graph of all the nodes connected to a network. */ public interface INetworkNodeGraph { /** * Rebuilds the network graph. * * @param action whether to perform or simulate * @param level the origin level * @param origin the origin, usually the network position */ void invalidate(Action action, Level level, BlockPos origin); /** * Runs an action on the network. * If the network is rebuilding it's graph, the action will be executed after the graph was built. * * @param handler the action to run */ void runActionWhenPossible(Consumer<INetwork> handler); /** * @return a collection of all connected entries */ Collection<INetworkNodeGraphEntry> all(); /** * @param listener the listener */ void addListener(INetworkNodeGraphListener listener); /** * Disconnects and notifies all connected nodes. */ void disconnectAll(); }
PHP
UTF-8
1,003
3.03125
3
[]
no_license
<?php require_once "./classes/response_doc.php"; class htmlDoc extends ResponseDoc { public function show() { $this->beginDoc(); $this->beginHeader(); $this->headerContent(); $this->endHeader(); $this->beginBody(); $this->bodyContent(); $this->endBody(); $this->endDoc(); } private function beginDoc() { echo "<!DOCTYPE html>\n<html lang=en>\n"; } private function beginHeader() { echo "<head>\n"; } protected function headerContent() { echo "<title>Mijn eerste class</title>\n"; } private function endHeader() { echo "</head>\n"; } private function beginBody() { echo "<body>\n"; } protected function bodyContent() { echo "<h1>Mijn eerste class</h1>\n"; } private function endBody() { echo "</body>\n"; } private function endDoc() { echo "</html>\n"; } }
Python
UTF-8
2,048
3.265625
3
[ "MIT" ]
permissive
import pygame from pytmx import * from os import path from .settings import * from .characters import * class TiledMap(): def __init__(self, filename, game): self.data = [] with open(filename, 'rt') as f: for line in f: self.data.append(line) self.scale = 32 * game.scale self.tm = load_pygame(filename, pixelalpha=True) self.width = self.tm.width * self.scale self.height = self.tm.height * self.scale print(f'tm height, tilehight, scale: {[self.tm.height, self.tm.tileheight, game.scale]}') self.tmxdata = self.tm def render(self, surface): ti = self.tm.get_tile_image_by_gid for layer in self.tm.visible_layers: if isinstance(layer, pytmx.TiledTileLayer): for x, y, gid in layer: tile = ti(gid) if tile: tile = pygame.transform.scale(tile, (self.scale, self.scale)) surface.blit(tile, (x*self.scale, y*self.scale)) def make_map(self): temp_surface = pygame.Surface((self.width, self.height)) self.render(temp_surface) return temp_surface class Camera: def __init__(self, width, height): self.camera = pygame.Rect(0, 0, width, height) self.width = width self.height = height def apply(self, entity): # move sprites to offest of camera(player usually) return entity.rect.move(self.camera.topleft) def apply_box(self, rect): return rect.move(self.camera.topleft) def update(self, target): # update the position of the camera x = -target.rect.centerx + int(WIDTH/2) y = -target.rect.centery + int(HEIGHT/2) # limit scrolling to borders of map x = min(0, x) y = min(0, y) x = max(-(self.width - WIDTH), x) y = max(-(self.height - HEIGHT), y) # set cameras new location self.camera = pygame.Rect(x, y, self.width, self.height)
JavaScript
UTF-8
2,767
3.53125
4
[]
no_license
/* * KVUE class类 * * KVue * * */ class KVue { constructor(options) { this.$options = options; this.$data = options.data; // $data 实例属性 this.observe(options.data); // 模拟一下watcher创建 // new Watcher(); // this.$data.name; // new Watcher(); // this.$data.foo.bar; new Compile(options.el, this); if (options.created) { options.created.call(this); } } observe(value) { // value不存在或不是预期类型 if (!value || typeof value != "object") { return; } Object.keys(value).forEach(key => { this.defineReactive(value, key, value[key]); // 代理data中的属性到vue属性 this.proxyData(key); }) } defineReactive(obj, key, val) { // 递归遍历 this.observe(val); const dep = new Dep(); // dep 相对独立(有几个key就有几个dep) // 数据劫持 Object.defineProperty(obj, key, { get() { // console.log("触发get函数"); Dep.target && dep.addDep(Dep.target); return val; }, set(newValue) { // console.log(`${key}属性值为:${newValue}`); val = newValue; // 触发更新 dep.notify(); } }) } proxyData(key) { Object.defineProperty(this, key, { get() { return this.$data[key]; }, set(newVal) { this.$data[key] = newVal; } }) } } // 管理watcher - 收集Watcher对象 class Dep { constructor() { // 存放若干依赖(watcher) this.deps = []; } addDep(watcher) { this.deps.push(watcher); } notify() { // dep -> watcher this.deps.forEach(dep => dep.updata()) } } // 数据更新 class Watcher { constructor(vm, key, cb) { this.vm = vm; this.key = key; this.cb = cb; // 将当前watcher实例指定到Dep Dep.target = this; this.vm[this.key]; // 触发getter,添加依赖 Dep.target = null; } // 执行数据更新 updata() { console.log("数据更新了") this.cb.call(this.vm, this.vm[this.key]); } } // var app = new KVue({ // data: { // name: "KVUE", // foo: { // bar: "This is bar..." // } // } // }) // // 当查询或设置属性值会触发钩子函数(get,set) // app.$data.name; // app.$data.name = "This is KVue"; // app.$data.foo.bar = "This is bar property";
C
UTF-8
2,494
3.0625
3
[]
no_license
/* * kv_trace.h * Author : Heekwon Park * E-mail : heekwon.p@samsung.com * * LOG & Elapsed time measurement funcionts */ #ifndef KV_TRACE_H #define KV_TRACE_H #include <time.h> #include <stdio.h> //////////////////// TIME ////////////////// typedef unsigned long long cycles_t; #define DECLARE_ARGS(val, low, high) unsigned low, high #define EAX_EDX_VAL(val, low, high) ((low) | ((unsigned long)(high) << 32)) #define EAX_EDX_ARGS(val, low, high) "a" (low), "d" (high) #define EAX_EDX_RET(val, low, high) "=a" (low), "=d" (high) static unsigned long long __native_read_tsc(void) { DECLARE_ARGS(val, low, high); asm volatile("rdtsc" : EAX_EDX_RET(val, low, high)); return EAX_EDX_VAL(val, low, high); } static inline cycles_t get_cycles(void) { unsigned long long ret = 0; ret=__native_read_tsc(); return ret; } extern cycles_t msec_value; extern cycles_t usec_value; extern cycles_t nsec_value; extern cycles_t cycle_value; #ifndef DEBUG #define DEBUG 0 #endif #define LOG(fmt, args...) {time_t r; struct tm * t; time(&r); t=localtime(&r); printf("{%2d:%2d:%2d}[%s:%s():%d] :: " fmt, t->tm_hour, t->tm_min, t->tm_sec, __FILE__, __func__, __LINE__, ##args);} #define ERRLOG(fmt, args...) {time_t r; struct tm * t; time(&r); t=localtime(&r); fprintf(stderr, "{%2d:%2d:%2d}[%s:%s():%d] :: " fmt, t->tm_hour, t->tm_min, t->tm_sec, __FILE__, __func__, __LINE__, ##args); exit(0);} #if DEBUG #define DEBUGLOG(fmt, args...) {time_t r; struct tm * t; time(&r); t=localtime(&r); printf("{%2d:%2d:%2d}[%s:%s():%d] :: " fmt, t->tm_hour, t->tm_min, t->tm_sec, __FILE__, __func__, __LINE__, ##args);} #else #define DEBUGLOG(fmt, args...) #endif #define time_sec_measure(START,END) ((END-START)/cycle_value) #define time_msec_measure(START,END) ((END-START)/msec_value) #define time_usec_measure(START,END) ((END-START)/usec_value) #define time_nsec_measure(START,END) ((END-START)/nsec_value) #define time_cycle_measure(START,END) (END-START) static inline void time_init(cycles_t *msec, cycles_t *usec, cycles_t *nsec, cycles_t *cycle){ cycles_t s_time, e_time; /* Time Value initialization*/ s_time = get_cycles(); sleep(1); e_time = get_cycles(); *cycle = time_cycle_measure(s_time, e_time); *msec = *cycle / 1000; //for cycle to msec *usec = *cycle / 1000 / 1000; //for cycle to usec *nsec = *cycle / 1000 / 1000 / 1000; //for cycle to usec *msec = ((*msec + 99999) / 100000) * 100000; *usec = ((*usec + 99) / 100) * 100; } #endif
Markdown
UTF-8
3,625
3.03125
3
[]
no_license
# Cours de C# ## Création de la structure `mkdir Isen.Cs && cd Isen.Cs` `dotnet new sln` Création du projet de type console : `mkdir Isen.Cs.ConsoleApp && cd Isen.Cs.ConsoleApp` `dotnet new console` Création du projet de type librairie: `mkdir Isen.Cs.Library && cd Isen.Cs.Library` `dotnet new classlib` Création du projet de type test unitaires (depuis la racine) : `mkdir Isen.Cs.Tests && cd Isen.Cs.Tests` `dotnet new xunit` ### Référencement des projets Ajouter au projet console une référence vers le projet Library Depuis le dossier du projet console: `dotnet add reference ..\Isen.Cs.Library\Isen.Cs.Library.csproj` Ajouter au projet Test une référence vers le projet Library Depuis le dossier du projet Test: `dotnet add reference ..\Isen.Cs.Library\Isen.Cs.Library.csproj` Pour retirer la référence, remplacer `add` par `remove` ### Indiquer au sln la présence des 3 projets Depuis la racine de la solution: `dotnet sln add Isen.Cs.Library\Isen.Cs.Library.csproj` `dotnet sln add Isen.Cs.ConsoleApp\Isen.Cs.ConsoleApp.csproj` `dotnet sln add Isen.Cs.Tests\Isen.Cs.Tests.csproj` ### Parenthèse spécifique à Visual Studio (et pas visual studio code) On peut créer des "dossiers de solution", qui sont des dossiers virtuels (non reflétés dans le filesytem) Rangements proposé : - `src` pour les projets library et console - `tests`pour les projets de tests - `sln`pour tous les fichiers hors porjets à la racine de la solution ### Ménage Effacer les fichiers .cs générés automatiquement, à l'exception de celui du projet Console. ### Build pour vérifier Il y a 3 étapes, qui s'appellent entre elles, lors d'un build: * `dotnet restore` : restaurer les packages "NuGet" distants (mécanisme équivalent à `npm`). * `dotnet build` : compiler les projets * `dotnet run` : éxécuter le projet, s'il est exécutable: * Exécuter dans la console, pour un projet console * Lancer un serveur web, pour un projet web. ### Initial commit Créer un projet sur Github ou Gitlab. Depuis la racine du projet : `git init` Trouver un .gitignore pour un projet .net Core : lien... Créer un fichier .gitignore: `touch .gitignore` Remplir ce fichier avec le contenu exemple. `git add .` `git commit -m "initial commit, project structure"` `git remote add origin https://github.com/mistermania/ISEN-CS.git ` `git push origin master` Ajouter un tag de version 0.1 `git tag v0.1` `git push origin v0.1` ## Ajout d'exercices 'Hors Projet' Dans le projet Library: * Creer un dossier Lessons * Creer une classe 01_Types (fichier 01_Types.cs) Inclure toute la structure d'une classe : * `using` (imports du java) * `namespace` (package du java) * `class` Coder la classe (voir code). L'appeler dans le main(). ### B_Enumerations Ce chapitre passe en revue les `enum`. Dans le projet Library, créer cette classe. ### C_Arrays Aperçu des passages par valeur ou référence. Ce chapitre traite des tableaux "primitifs" du style `object[]` ou `object[][]`. Créer la classe C_Arrays avec une méthode d'éxécution et l'appeler dans le main. ### D_MyCollection But: créer une classe de tableau mutable de string. Ce type de classe peut être ArrayList, List, MutableArray, Collection, ..., selon les languages et API. Créer `D_MyCollection` dans Lesson, avec méthode d'éxécution et appel dans main. Créer à la racine de Library une classe `MyCollection`. Créer à la racine de Library une interface `IMyCollection`. `MyCollection` doit implémenter l'interface `IMyCollection`.
Markdown
UTF-8
2,699
2.59375
3
[]
no_license
<!-- markdownlint-disable MD002 MD041 --> Há mais de 230 conectores de caixa de saída para automatização da Microsoft. Muitos desses conectores usam o Microsoft Graph para se comunicar com pontos de extremidade específicos de produtos da Microsoft. Além disso, há outros cenários em que pode ser necessário chamar o Microsoft Graph diretamente da automatização de energia usando blocos de construção básicos do serviço, já que não há conectores que se comunicam diretamente com o Microsoft Graph para cobrir toda a API. Além de abordar cenários para chamar o Microsoft Graph diretamente, vários pontos de extremidade da API do Microsoft Graph só dão suporte a [permissões delegadas](https://docs.microsoft.com/graph/permissions-reference). O conector HTTP no Microsoft Power Automate permite integrações muito flexíveis, incluindo chamar o Microsoft Graph. No entanto, o conector HTTP não tem a capacidade de armazenar em cache as credenciais de um usuário para habilitar cenários de permissão delegada específicos. Nesses casos, um conector personalizado pode ser criado para fornecer um invólucro em torno da API do Microsoft Graph e habilitar o consumo da API com permissões delegadas. Este laboratório aborda os dois cenários acima. Primeiro, você criará um conector personalizado para habilitar as integrações com o Microsoft Graph, que exigem [permissões delegadas](https://docs.microsoft.com/graph/permissions-reference). Em segundo lugar, você usará o [ponto de extremidade de solicitação $batch](https://docs.microsoft.com/graph/json-batching), para fornecer acesso a todo o poder do Microsoft Graph enquanto usa as permissões delegadas que exigem que um aplicativo tenha um usuário "conectado". > [!NOTE] > Este é um tutorial sobre como criar um conector personalizado para uso nos aplicativos do Microsoft Power Automate e do Azure Logic. Este tutorial pressupõe que você tenha lido a [visão geral do conector personalizado](https://docs.microsoft.com/connectors/custom-connectors/) para entender o processo. ## <a name="prerequisites"></a>Pré-requisitos Para concluir este exercício nesta postagem, você precisará do seguinte: - Acesso de administrador a uma locação do Office 365. Se você não tiver um, visite o [programa para desenvolvedores do Office 365](https://developer.microsoft.com/office/dev-program) para se inscrever de um locatário de desenvolvedor gratuito. - Acesso à [Microsoft Power Automated](https://flow.microsoft.com/). ## <a name="feedback"></a>Comentários Forneça comentários sobre este tutorial no [repositório do GitHub](https://github.com/microsoftgraph/msgraph-training-powerautomate).
Python
UTF-8
152
2.734375
3
[]
no_license
# coding=utf-8 def front_times(str, n): if n < 0: return 'not a valid number' if len(str) > 2: str = str[:3] return str * n
Python
UTF-8
713
2.875
3
[]
no_license
class Solution: def minCostToMoveChips(self, position: List[int]) -> int: counters = {} for v in position: counters[v] = counters.get(v, 0) + 1 ans = sys.maxsize for p in counters: cost = 0 for q in counters: if q != p: if abs(q-p) % 2: cost += counters[q] if cost < ans: ans = cost return ans class Solution: def minCostToMoveChips(self, position: List[int]) -> int: cnts = [0, 0] for v in position: cnts[v%2] += 1 return min(cnts)
Java
UTF-8
1,231
2.453125
2
[]
no_license
package com.hackusp.klabinusp.model; public class Usuario { private String id; private String roleId; private double pesoIc; private double pesoEstagio; private double pesoPalestra; public Usuario(String id, String roleId, double pesoIc, double pesoEstagio, double pesoPalestra) { this.id = id; this.roleId = roleId; this.pesoIc = pesoIc; this.pesoEstagio = pesoEstagio; this.pesoPalestra = pesoPalestra; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getRoleId() { return roleId; } public void setRoleId(String roleId) { this.roleId = roleId; } public double getPesoIc() { return pesoIc; } public void setPesoIc(double pesoIc) { this.pesoIc = pesoIc; } public double getPesoEstagio() { return pesoEstagio; } public void setPesoEstagio(double pesoEstagio) { this.pesoEstagio = pesoEstagio; } public double getPesoPalestra() { return pesoPalestra; } public void setPesoPalestra(double pesoPalestra) { this.pesoPalestra = pesoPalestra; } }
Python
UTF-8
1,021
4.21875
4
[]
no_license
# Program Name: p27_Count_Letters_in_a_Random_List_of_Letters.py # Name: Charlize Serrano # Version: Python 3.7.0 # Date Started - Date Finished: 9/28/18 - 9/29/18 # Description: Write a program that generates a random list of letters. from random import randint empty_list = [] x = randint(50, 75) b_count = 0 print("Made a list of %i letters"%x) for list in range(0, x, 1): letter_num = randint(65, 70) letter = chr(letter_num) if letter == 'B': b_count += 1 empty_list.append(letter) print(empty_list) print("the letter 'B' appears %i times"%b_count) ''' >>> RESTART: C:\Users\Charlize\Documents\Python\p27_Count_Letters_in_a_Random_List_of_Letters.py Made a list of 55 letters ['B', 'D', 'A', 'B', 'F', 'A', 'F', 'D', 'A', 'E', 'B', 'F', 'C', 'C', 'A', 'C', 'D', 'C', 'A', 'D', 'A', 'A', 'F', 'C', 'E', 'B', 'F', 'E', 'A', 'D', 'D', 'D', 'A', 'D', 'A', 'C', 'F', 'F', 'E', 'F', 'E', 'B', 'A', 'A', 'C', 'C', 'E', 'B', 'F', 'A', 'C', 'B', 'C', 'F', 'D'] the letter 'B' appears 7 times >>> '''
Java
UTF-8
3,959
2
2
[]
no_license
package com.ahpu.ssm.service.admin; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ahpu.ssm.pojo.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ahpu.ssm.mapper.admin.OrderMapper; import com.ahpu.ssm.mapper.admin.ProductMapper; @Service public class OrderServiceImpl implements OrderService{ @Autowired OrderMapper mapper; @Override public void addOrder(Order o) { // TODO Auto-generated method stub mapper.addOrder(o); } @Override public void addOrderItem(OrderItem oi) { // TODO Auto-generated method stub mapper.addOrderItem(oi); } @Override public void updateOrder(Order o) { // TODO Auto-generated method stub mapper.updateOrder(o); } @Override public Order selectOrderByOid(String oid) { // TODO Auto-generated method stub return mapper.selectOrderByOid(oid); } @Override public PageBean listOrder(int curPage) { // TODO Auto-generated method stub PageBean<Order> page = new PageBean<Order>(); page.setCurPage(curPage); int totalCount = mapper.selectCount(); page.setTotalSize(totalCount); double total = totalCount; int totalPage = (int)Math.ceil(total/ PageBean.pageSize); page.setTotalPage(totalPage); Map<String,Object> map = new HashMap<String,Object>(); map.put("start", (curPage - 1) * PageBean.pageSize); map.put("size", PageBean.pageSize); List<Order> list = mapper.findByPage(map); page.setList(list); return page; } @Override public PageBean listOrderQita(int curPage , int state) { // TODO Auto-generated method stub PageBean<Order> page = new PageBean<Order>(); page.setCurPage(curPage); int totalCount = mapper.selectCountqita(state); page.setTotalSize(totalCount); double total = totalCount; int totalPage = (int)Math.ceil(total/ PageBean.pageSize); page.setTotalPage(totalPage); Map<String,Object> map = new HashMap<String,Object>(); map.put("start", (curPage - 1) * PageBean.pageSize); map.put("size", PageBean.pageSize); map.put("state", state); List<Order> list = mapper.findByPage2(map); page.setList(list); return page; } @Override public void deleteOrder(String o) { // TODO Auto-generated method stub mapper.deleteOrder(o); } @Override public PageBean userListOrder(int curPage,String usernameid) { // TODO Auto-generated method stub PageBean<Order> page = new PageBean<Order>(); page.setCurPage(curPage); int totalCount = mapper.selectCountByUsernameid(usernameid); page.setTotalSize(totalCount); double total = totalCount; int totalPage = (int)Math.ceil(total/ PageBean.pageSize); page.setTotalPage(totalPage); Map<String,Object> map = new HashMap<String,Object>(); map.put("start", (curPage - 1) * PageBean.pageSize); map.put("size", PageBean.pageSize); map.put("usernameid", usernameid); List<Order> list = mapper.findByPage3(map); page.setList(list); return page; } @Override public PageBean userListDetail(int curPage, String oid) { PageBean<OrderItem> page = new PageBean<OrderItem>(); page.setCurPage(curPage); int totalCount = mapper.selectCountByOid(oid); page.setTotalSize(totalCount); double total = totalCount; int totalPage = (int)Math.ceil(total/ PageBean.pageSize); page.setTotalPage(totalPage); Map<String,Object> map = new HashMap<String,Object>(); map.put("start", (curPage - 1) * PageBean.pageSize); map.put("size", PageBean.pageSize); map.put("oid", oid); List<OrderItem> list = mapper.findByPage4(map); page.setList(list); return page; } @Override public Cart findcid(String cid) { return mapper.findcid(cid); } @Override public int findcount(int state) { return mapper.countorder(state); } @Override public List<OrderItem> selectOrderItemByOid(String oid) { // TODO Auto-generated method stub return mapper.selectOrderItemByOid(oid); } }
Shell
UTF-8
205
3.03125
3
[]
no_license
#!/usr/bin/env bash set -euox pipefail IFS=$'\n\t' java-app.stop.main() { cd $(dirname $(readlink -f $0)) local pid=java-example/pid kill -9 $(cat $pid) rm $pid } java-app.stop.main "$@"
Java
UTF-8
1,575
2.265625
2
[]
no_license
package com.example.a76780.himalaya.adapters; import android.support.v4.view.PagerAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.example.a76780.himalaya.R; import com.squareup.picasso.Picasso; import com.ximalaya.ting.android.opensdk.model.track.Track; import java.util.ArrayList; import java.util.List; public class PlayerTrackPagerAdapter extends PagerAdapter { private List<Track> mDate=new ArrayList<>(); @Override public Object instantiateItem(ViewGroup container, int position) { View itemView=LayoutInflater.from(container.getContext()).inflate(R.layout.item_track_pager,container,false); container.addView(itemView); //设置数据 //找到控件 ImageView item=itemView.findViewById(R.id.track_pager_item); //设置图片 Track track=mDate.get(position); String coverUrlLarge=track.getCoverUrlLarge(); Picasso.with(container.getContext()).load(coverUrlLarge).into(item); return itemView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } @Override public int getCount() { return mDate.size(); } @Override public boolean isViewFromObject(View view, Object object) { return view==object; } public void setData(List<Track> list) { mDate.clear(); mDate.addAll(list); notifyDataSetChanged(); } }
C++
UTF-8
1,568
2.625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* PresidentialPardonForm.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fcoudert <fcoudert@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/05 10:55:30 by fcoudert #+# #+# */ /* Updated: 2020/12/05 11:45:37 by fcoudert ### ########.fr */ /* */ /* ************************************************************************** */ #include "PresidentialPardonForm.hpp" PresidentialPardonForm::PresidentialPardonForm() { } PresidentialPardonForm::PresidentialPardonForm(std::string target): Form("Presidential Pardon Form", 25, 5), _target(target) { } PresidentialPardonForm::PresidentialPardonForm(PresidentialPardonForm const & copy): Form(copy) { this->operator= (copy); } PresidentialPardonForm::~PresidentialPardonForm() { } PresidentialPardonForm & PresidentialPardonForm::operator=(PresidentialPardonForm const & ope) { Form::operator= (ope); return(*this); } void PresidentialPardonForm::execute_action()const { std::cout << _target << " has been pardoned by Zafod Beeblebrox" << std::endl; }
Python
UTF-8
2,318
3.03125
3
[ "MIT" ]
permissive
"""Alumno: Sergi Viel usuario: evokraken version 04.00 """ """ CONTROL DE CAMBIOS La direccion se controla mediante un giro aleatorio 'cabeceo'. El modulo controlado por un random de cero a 'magnitDePaso'. Obtenemos el punto medio de cada paso. Trazamos un vector perpendicular y a partir de el obtenemos dos puntos mas para cerra una celosia con los puntos del siguiente paso. Debemos dejar dos variables en memoria de ciclo """ import random as rd import Rhino.Geometry as rg import rhinoscriptsyntax as rs #configuramos random para un seed aportado por usuario. rd.seed(sSeed) #punto pUno aportado por usuario y acumulador de resultados pUno = (PtoO) resultado=[] VtoF = rg.Vector3d(1,1,0) axisZ = rg.Vector3d(0,0,1) for i in range(intN): #vector de recta #VtoF = rg.Vector3d(rd.randint(-1,1),rd.randint(-1,1),0) radian = rd.randrange(-cabeceo,cabeceo,1) modulo = rd.randrange(1, magnitDePaso+1, 1) VtoFF = modulo*rs.VectorUnitize((rs.VectorRotate(VtoF,radian,axisZ))) VtoNormal = 0.5*rs.VectorRotate(VtoFF,90,axisZ) #Obtenemos recta 'trazoEje' y los puntos a conectar trazoEje = rg.Line(pUno,VtoFF) pDos = (trazoEje).To pMed = rg.Line(pUno,VtoFF).PointAt(0.5) pTres = rg.Line(pMed,VtoNormal).To pCuatro = rg.Line(pMed,-VtoNormal).To #Polilinea cerrada de cada paso con los puntos obtenidos poli = rg.Polyline([pUno,pTres,pDos,pCuatro,pUno]) #obtenemos los resultados de cada paso resultado.append(trazoEje) resultado.append(poli) #resultado.append(pDos) #resultado.append(pMed) #resultado.append(pTres) #resultado.append(pCuatro) #excluimos en el bucle el primer y ultimo paso para esta linea #para evitar introducir en la lista resultado elementos vacíos #que puedan provocar errores. if i != 0 or i==intN: nexo1 = rg.Line(pTresPrima, pTres) nexo2 = rg.Line(pCuatroPrima, pCuatro) resultado.append(nexo1) resultado.append(nexo2) #preparamos para el siguiente bucle pTresPrima = pTres pCuatroPrima = pCuatro pUno = (pUno+VtoFF) #el inicio del trazo en el final del anterior VtoF = VtoFF #la direccion del anterior a partir del cual se genera el nuevo #suma de todos los trazos lo dejamos para la salida a = resultado
Java
UTF-8
2,785
2.78125
3
[]
no_license
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; public class OrderDetail { protected static int Number=0; private String OrderId; private String FoodItemId; private int NumberofItems; private ArrayList<Integer> Qty; private ArrayList<Integer> Half; private double total; private ArrayList<Double> Price; OrderDetail(){ this.NumberofItems = 0; this.FoodItemId = new String(); this.Qty = new ArrayList<Integer>(0); this.Half = new ArrayList<Integer>(0); this.Price = new ArrayList<Double>(0); GenerateOrderNumber(); } OrderDetail(int TableNumber){ this.NumberofItems = 0; this.FoodItemId = new String(); this.Qty = new ArrayList<Integer>(0); this.Half = new ArrayList<Integer>(0); this.Price = new ArrayList<Double>(0); GenerateOrderNumber(); } OrderDetail(int TableNumber,String OrderId){ this.NumberofItems = 0; this.FoodItemId = new String(); this.Qty = new ArrayList<Integer>(0); this.Half = new ArrayList<Integer>(0); this.Price = new ArrayList<Double>(0); this.OrderId = OrderId; } protected double getTotal() { return total; } protected void GenerateOrderNumber() { Number++; this.OrderId = "O"+Number; } protected void addFoodItem(String FoodCode, int Qty, int Half,double Price) { this.FoodItemId += FoodCode+" "; this.Qty.add(Qty); this.Half.add(Half); this.Price.add(Price); total+=Price*Qty; NumberofItems++; } protected String getOrderId() { return OrderId; } protected void setOrderId(String orderId) { OrderId = orderId; } protected String getFoodItemId() { return FoodItemId; } protected void setFoodItemId(String foodItemId) { FoodItemId = foodItemId; } protected void setQty(String abc) { String abcd[] = abc.split(" "); for(int i=0;i<abcd.length;i++) { Qty.add(Integer.parseInt(abcd[i])); } } protected int getNumberofItems() { return NumberofItems; } protected void setNumberofItems(int numberofItems) { NumberofItems = numberofItems; } protected String getQtyString() { String QtyString = new String(); for(int i=0;i<this.Qty.size();i++) QtyString += String.valueOf(Qty.get(i))+" "; return QtyString; } protected void setPrice(String abc) { String abcd[] = abc.split(" "); total=0; for(int i=0;i<abcd.length;i++) { { Price.add(Double.parseDouble(abcd[i])); total+=Price.get(i); } } } protected String getNameofFoodIdByIndex(int index) { String abcd[] = FoodItemId.split(" "); return abcd[index]; } protected String getPriceString() { String QtyString = new String(); for(int i=0;i<this.Qty.size();i++) QtyString += String.valueOf(Price.get(i))+" "; return QtyString; } }