text
stringlengths
64
89.7k
meta
dict
Q: JTable row sorter - IllegalArgumentException: Invalid SortKey Can someone help me with this? It was working until I changed something trying to optimaze it... damn! This is my table model: class MyTableModel extends DefaultTableModel { private String[] columnNames = {"Last Name","First Name","Next Visit"}; //column header labels Object[][] data = new Object[100][3]; public void reloadJTable(List<Customer> list) { for(int i=0; i< list.size(); i++){ data[i][0] = list.get(i).getLastName(); data[i][1] = list.get(i).getFirstName(); if (list.get(i).getNextVisit()==null) { data[i][2] = "NOT SET"; } else { String date = displayDateFormat.format(list.get(i).getNextVisit().getTime()); data[i][2] = date; } model.addRow(data); } } public void clearJTable() { model.setRowCount(0); } public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { return data[row][col]; } /* * JTable uses this method to determine the default renderer/ * editor for each cell. If we didn't implement this method, * then the last column would contain text ("true"/"false"), * rather than a check box. */ public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } /* * Don't need to implement this method unless your table's * editable. */ public boolean isCellEditable(int row, int col) { //Note that the data/cell address is constant, //no matter where the cell appears onscreen. if (col < 2) { return false; } else { return true; } } } and this is how I implement the JTable: // these declarations are all private shared across the model JTable customerTbl; MyTableModel model; List<Customer> customers = new ArrayList<Customer>(); SimpleDateFormat displayDateFormat = new SimpleDateFormat ("EEE dd-MM-yyyy 'at' hh:mm"); //JTable configuration model = new MyTableModel(); customerTbl = new JTable(model); model.reloadJTable(customers); customerTbl.setAutoCreateRowSorter(true); //enable row sorters DefaultRowSorter sorter = ((DefaultRowSorter)customerTbl.getRowSorter()); //default sort by Last Name ArrayList list = new ArrayList(); list.add( new RowSorter.SortKey(0, SortOrder.ASCENDING)); sorter.setSortKeys(list); //EXCEPTION HERE sorter.sort(); customerTbl.getColumnModel().getColumn(0).setPreferredWidth(100); //set Last Name column preferred width customerTbl.getColumnModel().getColumn(1).setPreferredWidth(80); //set First Name column preferred width customerTbl.getColumnModel().getColumn(2).setPreferredWidth(150); //set Last Visit column preferred width I'm getting the following exception triggered on: sorter.setSortKeys(list); Exception in thread "main" java.lang.IllegalArgumentException: Invalid SortKey at javax.swing.DefaultRowSorter.setSortKeys(Unknown Source) at com.vetapp.customer.CustomersGUI.<init>(CustomersGUI.java:128) at com.vetapp.main.VetApp.main(VetApp.java:31) I believe it has to do with the TableColumnModel which is not created correctly... A: The main problem is that the column count is returning 0 from the TableModel's super class DefaultTableModel. You need to override this method @Override public int getColumnCount() { return columnNames.length; } Another side but potentially fatal issue is the fact that getColumnClass is returning the class of elements within the TableModel. This will throw a NullPointerException if the table is empty. Use a class literal instead such as String.class. Maintaining a separate backing data array is unnecessary for DefaultTableModel. It has already has its own data vector. This approach is used when extending AbstractTableModel.
{ "pile_set_name": "StackExchange" }
Q: what are the good ways to migrate the Hdd SAS from bad server to the good server without lose data I have a problem with a HP ProLiant ML350 G6 with 2 SAS HDD 300GB : I shut it down for add a network card, but it won't start. I have changed (migrate) the HDD to an other good server, But both HDD were ok, with green lights. I can't find how to see or enter in the raid configuration ? what are the good ways to migrate the Hdd sas from bad server to the good serverand keeping os and tdata in the hdd Please help Thank you A: You are in a very dangerous situation. Simply moving disks to another server does not guarantee being able to boot back up or read out data from them, on the contrary, you risk losing access to your data. RAID data may be stored on disk, or in the controller. In the latter case, when moving disks to another controller (server), the system has no idea what the RAID-array is supposed to look like. When the other server has a different controller (and/or firmware version), the likeliness of this being the case is higher. To my knowledge, in the case of ProLiant SmartArray controllers, RAID-data is stored in both the controller and on disk. In the case that you are using the same controllers in both servers, you may be able to regain access by using the 'Scan Disks' functionality in the ACU (Array Configuration Utility) or SSA (Smart Storage Administrator). Make sure the SmartArray controller on your destination server is at the same firmware version or higher. You may also get a prompt during boot asking what you would like to do. Is there any chance you can get the original system running again? That would be your best bet. If your data is precious, get support from HP.
{ "pile_set_name": "StackExchange" }
Q: How do I aggregate hourly data to daily, weekly, monthly and yearly values in PostgreSQL? I have a table my_data in my PostgreSQL 9.5 database containing hourly data. The sample data is like: ID Date hour value 1 01/01/2014 1 9.947484 2 01/01/2014 2 9.161652 3 01/01/2014 3 8.509986 4 01/01/2014 4 7.666654 5 01/01/2014 5 7.110822 6 01/01/2014 6 6.765822 7 01/01/2014 7 6.554989 8 01/01/2014 8 6.574156 9 01/01/2014 9 6.09499 10 01/01/2014 10 8.471653 11 01/01/2014 11 11.36581 12 01/01/2014 12 11.25081 13 01/01/2014 13 9.391651 14 01/01/2014 14 6.976655 15 01/01/2014 15 6.574156 16 01/01/2014 16 6.420823 17 01/01/2014 17 6.229156 18 01/01/2014 18 5.577491 19 01/01/2014 19 4.964159 20 01/01/2014 20 6.593323 21 01/01/2014 21 7.321654 22 01/01/2014 22 9.295818 23 01/01/2014 23 8.241653 24 01/01/2014 24 7.014989 25 02/01/2014 1 6.842489 26 02/01/2014 2 7.513321 27 02/01/2014 3 7.244988 28 02/01/2014 4 5.80749 29 02/01/2014 5 5.481658 30 02/01/2014 6 6.669989 .. .. .. .. and so on. The data exist for many years in the same manner. Structure of above table is: ID (integer serial not null), Date (date) (mm/dd/yyyy), hour (integer), value (numeric). For a large set of data like above, how do I find daily, weekly, monthly and yearly averages in PostgreSQL? A: You use aggregation. For instance: select date, avg(value) from t group by date order by date; For the rest, use date_trunc(): select date_trunc('month', date) as yyyymm, avg(value) from t group by yyyymm order by yyyymm; This assumes that date is stored as a date data type. If it is stored as a string you should fix the data type in your data. You can convert it to a date using to_date().
{ "pile_set_name": "StackExchange" }
Q: counter in xslt not working correctly i'm having the below XML Document. <?xml version="1.0" encoding="UTF-8"?> <chapter num="A"> <title> <content-style font-style="bold">PART 1 GENERAL PRINCIPLES</content-style> </title> <section level="sect1"> <title> <content-style font-style="bold">Chapter 2: PREVENTING COMMERCIAL DISPUTES</content-style> </title> <section level="sect2" number-type="manual" num="1."> <title>INTRODUCTION</title> <para> <phrase>2.001</phrase> With increasing competition in the business environment and the need to provide value for money to customers, most, if not all businesses, cannot afford to continuously be engaged in the dispute resolution arena as though it were a part of their core business. If all the disputes of a business entity have to be litigated or arbitrated to the bitter end, then this will become a substantial drain on its financial resources and big distraction for its management. Prolonged engagement in litigation and arbitration will undoubtedly have a detrimental effect on the business.</para> <para> <phrase>2.002</phrase> Preventing or minimising disputes requires businesses to know and understand the people they are dealing with and they will also need to ensure that the governing contracts are clearly and carefully drafted in order to safeguard the rights of both parties. The parties need to devote resources to train their employees to carefully and skilfully monitor the performance of the contracts and to maintain proper and adequate documentary records. This requires financial investment which some businesses are unable or reluctant to budget for. However, those businesses which have a keen awareness of the need to prevent or minimise disputes and are willing to provide the financial investment to attain this will find that, with a manageable preventative dispute resolution philosophy in place, this will, in the long term, be cost-effective and above all, create an environment that preserves close working relationships.</para> </section> <section level="sect2" number-type="manual" num="2."> <title>SELECTING A COUNTERPARTY</title> <para> <phrase>2.003</phrase> Commercial disputes inevitably arise between two or more parties under a commercial contract. The attributes of the counterparty with which one contracts will therefore have an impact on whether disputes can be prevented or, even if not, whether disputes can be resolved in an efficient and cost-effective manner, which will ultimately benefit both parties.</para> <para> <phrase>2.004</phrase> Consideration should be given to certain aspects of the counterparty before a contract is entered into. These attributes of a contracting party can impact on whether the relationship is likely to go smoothly or whether it is going to be &#x201C;dispute prone&#x201D;.</para> <section level="sect2" number-type="manual" num="(a)"> <title>Financial power</title> <para> <phrase>2.005</phrase> A contracting party which has financial substance is, in general, more likely to be willing to abide by their contractual obligations, simply because they are relatively easy targets of a lawsuit. On the other hand, where one contracts with an insubstantial or &#x201C;fly-by-night&#x201D; party, there is a genuine concern that, once the contract becomes unprofitable or if something goes wrong, there is a bigger propensity for disputes to arise as a result of the latter seeking to avoid its obligations.</para> </section> <section level="sect2" number-type="manual" num="(b)"> <title>Market reputation</title> <para> <phrase>2.006</phrase> A contracting party which has a market reputation it wishes to safeguard is likely to be more careful in the type of disputes it would be likely to get involved in. Listed companies or those which have a public image to preserve are, in general, more likely to avoid litigating every claim irrespective of size (unless such claims, if not litigated, are liable to open up floodgates) to minimise the bad publicity associated with being in the courts too often, or giving the impression to potential future contracting parties that they are litigious and difficult to deal with.</para> </section> <section level="sect2" number-type="manual" num="(c)"> <title>Location and culture</title> <para> <phrase>2.007</phrase> This is a sensitive topic and therefore there will be no specific references. However, a discussion of this type would be incomplete without acknowledging the fact that businesses or projects in certain parts of the world are more prone to conflicts or natural disasters and are more likely to end up in disputes than those in more &#x201C;peaceful&#x201D; parts of the world. Certain cultures tend also to be more litigious than others, and when contracting with parties of certain cultural backgrounds that focus less on mutual tolerance and co-operation, there will be more expectation of disputes.</para> </section> <section level="sect2" number-type="manual" num="(d)"> <title>Focus/investment on risk prevention</title> <para> <phrase>2.008</phrase> Certain contracting parties, more often seen in developed countries, have a better awareness of the law and the need to invest in risk prevention in order to minimise the probability of disputes. &#x201C;Investments&#x201D; in this regard include spending money to vet their business partners, including investigating their financial status and their market reputation, and allowing their legal department a sufficient budget to properly review draft contracts, assist with negotiations and to keep fully up-to-date with the latest legal developments.</para> </section> </section> <section level="sect2" number-type="manual" num="3."> <title>CONTRACT NEGOTIATION AND DRAFTING</title> <para> <phrase>2.009</phrase> There are two basic ways in which conflicts can be avoided without the need for the use of dispute resolution mechanisms. The first is the use of negotiation skills to negotiate a contract that affords the best terms and conditions possible, covering all or most foreseeable contingencies. Having clear and favourable provisions in a contract puts a party in a better position, especially when it is sought to resolve disputes at their source, without the need to revert to the dispute resolution mechanisms provided for in the contract. This, without a doubt, is the cheapest and most effective means of avoiding disputes or resolving possible disputes. The importance of contract negotiations should not be lightly dismissed.</para> <para> <phrase>2.010</phrase> The second is having a clearly drafted contract that is well thought out and planned and serves everyone&#x2019;s interests. Often a hastily drafted contract that is put together at the last minute results in uncertainty and vagueness of terms which could potentially create disputes. The inclusion of appropriate clauses (for example, clauses that cover force majeure or hardship) provide for changing conditions that may render the contract impossible to perform are of major importance. The drafting of such clauses is relatively technical in nature and requires the skills of a competent drafter of commercial contracts to ensure that they are manageable from a commercial standpoint.</para> <para> <phrase>2.011</phrase> An area to be aware of is the use of standard form contracts and adopting such forms within the existing framework of the contract. Although there are a variety of such standard form contracts available in the market place to be referred to, care must be taken, as these forms are only a guide to assist in the drafting of a contract that suits individual needs. Consulting legal counsel for advice is beneficial, especially when the contract touches on issues such as jurisdiction, which can often be difficult concepts for a lay person to understand.</para> <para> <phrase>2.012</phrase> The drafting of specialist contracts such as those in the construction, insurance, commodity and maritime fields requires a great deal of industry knowledge and experience to ensure that suitable wording is used to minimise the chances of disputes. However, regardless of the type of contract involved, there are certain provisions which are generic in nature, and the inclusion of which will generally (although not always) minimise the scope of the disputes between the parties, and are usually good to have. These provisions are often referred to as boilerplate clauses.</para> <para> <phrase>2.013</phrase> The importance of boilerplate clauses is often overlooked as the parties tend to focus on the commercial terms of the contract, such as the cost of the goods or services being provided. Failure to include appropriate boilerplate clauses may prevent a party from effectively enforcing its rights under the contract and offer an escape route to the defaulting party from its liabilities.</para> </section> </section> </chapter> and when i apply the below xslt, the counter in section (taken as ), everytime a new section with number in num is found, the counter is getting reset to 1 but if the num is having value like (a),(b) .. it is continuing, what i want is, the counter should be never be reset to 1. please help me in acheiving this. XSLT <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ntw="Number2Word.uri" exclude-result-prefixes="ntw"> <xsl:variable name="ThisDocument" select="document('')"/> <xsl:output method="html"/> <xsl:template match="/"> <xsl:text disable-output-escaping="yes">&lt;!DOCTYPE&gt;</xsl:text> <html> <head> <xsl:text disable-output-escaping="yes"><![CDATA[</meta>]]></xsl:text> <title> <xsl:value-of select="substring-after(chapter/section/title,':')"/> </title> <link rel="stylesheet" href="er:#css" type="text/css"/><xsl:text disable-output-escaping="yes"><![CDATA[</link>]]></xsl:text> </head> <body> <xsl:apply-templates/> <section class="tr_footnotes"> <hr/> <xsl:apply-templates select="//footnote" mode="footnote"/> </section> </body> </html> </xsl:template> <xsl:template match="chapter"> <section class="tr_chapter"> <div class="chapter"> <xsl:variable name="l"> <xsl:value-of select="substring(substring-after(section/title,' '),1,1)"/> </xsl:variable> <a name="AHK_CH_0{$l}"/> <div class="chapter-title"> <xsl:variable name="titl"> <xsl:value-of select="substring-after(section/title,':')"/> </xsl:variable> <span class="chapter-num"> <xsl:value-of select="concat('Chapter ',$l,' ')"/> </span> <xsl:value-of select="$titl"/> </div> <div class="para align-center"> <span class="font-style-italic"> <xsl:value-of select="document('AHK-authors.xml')/chapters/chapter[@no=$l]"/> </span> </div> <div class="para align-right"><span class="format-smallcaps">Para</span>.</div> <div class="toc"> <div class="toc-part"> <table class="toc-div"> <tbody> <tr> <td> <xsl:for-each select="current()/section/section|current()/section/section/section[contains(@num, '(')]|current()/section/section/section/section[contains(@num, '(')]"> <xsl:call-template name="IndexItem"> </xsl:call-template> </xsl:for-each> </td> </tr> </tbody> </table> </div> </div> <xsl:apply-templates select="section/section"/> </div> </section> </xsl:template> <xsl:template match="chapter/para"> <div class="para align-right"> <span class="format-smallcaps">Para</span>. </div> <xsl:apply-templates select="section"/> </xsl:template> <xsl:template name="fig" match="figure"> <div class="figure"> <div class="figure-title"> <xsl:value-of select="current()/title"/> </div> <xsl:variable name="numb"> <xsl:value-of select="substring-after(graphic/@href,'_')"/> </xsl:variable> <xsl:variable name="figCon"> <xsl:value-of select="concat('er:#page-',$numb)"/> </xsl:variable> <img class="graphic" src="{$figCon}" alt=""/> </div> </xsl:template> <xsl:template name="IndexItem"> <xsl:if test="not(contains(@level,'sect1'))"><!--changed fron @num to sect2--> <xsl:variable name="tocpg"> <xsl:value-of select="concat('#P',descendant::para/phrase[1]/text())"/> </xsl:variable> <xsl:variable name="tocpgtag" select="translate($tocpg,'.', '-')"/> <xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'"/> <xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/> <xsl:variable name="text" select="current()/title/text()"/> <xsl:variable name="Brac"> <xsl:choose> <xsl:when test="contains(current()/@num,'(')"> <xsl:value-of select="2"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="1"/> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="d"> <xsl:value-of select="concat('toc-item-',$ThisDocument//ntw:nums[@num=$Brac]/@word,'-level')"/> </xsl:variable> <table class="{$d}"> <tbody> <tr> <td class="toc-item-num"> <xsl:value-of select="@num"/> </td> <td class="toc-title"> <xsl:value-of select="concat(substring($text,1,1), translate(substring($text,2), $uppercase, $smallcase))"/> </td> <td class="toc-pg"> <a href="{$tocpgtag}"> <xsl:value-of select="descendant::para/phrase[1]/text()"/> </a> </td> </tr> </tbody> </table> </xsl:if> </xsl:template> <!-- Index Templates Complete --> <!-- Paragraph templates --> <xsl:template name="section" match="section"> <!-- Variables--> <xsl:variable name="classname"> <!--Get name attribute of current node --> <xsl:value-of select="concat('section-',parent::section/@level)"/> </xsl:variable> <xsl:variable name="chapternumber"> <!-- Get num attribute of parent node --> <xsl:variable name="StrL"> <xsl:value-of select="string-length(substring(substring-after(ancestor::chapter/section/title,'Chapter '),1,1))"/> </xsl:variable> <xsl:choose> <xsl:when test="$StrL>1"> <xsl:value-of select="substring(substring-after(ancestor::chapter/section/title,'Chapter '),1,1)"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="concat('0',substring(substring-after(ancestor::chapter/section/title,'Chapter '),1,1))"/> </xsl:otherwise> </xsl:choose> </xsl:variable> <xsl:variable name="sectnum"> <xsl:number format="1"/> </xsl:variable> <!--Create a string variable by concat string method --> <xsl:variable name="sectionname"> <xsl:value-of select="concat('CH_',$chapternumber,'-SEC-', $sectnum)"/> </xsl:variable> <!-- Template Content --> <div class="{$classname}"> <a name="{$sectionname}"> </a> <div class="section-title"> <span class="section-num"> <xsl:value-of select="@num"/> <xsl:text> </xsl:text> </span> <xsl:apply-templates select="title"/> </div> <xsl:apply-templates select="child::node()[not(self::title)]"/> </div> </xsl:template> <xsl:template name="para" match="section/para"> <div class="para"> <xsl:apply-templates select="phrase"/> <span class="phrase"> <xsl:value-of select="current()/phrase"/> </span> <xsl:choose> <xsl:when test="contains(current()/text(),'Chapter')"> <xsl:variable name="x"> <xsl:value-of select="substring(substring-before(current()/text(),'Chapter'),1)"/> </xsl:variable> <xsl:variable name="y"> <xsl:value-of select="substring(substring-after(current()/text(),'Chapter'),4)"/> </xsl:variable> <xsl:variable name="z"> <xsl:value-of select="normalize-space(substring-before(substring-after(current()/text(),'Chapter'),'.'))"/> </xsl:variable> <xsl:variable name="h"> <xsl:value-of select="string-length($z)"/> </xsl:variable> <xsl:value-of select="$x"/> <xsl:choose> <xsl:when test="$h =1"> <a href="{concat('er:#AHK_CH_0',$z,'/AHK_CH_0',$z)}"> <xsl:value-of select="concat('Chapter',$z)"/> </a> </xsl:when> <xsl:otherwise> <a href="{concat('er:#AHK_CH_',$z,'/AHK_CH_',$z)}"> <xsl:value-of select="concat('Chapter',$z)"/> </a> </xsl:otherwise> </xsl:choose> <xsl:value-of select="$y "/> <xsl:apply-templates select="footnote"/> <xsl:apply-templates select="current()/phrase/text()"/> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="child::node()[not(self::phrase)]"/> </xsl:otherwise> </xsl:choose> </div> </xsl:template> <xsl:template name="phrase" match="phrase"> <xsl:variable name="phrase"> <xsl:value-of select="concat('P',text())"/> </xsl:variable> <xsl:variable name="newphrase" select="translate($phrase,'.','-')"/> <a> <xsl:attribute name="name"><xsl:value-of select="$newphrase"></xsl:value-of></xsl:attribute> </a> </xsl:template> <!-- Table Templates --> <xsl:template name="table" match="table"> <table style="frame-{current()/@frame} width-{translate(current()/@width,'%','')}"> <xsl:apply-templates/> </table> </xsl:template> <xsl:template match="tgroup"> <colgroup> <xsl:apply-templates select=".//colspec"/> </colgroup> <xsl:apply-templates select="child::node()[not(self::colspec)]"/> </xsl:template> <xsl:template name="tbody" match="tgroup/tbody"> <tbody> <xsl:for-each select="current()/row"> <xsl:call-template name="row"/> </xsl:for-each> </tbody> </xsl:template> <xsl:template name="thead" match="tgroup/thead"> <xsl:for-each select="current()/row"><thead> <tr> <xsl:for-each select="current()/entry"> <xsl:call-template name="headentry"/> </xsl:for-each> </tr> </thead> </xsl:for-each> </xsl:template> <xsl:template name="colspec" match="colspec"> <col class="colnum-{current()/@colnum} colname-{current()/@colname} colwidth-{translate(current()/@colwidth,'%','')}"/> </xsl:template> <xsl:template name="row" match="tbody/row"> <tr> <xsl:for-each select="current()/entry"> <xsl:call-template name="entry"/> </xsl:for-each> </tr> </xsl:template> <xsl:template name="entry" match="entry"> <xsl:variable name="count"> <xsl:value-of select="count(preceding-sibling::* | following-sibling::*)"/> </xsl:variable> <xsl:choose> <xsl:when test="$count &lt; 2"> <xsl:if test="position()=1"> <td> <div class="para align-center"> <xsl:value-of select="para[position()=1]"/> </div> </td> <td> <div class="para"> <xsl:value-of select="following-sibling::node()"/> </div> </td> </xsl:if> </xsl:when> <xsl:when test="$count &gt; 1"> <td> <div class="para"> <xsl:apply-templates/> </div> </td> </xsl:when> </xsl:choose> </xsl:template> <xsl:template name="headentry"> <th> <xsl:if test="translate(current()/@namest,'col','') != translate(current()/@nameend,'col','')"> <xsl:variable name="colspan"> <xsl:value-of select="translate(current()/@nameend,'col','') - translate(current()/@namest,'col','') + 1"/> </xsl:variable> <xsl:attribute name="colspan"><xsl:value-of select="$colspan"></xsl:value-of></xsl:attribute> </xsl:if> <div class="para"> <xsl:value-of select="current()/para/text()"/> <xsl:apply-templates/> </div> </th> </xsl:template> <!-- Table Templates complete --> <!--List templates --> <xsl:template name="orderedlist" match="orderedlist"> <ol class="eng-orderedlist orderedlist"> <xsl:apply-templates/> </ol> </xsl:template> <xsl:template name="orderitem" match="item"> <li class="item"> <xsl:apply-templates/> </li> </xsl:template> <xsl:template name="orderitempara" match="item/para"> <div class="para"> <span class="item-num"> <xsl:if test="position()=1"> <xsl:value-of select="parent::item[1]/@num"/> <xsl:text> </xsl:text> </xsl:if> </span> <xsl:apply-templates/> </div> </xsl:template> <!--List templates Complete --> <!-- Paragraph templates Complete --> <!-- Footnote Templates--> <xsl:template match="footnote"> <sup> <a> <xsl:attribute name="name"><xsl:text>f</xsl:text><xsl:number level="any" count="footnote" format="1"/></xsl:attribute> <xsl:attribute name="href"><xsl:text>#ftn.</xsl:text><xsl:number level="any" count="footnote" format="1"/></xsl:attribute> <xsl:attribute name="class"><xsl:text>tr_ftn</xsl:text></xsl:attribute> <xsl:number level="any" count="footnote" format="1"/> </a> </sup> </xsl:template> <xsl:template match="footnote" mode="footnote"> <div class="tr_footnote"> <div class="footnote"> <sup> <a> <xsl:attribute name="name"><xsl:text>ftn.</xsl:text><xsl:number level="any" count="footnote" format="1"/></xsl:attribute> <xsl:attribute name="href"><xsl:text>#f</xsl:text><xsl:number level="any" count="footnote" format="1"/></xsl:attribute> <xsl:attribute name="class"><xsl:text>tr_ftn</xsl:text></xsl:attribute> <xsl:number level="any" count="footnote" format="1"/> </a> </sup> <div class="a"> <xsl:variable name="new"> <xsl:value-of select="current()"/> </xsl:variable> <xsl:variable name="new1"> <xsl:value-of select="substring(substring-after(current(),'paragraph'),2,5)"/> </xsl:variable> <xsl:variable name="roo"> <xsl:value-of select="substring(//@num,2)"/> </xsl:variable> <xsl:variable name="befTex"> <xsl:value-of select="substring-before(current(),'paragraph')"/> </xsl:variable> <xsl:variable name="before"> <xsl:value-of select="substring-before($new1,'.')"/> </xsl:variable> <xsl:variable name="after"> <xsl:value-of select="substring(substring-after($new1,'.'),1,3)"/> </xsl:variable> <xsl:variable name="centTex"> <xsl:value-of select="substring(substring-after(current(),$after),1)"/> </xsl:variable> <xsl:variable name="pCon"> <xsl:value-of select="concat('paragraph',' ',$before,'.',$after)"/> </xsl:variable> <xsl:variable name="tes"> <xsl:if test="contains($centTex,'chapter')"> <xsl:value-of select="concat(' ',substring(substring-before($centTex,'chapter'),2))"/> </xsl:if> </xsl:variable> <xsl:variable name="ChapNu"> <xsl:value-of select="normalize-space(substring(substring-after(current(),'chapter'),1,2))"/> </xsl:variable> <xsl:variable name="ChapNuC"> <xsl:value-of select="concat('er:#BVI_CH_0',$ChapNu,'/BVI_CH_0',$ChapNu)"/> </xsl:variable> <xsl:variable name="curSel"> <xsl:value-of select="concat('#P',$before,'-',$after)"/> </xsl:variable> <xsl:variable name="ChapCon"> <xsl:value-of select="concat('chapter',' ',substring(substring-after(current(),'chapter'),2,1))"/> </xsl:variable> <xsl:variable name="conc1"> <xsl:value-of select="concat('er:#BVI_CH_0',$before,'/P',$before,'-',$after)"/> </xsl:variable> <xsl:value-of select="$befTex"/> <xsl:choose> <xsl:when test="contains(substring(substring-after($new,'paragraph'),1,3),'.')"> <xsl:choose> <xsl:when test="$before = $roo"> <a href="{$curSel}"> <xsl:value-of select="$pCon"/> </a> </xsl:when> <xsl:otherwise> <a href="{$conc1}"> <xsl:value-of select="$pCon"/> </a> </xsl:otherwise> </xsl:choose> <xsl:value-of select="$tes"/> <xsl:if test="contains($centTex,'chapter')"> <a href="{$ChapNuC}"> <xsl:value-of select="$ChapCon"/> </a> </xsl:if> <xsl:text>.</xsl:text> </xsl:when> <xsl:otherwise> <xsl:apply-templates/> </xsl:otherwise> </xsl:choose> </div> </div> </div> </xsl:template> <xsl:template match="footnote/para/uri"> <xsl:variable name="url1"> <xsl:value-of select="translate(@href, '&#x003C;','')" /> </xsl:variable> <xsl:variable name="url2"> <xsl:value-of select="translate($url1, '&#x003E;','')" /> </xsl:variable> <a href="{$url2}"> <xsl:value-of select="." /> </a> </xsl:template> <!-- Footnote Templates Complete --> <xsl:template match="content-style"> <xsl:choose> <xsl:when test="@format='smallcaps'"> <xsl:value-of select="translate(normalize-space(.),'ABCDEFGHIJKLMNOPQRSTUVWXZ','abcdefghijklmnopqrstuvwxyz')"/> </xsl:when> <xsl:when test="@format='superscript'"> </xsl:when> <xsl:otherwise> <xsl:variable name="fontStyle"> <xsl:value-of select="concat('font-style-',@font-style)"/> </xsl:variable> <span class="{$fontStyle}"> <xsl:apply-templates/> </span> </xsl:otherwise> </xsl:choose> </xsl:template> <!-- Namespace ntw--> <ntw:nums num="1" word="first"/> <ntw:nums num="2" word="second"/> <ntw:nums num="3" word="third"/> <ntw:nums num="4" word="forth"/> <ntw:nums num="5" word="fifth"/> <ntw:nums num="6" word="sixth"/> <ntw:nums num="7" word="seventh"/> <ntw:nums num="8" word="eighth"/> <ntw:nums num="9" word="nighth"/> <ntw:nums num="10" word="tenth"/> <!-- Namespace ntw ends --> </xsl:stylesheet> Thanks A: I've used the counter value as 1 in the below code, but i\ need to use the code given in the second block below. <xsl:variable name="sectionname"> <xsl:value-of select="concat('CH_',$chapternumber,'-SEC-', $sectnum)"/> </xsl:variable> <xsl:variable name="sectnum"> <xsl:for-each select="Current()"> <xsl:value-of select="count(preceding-sibling::*)"/> </xsl:for-each/> </xsl:variable> and this will give the value.
{ "pile_set_name": "StackExchange" }
Q: Get image src from html element Inside my HTML I have this <link rel="image_src" href="data/20/1.jpg" /> I need to retrieve the href (data/20/1.jpg). I tried the code below without any luck function fetch_rel($url) { $data = file_get_contents($url); $dom = new DomDocument; @$dom->loadHTML($data); $xpath = new DOMXPath($dom); # query metatags with og prefix $metas = $xpath->query('//*/link[starts-with(@rel, \'image_src\')]'); $og = array(); foreach($metas as $meta){ # get property name without og: prefix $property = str_replace('image_src', '', $meta->getAttribute('rel')); # get content $content = $meta->getAttribute('href'); $og[$property] = $content; } return $og; } $og = fetch_rel($u); $image_src = $og['image_src']; Any suggestions? A: I think you've made just a little error: You try to access $og['image_src'];, but your array has no index image_src, because you replaced image_src with ''. You have to replace this line: # get property name without og: prefix <-- By the way: you have no og: prefix ;) $property = str_replace('image_src', '', $meta->getAttribute('rel')); with this: $property = $meta->getAttribute('rel');
{ "pile_set_name": "StackExchange" }
Q: Internet Explorer does not prompt for windows authentication after session timeout I have a problem with SSRS Report Manager web application(but again I see this more as a typical ASP.Net application issue as well). This application is configured to use the Windows Authentication and users typically acess the application using Internet Explorer. The application also has the session timeout setup for 20 minutes. The issue (which has be interpreted as Information security issue :( ) is that, if the user is idle on this application for more than 20 minutes, he can still come back and continue working with any problem. They said that it's not timing out at all as they do not get the Login prompt. When I run the Fiddler, I observed that first request after 20 minutes, is in-fact 401 that means, server has declined the request. After that, I believe, Internet Explorer sents the cached credentials. Because of this the Login Prompt does not appear. The questions I have is these 1. Is it true that the IE can send cached credentials after session is timed out? Any Microsoft Link/reference? 2. Is there any way we could force the login dialog to come after session timed out? (I removed from IE settings tab and advaced tab but no luck) A: Their is a very good blog-post discussing a few different options, but the best one is to get your application to detect the session timeout and send a 401 response code. An alternative (and better) approach is to not use Windows Authentication, and to implement your own login interface. This is pretty straight-forward in ASP.NET. If you do not have control of your application, and it sounds like you don't, then there is not a lot you can do. However, that doesn't explain what you are trying to achieve by forcing the user to login manually, and re-login if their session expires. The only time that you would gain anything from forcing the user to log-in to your web-site manually is if you expected them to leave their computer unlocked - but then you already have a gaping security hole anyway. It's like winding up the windows in your car, but then leaving the doors unlocked and the key on the roof.
{ "pile_set_name": "StackExchange" }
Q: Always show the navigation arrows on a FlipView control in UWP When using a mouse and hovering over a Universal Windows Platform (UWP) FlipView control the previous/next navigation buttons are shown. However, when using touch or pen, they remain hidden which may confuse users into not expecting additional content. I would like navigation buttons to always be visible. How can I do this? A: We need to create a custom FlipView. Start with the code shown below: public class CustomFlipView : FlipView { protected override void OnApplyTemplate() { base.OnApplyTemplate(); SelectionChanged += (s,e) => UpdateNavigationButtonsVisibility(); Button prev = GetTemplateChild("MyPreviousButtonHorizontal") as Button; prev.Click += OnBack; prev.Visibility = Visibility.Collapsed; Button next = GetTemplateChild("MyNextButtonHorizontal") as Button; next.Click += OnNext; next.Visibility = Visibility.Collapsed; } private void OnBack(object sender, RoutedEventArgs e) { if (Items.Any()) { SelectedIndex--; UpdateNavigationButtonsVisibility(); } } private void OnNext(object sender, RoutedEventArgs e) { if (Items.Any()) { SelectedIndex++; UpdateNavigationButtonsVisibility(); } } private void UpdateNavigationButtonsVisibility() { Button prev = GetTemplateChild("MyPreviousButtonHorizontal") as Button; Button next = GetTemplateChild("MyNextButtonHorizontal") as Button; if (SelectedIndex < 1) prev.Visibility = Visibility.Collapsed; if (SelectedIndex == Items.Count - 1) next.Visibility = Visibility.Collapsed; if (Items.Count > 1 && SelectedIndex != Items.Count - 1) next.Visibility = Visibility.Visible; if (Items.Count > 1 && SelectedIndex > 0) prev.Visibility = Visibility.Visible; } } Build the project before opening the XAML file where you need to insert the CustomFlipView. Then add the control to your XAML; you may need to add namespace declaration depending where you created the CustomFlipView class. The problem with the default FlipView is the scroll buttons reveal themselves only when pointing over it, something we do not have in case of a touch device. To make things more complicated, internal code sets the template’s buttons opacity to zero when loaded, so we need to change the name of both navigation buttons so the internal code gracefully degrades and allows them to be visible all the time. Then we add code to handle when the navigation buttons are clicked so we don't show previous button on first page or show next button on last page. To overwrite the names of navigation buttons, we need to edit the control's template. The quickest way is by opening the Document Outline pane, right-clicking your CustomFlipView → Edit Template → Edit a Copy. A lot of code will appear in your XAML, but the important part to find looks like this: <Button x:Name="MyPreviousButtonHorizontal" HorizontalAlignment="Left" Height="70" IsTabStop="False" Template="{StaticResource HorizontalPreviousTemplate}" UseSystemFocusVisuals="False" VerticalAlignment="Center" Width="40"/> <Button x:Name="MyNextButtonHorizontal" HorizontalAlignment="Right" Height="70" IsTabStop="False" Template="{StaticResource HorizontalNextTemplate}" UseSystemFocusVisuals="False" VerticalAlignment="Center" Width="40"/> Note I renamed the x:Name properties from PreviousButtonHorizontal to MyPreviousButtonHorizontal and NextButtonHorizontal to MyNextButtonHorizontal to match with the code-behind we wrote earlier. Now the CustomFlipView should display navigation arrows when using touch and pen, not just mouse.
{ "pile_set_name": "StackExchange" }
Q: Javascript: check if checkboxes are checked by looping through an array I have 3 sets of checkboxes - checkboxDofM, checkboxMonth and checkboxDay. I want to check if any of the boxes of checkboxDofM are checked. If they are, then the user should not able to check any boxes of checkboxDay. Likewise, if any of the boxes in checkboxDay are checked, then the user should not be able to select any boxes of checkboxDofM. The only problem is I don't know how to do this as I have no control of the ID and Name of the checkboxes being generated and the "checked" function doesn't seem to be working. Can someone help me with this? Developer Tools showing what's inside the element of the array I'm getting Here is the view: @using (Html.BeginForm("ScheduleInfo", "Scheduler", FormMethod.Post)) { Html.EnableClientValidation(); <center> <div class="col-2"> <ul class="list-group"> <li class="list-group-item-heading list-group-item active"> <h4 class="list-group-item-text">Select the day(s) of the month the task should be set at</h4> </li> @Html.HiddenFor(m => m.DofMID) @Html.DisplayFor(m => m.DofMNo) @for (int i = 0; i < Model.DofMInfo.Count; i++) { <li class="list-group-item" style="display:inline-block"> <div class="checkbox-inline checkboxDofM" id= "checkboxDofM"> @Html.HiddenFor(m => m.DofMInfo[i].DofMID) @Html.CheckBoxFor(m => m.DofMInfo[i].IsChecked) @Html.LabelFor(m => m.DofMInfo[i].IsChecked, Model.DofMInfo[i].DofMNo) </div> </li> } </ul> </div> </center> <center> <div class="col-2"> <ul class="list-group"> <li class="list-group-item-heading list-group-item active"> <h4 class="list-group-item-text">Select the month(s) the task should be set at</h4> </li> @Html.HiddenFor(m => m.monthID) @Html.DisplayFor(m => m.monthName) @for (int i = 0; i < Model.MonthInfo.Count; i++) { <li class="list-group-item" style="display:inline-block"> <div class="checkbox-inline checkboxMonth" id="checkboxMonth"> @Html.HiddenFor(m => m.MonthInfo[i].monthID) @Html.CheckBoxFor(m => m.MonthInfo[i].IsChecked) @Html.LabelFor(m => m.MonthInfo[i].IsChecked, Model.MonthInfo[i].monthName) </div> </li> } </ul> </div> </center> <center> <div class="col-3"> <ul class="list-group"> <li class="list-group-item-heading list-group-item active"> <h4 class="list-group-item-text">Select the day(s) the task should be set at</h4> </li> @Html.HiddenFor(m => m.dayID) @Html.DisplayFor(m => m.dayName) @for (int i = 0; i < Model.DayInfo.Count; i++) { <li class="list-group-item" style="display:inline-block"> <div class="checkbox-inline checkboxDay" id="checkboxDay"> @Html.HiddenFor(m => m.DayInfo[i].dayID) @Html.CheckBoxFor(m => m.DayInfo[i].IsChecked) @Html.LabelFor(m => m.DayInfo[i].IsChecked, Model.DayInfo[i].dayName) </div> </li> } </ul> </div> </center> <script type="text/javascript"> var myFunction = function () { var DofMCheck = Array.from(document.getElementsByClassName("checkbox-inline checkboxDofM")); console.log(DofMCheck); }(); </script> <input type="submit" value="Submit Data" id="btnSubmit" /> } Here is the viewModel: public class Values { public List<object> DayOfMonth { get; set; } public List<object> Month { get; set; } public List<object> DaysOfWeek { get; set; } [Required(ErrorMessage = "Field must not be left blank!")] [RegularExpression(@"^(,{0,1}(\b\d\b|[0-5][0-9]|\*+)(-\b\d\b|-[0-5][0-9]){0,1})$", ErrorMessage = "Enter a number between 0-59!")] public object Second { get; set; } [Required(ErrorMessage = "Enter a number between 0-59!")] [RegularExpression(@"^(,{0,1}(\b\d\b|[0-5][0-9]|\*+)(-\b\d\b|-[0-5][0-9]){0,1})$", ErrorMessage = "Enter a number between 0-59!")] public object Minute { get; set; } [Required(ErrorMessage = "Enter a number between 0-23!")] [RegularExpression(@"^(,{0,1}(\b\d\b|[0-1][0-9]|[2][0-3]|\*+)(-\b\d\b|-[0-1][0-9]|-[2][0-4]){0,1})$", ErrorMessage = "Enter a number between 0-23!")] public object Hour { get; set; } public List<SelectListItem> Jobs { get; set; } public int Job { get; set; } public List<Values> DofMInfo { get; set; } public string DofMNo { get; set; } public int DofMID { get; set; } public List<Values> MonthInfo { get; set; } public int monthID { get; set; } public string monthName { get; set; } public List<Values> DayInfo { get; set; } public int dayID { get; set; } public string dayName { get; set; } public bool IsChecked { get; set; } } } Here is the controller: public class SchedulerController : Controller { // GET: Scheduler [HttpGet] public ActionResult SchedulerIndex() { List<Values> lst = new List<Values>(); List<Values> lst2 = new List<Values>(); List<Values> lst3 = new List<Values>(); Values val = new Values(); val.Jobs = new List<SelectListItem>(); val.Jobs.Add(new SelectListItem() { Text = "Email", Value = "1", Selected = false }); val.Jobs.Add(new SelectListItem() { Text = "Backup", Value = "2", Selected = false }); val.Jobs.Add(new SelectListItem() { Text = "Start Application", Value = "3", Selected = false }); val.Jobs.Add(new SelectListItem() { Text = "Job4", Value = "4", Selected = false }); val.Jobs.Add(new SelectListItem() { Text = "Job5", Value = "5", Selected = false }); List<Values> month11 = new List<Values>(); month11.Add(new Values { monthID = 0, monthName = "Jan", IsChecked = false }); month11.Add(new Values { monthID = 1, monthName = "Feb", IsChecked = false }); month11.Add(new Values { monthID = 2, monthName = "Mar", IsChecked = false }); month11.Add(new Values { monthID = 3, monthName = "Apr", IsChecked = false }); month11.Add(new Values { monthID = 4, monthName = "May", IsChecked = false }); month11.Add(new Values { monthID = 5, monthName = "Jun", IsChecked = false }); month11.Add(new Values { monthID = 6, monthName = "Jul", IsChecked = false }); month11.Add(new Values { monthID = 7, monthName = "Aug", IsChecked = false }); month11.Add(new Values { monthID = 8, monthName = "Sep", IsChecked = false }); month11.Add(new Values { monthID = 9, monthName = "Oct", IsChecked = false }); month11.Add(new Values { monthID = 10, monthName = "Nov", IsChecked = false }); month11.Add(new Values { monthID = 11, monthName = "Dec", IsChecked = false }); List<Values> day6 = new List<Values>(); day6.Add(new Values { dayID = 0, dayName = "Mon", IsChecked = false }); day6.Add(new Values { dayID = 1, dayName = "Tue", IsChecked = false }); day6.Add(new Values { dayID = 2, dayName = "Wed", IsChecked = false }); day6.Add(new Values { dayID = 3, dayName = "Thu", IsChecked = false }); day6.Add(new Values { dayID = 4, dayName = "Fri", IsChecked = false }); day6.Add(new Values { dayID = 5, dayName = "Sat", IsChecked = false }); day6.Add(new Values { dayID = 6, dayName = "Sun", IsChecked = false }); List<Values> days31 = new List<Values>(); days31.Add(new Values { DofMID = 0, DofMNo = "1", IsChecked = false }); days31.Add(new Values { DofMID = 1, DofMNo = "2", IsChecked = false }); days31.Add(new Values { DofMID = 2, DofMNo = "3", IsChecked = false }); days31.Add(new Values { DofMID = 3, DofMNo = "4", IsChecked = false }); days31.Add(new Values { DofMID = 4, DofMNo = "5", IsChecked = false }); days31.Add(new Values { DofMID = 5, DofMNo = "6", IsChecked = false }); days31.Add(new Values { DofMID = 6, DofMNo = "7", IsChecked = false }); days31.Add(new Values { DofMID = 7, DofMNo = "8", IsChecked = false }); days31.Add(new Values { DofMID = 8, DofMNo = "9", IsChecked = false }); days31.Add(new Values { DofMID = 9, DofMNo = "10", IsChecked = false }); days31.Add(new Values { DofMID = 10, DofMNo = "11", IsChecked = false }); days31.Add(new Values { DofMID = 11, DofMNo = "12", IsChecked = false }); days31.Add(new Values { DofMID = 12, DofMNo = "13", IsChecked = false }); days31.Add(new Values { DofMID = 13, DofMNo = "14", IsChecked = false }); days31.Add(new Values { DofMID = 14, DofMNo = "15", IsChecked = false }); days31.Add(new Values { DofMID = 15, DofMNo = "16", IsChecked = false }); days31.Add(new Values { DofMID = 16, DofMNo = "17", IsChecked = false }); days31.Add(new Values { DofMID = 17, DofMNo = "18", IsChecked = false }); days31.Add(new Values { DofMID = 18, DofMNo = "19", IsChecked = false }); days31.Add(new Values { DofMID = 19, DofMNo = "20", IsChecked = false }); days31.Add(new Values { DofMID = 20, DofMNo = "21", IsChecked = false }); days31.Add(new Values { DofMID = 21, DofMNo = "22", IsChecked = false }); days31.Add(new Values { DofMID = 22, DofMNo = "23", IsChecked = false }); days31.Add(new Values { DofMID = 23, DofMNo = "24", IsChecked = false }); days31.Add(new Values { DofMID = 24, DofMNo = "25", IsChecked = false }); days31.Add(new Values { DofMID = 25, DofMNo = "26", IsChecked = false }); days31.Add(new Values { DofMID = 26, DofMNo = "27", IsChecked = false }); days31.Add(new Values { DofMID = 27, DofMNo = "28", IsChecked = false }); days31.Add(new Values { DofMID = 28, DofMNo = "29", IsChecked = false }); days31.Add(new Values { DofMID = 29, DofMNo = "30", IsChecked = false }); days31.Add(new Values { DofMID = 30, DofMNo = "31", IsChecked = false }); val.MonthInfo = month11; val.DayInfo = day6; val.DofMInfo = days31; ViewBag.lst = lst; ViewBag.lst2 = lst2; ViewBag.lst3 = lst3; return View(val); } [HttpPost] public ActionResult ScheduleInfo(Values model, int Job, string Second, string Minute, string Hour, object DayOfMonth, object Month, object DaysOfWeek)// int DayOfMonth) { var secondCon = Convert.ToInt32(Second); var minuteCon = Convert.ToInt32(Minute); var hourCon = Convert.ToInt32(Hour); model.Job = Job; model.Second = secondCon; model.Minute = minuteCon; model.Hour = hourCon; model.DayOfMonth = new List<object>(); model.Month= new List<object>(); model.DaysOfWeek = new List<object>(); foreach (var dofm in model.DofMInfo) { if (dofm.IsChecked) { model.DayOfMonth.Add(dofm.DofMID); } else if (dofm.IsChecked == false) { model.DayOfMonth.Add("?"); } } foreach (var month in model.MonthInfo) { if (month.IsChecked) { model.Month.Add(month.monthID); } else if(month.IsChecked) { model.Month.Add("*"); } } foreach (var day in model.DayInfo) { if (day.IsChecked) { model.DaysOfWeek.Add(day.dayID); } else if (day.IsChecked== false) { model.DaysOfWeek.Add("?"); } } return RedirectToAction("SchedulerIndex"); } } What I meant by checked not working is this: <script> let checkboxDofMElements = document.getQuerySelectorAll('.checkboxDofM'); for(let i = 0; i < checkboxDofMElements.length; i++) { checkboxDofMElements[i].addEventListener('change', function(event) { if(this.checked) { console.log("Something has changed"); } else { console.log("nothing has changed"); } }); } </script> When I add the script above, it should return "something has changed". Instead it returns the "nothing has changed" message. Like this A: Instead of document.getQuerySelectorAll('.checkboxDofM') you most use Element.querySelectorAll() And instead of using this.checked you can use event.target.checked Code example: const checkboxDofMElements = document.querySelectorAll('.checkboxDofM'); checkboxDofMElements.forEach(el => el.addEventListener('change', event => { const str = event.target.checked ? 'Something has changed' : 'nothing has changed'; console.log(`${str} for day ${event.target.value}`); })); <input type="checkbox" name="day" value="1" class="checkboxDofM"> 1<br> <input type="checkbox" name="day" value="2" class="checkboxDofM"> 2<br>
{ "pile_set_name": "StackExchange" }
Q: trimming the string I have java String of say length 10 .Now i want to reduce it to lenthg of 5 .Is there something i can do like we do in C as shown below str[6] = '\0' ; //insert null at 6th place so remaining string is ignored. I dont want to use inbuilt API of java to do this.The main problem that i wanted to solve is i wanted to remove duplicate characters in string .Now after removing duplicate characters string size is reduced so i want to remove remaining 5 characters. A: Strings in Java are immutable, as such you cannot modify the string but have to create a new one. As you cannot get your fingers on the underlying char[] of the String either, the only way to achieve your goal is using the API methods: String s = "blah blah blah"; s = s.substring(0, 5);
{ "pile_set_name": "StackExchange" }
Q: Can I change the theme name in WordPress? How can I change the theme name in WordPress and where? Can I also change the folder name theme1244 in public/wp-content/themes/theme1244 without having problems in the future? A: Step 1: Firstly go to wp-content/themes/ folder. And then rename your theme folder to whatever you want. Step 2: Open your theme folder and open style.css file. In top part of style.css you will see theme name. Rename it and save changes. Step 3: Go to Wp-admin/appearance/themes and activate your theme under new name. If you are using child/parent theme and you also rename parent theme folder&name, so after Step 3 you should additionally change parent theme path in child theme’s style.css. note : renaming your theme will stop its automatic updates, you should do it manually in the future. A: You can absolutely change the name of the folder without having any problems. If you want to change just the themes name, open the style.css in the root folder of your theme and edit the name in the comments at the top of the file. If you plan on doing more changes, you might be better off creating a child theme: https://codex.wordpress.org/Child_Themes A: All the above is correct, but is not enough. After you rename the theme, e.g. rename the folder old-theme --> new-theme, you should copy the theme customizations (colors, header / footer, widgets, etc.) from the old theme to the new theme. This is done directly in the MySQL database: Find an option named theme_mods_old-theme in the table wp_options Copy the option_value (it is a text holding the theme customizations in a special WordPress format) Put the copied value in a new option named theme_mods_new-theme in the wp_options table.
{ "pile_set_name": "StackExchange" }
Q: Dealing with bully/rogue consular official My wife and will be traveling to Italy for vacations and she is from a country that requires a visa. This is usually not a problem, as she has obtained travel visas to several other countries including the US and Ireland. However, we are running into problems that we now believe are due to a rogue immigrations official at the Italian Consulate in Buenos Aires, who is willfully disregarding EU law. She had originally approached the consular official with the typical proof of funds, proof of accommodation, and international insurance. He denied her based on the format of her proof of funds (which had been prepared by her accountant in a similar way to those that had been accepted in all other countries). Then we realized that different rules apply to her since she is the wife of an Irish national (me). She only needs to show my passport and an apostilled marriage certificate. She returned with this and still he claimed that he required proof of funds. She returned again with printed EU law clarifying that he was not allowed to request those documents, and he then looked at my passport and our marriage certificate and noticed that my name has a small modification (one middle name on the marriage cert and 2 on my Irish passport). This is a common problem since I have two passports (USA and Irish). My USA only has one middle name (my parents claimed that there was only space for one when they got my passport a long time ago). This has trickled down to my current ID (in Argentina) and marriage certificate. The official said he couldn't accept this (even though I was in the room and showed him both passports). The Irish embassy said this was a common problem and wrote a letter in official Irish Consular letterhead that certified the equivalence of the names. And once again the Italian official denied it saying it was "meaningless." There is plenty of EU law that supports the right of a citizen to travel freely with his family and guard against "divergent administrative practices". On the other hand, I have no idea how to defend myself when these practices are violated. This has been going on for a month and a half, and we're now very close to canceling a family vacation (non-refundable) due to a single consular official! Any advice? A: I don't have a great solution for you, but here are some options, too long for a comment: There's SOLVIT. I suspect that the timeframe of 10 weeks may be longer than you have, but they may be able to resolve the question more quickly than that. (Furthermore, I am unfamiliar with EU law on divergent administrative practices, but the free-movement directive does not establish standards for the evaluation of family relationships. That implies that this is left to national law, so it may be difficult to challenge the officer's recognition of your documents except within the Italian system. Still, it can't hurt to try the easier options first.) You could try another country's consulate. That could be difficult if you can't easily change your trip to make that country your "main destination." If Ireland registers foreign marriages, you might be able to get them to register your marriage with your Irish name, which might help, but that's a lot of ifs. In particular, it does not appear at first glance that Ireland registers foreign marriages. You can also of course try to apply for a regular Schengen visa, submitting appropriate financial proofs that are acceptable to the consulate. The consular officer will gloat, but if that is the price for not having to cancel your vacation then it may be worth humbling yourself just to get through it and get your wife on the plane. In the longer term, you should be able to get your US passport corrected. Even though there's only a single spot on the application for "middle name," it should be possible to put two words there. I would also look into the possibility of getting the marriage certificate changed or amended; whether that will be possible will depend on the law of the place where you were married, which you haven't identified.
{ "pile_set_name": "StackExchange" }
Q: CreateUserWizard - Preventing user creation if confirmation email cannot be sent I am trying to fix the behavior of a CreateUserWizard control in ASP.NET 2.0. With a fairly naive, out-of-the-box implementation, if you enter an email address that does not exist, or there is some other error sending the email, you get a YSOD showing the ugly details of the SMTP error, plus the user account is created anyway. Handling the SendMailError does not seem to help, as it is fired after the user is already created. Ideally, an email error would cause an "invalid email address" error message (or something to that effect) to be displayed. Seems like this should be pretty easy, but after quite a bit of looking around I haven't found an answer. Anybody have any solutions? A: This is what I do. It's not perfect, but it helps. protected void CreateUserWizard1_SendMailError(object sender, SendMailErrorEventArgs e) { // e.Exception can be one of the exceptions generated from SmtpClient.Send(MailMessage) if (e.Exception is SmtpFailedRecipientException) { // The message could not be delivered to one or more of the recipients in To, CC, or BCC()()(). // TODO: Set an error message on the page e.Handled = true; // Since the user has already been created at this point, we need to remove them. Membership.DeleteUser(CreateUserWizard1.UserName); // Set an internal flag for use in the ActiveStepChanged event. emailFailed = true; return; } } protected void CreateUserWizard1_ActiveStepChanged(object sender, EventArgs e) { if (CreateUserWizard1.ActiveStep != CreateUserWizard1.CompleteStep) return; if (emailFailed) { // If the email failed, keep the user on the first step. CreateUserWizard1.ActiveStepIndex = 0; return; } }
{ "pile_set_name": "StackExchange" }
Q: Rendering as plain text I am using the react wrapper with the latest version of tabulator. All styles seem to be missing, so everything is rendering as concatenated plain text. Is there a step I'm missing other than what is in the quick start? Thanks A: You may have missed to include the css imports! import 'react-tabulator/lib/styles.css'; // required styles import 'react-tabulator/lib/css/tabulator.min.css'; // theme Hope this helps
{ "pile_set_name": "StackExchange" }
Q: How to place an icon at the center of the screen on Qt Symbian? How can I place an icon at the center of screen on Qt Symbian? At the moment I'm using the following: p3->setGeometry(QRectF(236.0, 236.0, 64.0, 64.0)); But what I need is for the icon to be automatically set to the center of the screen. A: Use QDesktopWidget to get screen geometry (don't be scared by its name ^^). //Sample code QRect screen = qApp->desktop()->screenGeometry(); int iconSize = 64; p3->setGeometry(QRectF(screen.width()/2 - iconSize/2, screen.height()/2 - iconSize/2, iconSize, iconSize));
{ "pile_set_name": "StackExchange" }
Q: Easiest way to assign text content element to XmlNode[] 'Any' property from bound class? Given this: class foo { public XmlNode[] Any { get;set;} } What's the easiest way to do this: foo f = new foo(); f.Any = "some text content"; The above sample is an simplification, the actual class is a bound class generated by XSD.exe with an xs:any element. A: This is one approach: foo f = new foo(); f.Any = new XmlNode[] { new XmlDocument().CreateTextNode("some text content") }; This seems to be the simplest method I can find.
{ "pile_set_name": "StackExchange" }
Q: MVC Individual User Accounts login value persisting I have an MVC website that uses ASP.NET Identity. This site can be used for multiple customers data, and each customer is independent to another, no data should be shared. Each transaction should happen only on that customers data when that Customer is selected. However, the Users who log in can see All customers, they just choose at login which customer to transact against. So upon login, they will pick from a Dropdown their customer, and then see all that customers items, individual information, and unique things that can be done for that customer. So for example var allItems = from a in db.Items where a.CustomerId = customerId select a; This customer Id can be got at login, as its what the User chose from a dropdown. However, how do I persist this choice throughout the entirety of the users log in session? I obviously don't want to save it to the database as its not a permanent choice I want the choice to be gone when they log out, with them to be free to choose another Customer next login. Another cool thing would be able to override the get method in the DbContext to retreive only items matching whatever customer Id was selected on login public DbSet<Item> ItemsAll { get; set; } public IQueryable<Item> Items { get { return ItemsAll.Where(x => x.Customer == myLoggedInCustomerChoice); } } A: Add the value to a Session-variable, and check against it when you load pages.
{ "pile_set_name": "StackExchange" }
Q: Simple cURL via Applescript / Shell I want to send a simple cUrl in Applescript/shell URL: http://10.0.1.14/api/newdeveloper/lights/2/state Boddy: {"on":false} Method: Put Anyone can maybe help maybe? A: Make all the below lines into a single one, and then execute. curl -X PUT -d "{\"on\":false}" -H "Content-Type: application/json" "http://10.0.1.14/api/newdeveloper/lights/2/state"
{ "pile_set_name": "StackExchange" }
Q: How can I get an index value from A to Z using data-ng-repeat? I have been using before the index value like this: {{ $index }} What I really need is instead of getting a number I would like to get an uppercase character going from A to Z. There should be no problem of running out of characters as I have at the most only 10 things that are repeated. Can someone tell me how I can do this? A: Add the following method to your scope: $scope.indexChar = function (index) { return String.fromCharCode(65 + index); }; Then use it in your view: {{ indexChar($index) }} Here's the fiddle: http://jsfiddle.net/Xs5Qn/ A: You could use the function String.fromCharCode(n), wrapped in a filter: angular.module('myApp').filter('fromCharCode', function() { return function(input) { return String.fromCharCode(input); }; }); In the template you can call it like this: {{($index + 65) | fromCharCode}} // 65 is the letter A Edit: you could also create a more specific filter that returns only uppercase letters: angular.module('myApp').filter('letterFromCode', function() { return function(input) { var code = input % 26; return String.fromCharCode(65 + code); }; });
{ "pile_set_name": "StackExchange" }
Q: The following html anchor tag for twitter The following anchor tag <a href="http://twitter.com/share" class="twitter-share-button external" data-text="check out ___ on MySite!" data-count="none" data-via="MySite">tweet</a> I am wondering if special .js file needed? I mean, how does the browser know date-text, data-count fields? those are not standard, browser probably won't know that they mean. But I seearch the whole file and couldn't find any reference to any .js file that relate to the twitter sharing. A: Check out the Tweet Button Docs. You need to add the following line somewhere in your page for that special anchor to function: <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
{ "pile_set_name": "StackExchange" }
Q: AJAX Request on change function with jQuery/Rails I'm trying to get a rails partial when a select input value changes. The goal is to populate the empty select input with options that are located in a partial. Right now, console is saying GET http://localhost:3000/occupation 404 (Not Found) HTML <select class="occupation-primary"> <option value="1">Occupation 1</option> <option value="2">Occupation 2</option> </select> <select id="occupation-secondary"> </select> JS $('.occupation-primary').change(function() { $.ajax({ url: "occupation", type: "GET", }) }); questionnaires_controller.rb def occupation respond_to do |format| format.js end end questionnaires/occupation.js.erb $('#occupation-secondary').html("<%= escape_javascript(render(partial: 'questionnaires/options')).html_safe %>"); questionnaires/_options.html.erb <option value="1">Option 1</option> <option value="2">Option 2</option> routes.rb get "questionnaires/occupation" => "questionnaires#occupation", as: :occupation A: Change this in your routes rb, to bypass the "show" error: get "questionnaire/occupation" => "questionnaires#occupation", as: :occupation #skip the 's' And it will work without the "s" http://localhost:3000/questionnaire/occupation Otherwise, if your are using resources :questionnaires in routes rb, you need to say :except => :show resources :questionnaires, :except => :show Don't forget to change the url in the ajax call, to "questionnaire/occupation" or "questionnaires/occupation", depending on what you chose to do.
{ "pile_set_name": "StackExchange" }
Q: Run JS link file on just 1 web part I have a page with 2 web parts. the 2 web parts are the same list just imported in different views. i have added a JS link file to 1 of the web parts using the edit web part properties miscellaneous field. The problem is the js link file affects both web parts. where i only want it to affect 1 webpart. I know i can tick the server render option in the web part properties of the web part i don't want to be affected by the js link file, but i would like to be able to include this in my code instead. i have tried using the web part id in an if statement but i'm not sure where to put it. the web part id that i want to run the js link file is " DCE7572D-9439-479D-8DBA-F5AFCC3C67B9 ". can i do something like: if (ctx.view == '{DCE7572D-9439-479D-8DBA-F5AFCC3C67B9}') { //---Run JS Link file on this web part--- } For my jslink code i am running a template for an accordion list view. see code below. function () { // jQuery library is required in this sample // Fallback to loading jQuery from a CDN path if the local is unavailable (window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.0.min.js"><\/script>')); // Create object that have the context information about the field that we want to change it's output render var accordionContext = {}; accordionContext.Templates = {}; // Be careful when add the header for the template, because it's will break the default list view render accordionContext.Templates.Header = "<div class='accordion'>"; accordionContext.Templates.Footer = "</div>"; // Add OnPostRender event handler to add accordion click events and style accordionContext.OnPostRender = accordionOnPostRender; // This line of code tell TemplateManager that we want to change all HTML for item row render accordionContext.Templates.Item = accordionTemplate; SPClientTemplates.TemplateManager.RegisterTemplateOverrides(accordionContext); })(); // This function provides the rendering logic function accordionTemplate(ctx) { var description = ctx.CurrentItem["Phone_Number"]; var viewID = ctx.view; // Return whole item html return "<h2>" + "phone number" + "</h2><p>" + description + viewID + "</p><br/>"; } function accordionOnPostRender() { // Register event to collapse and uncollapse when click on accordion header $('.accordion h2').click(function () { $(this).next().slideToggle(); }).next().hide(); $('.accordion h2').css('cursor', 'pointer'); } A: This is where CSR flaws and most likely a reason why it is no longer available in modern SharePoint developments. CSR is bound to internal fieldnames, not scoped, so if anyone adds that field to a page it gets processed by CSR. (this also has a benefit... you do not have to use JSLink, can define CSR transformations in one global UserCustomAction ScriptLink) You have to do the hardcoded ViewID check inside every function and code the default return (for other Views you want that OOTB rendering) as well
{ "pile_set_name": "StackExchange" }
Q: How would I stagger text around an uneven background image? Often as a Web Producer I get a lovely mock-up with text wrapping around an obvious background image. The content is going to come from a backend CMS and I don't want the editorial staff to worry about inserting <br /> tags etc. Lorem ipsum dolor sit amet, consectetuer adiping elit, xxxxxxxxxxxxxx sed diam nonummy nibh euismod tincidunt ut lao xxxxxxxxxxxxxxxxxx dolore magna aliquam erat volutpat. Ut wisi xxxxxxxxxxxxxxxxxxxxxxxxx enim ad minim veniam, quis nostrud exerci xxxxxxxxxxxxxxxxxxxxxxxxxxx tation ullamcorper suscipit lobortis xxxxxxxxxxxxxxxxxxxxxxxxxxxxx ut aliquip ex ea commodo consequat. xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Duis autem vel eum iriure dolor in xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx hendrerit in vulputate velit esse xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx molestie consequat, vel illum xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Does anyone know of a solution to make this kind of thing automated via script, css? A: A List Apart did an article on this a while back. It's not totally turn-key, but they show you how to do it in PHP without too much trouble. A: If you absolutely had to do this browser-side and you wanted it to be as close to 'pixel perfect' as possible (in terms of specifying things like an exact margin around the image's shape), you'll probably need to use the <canvas> feature of HTML 5. With it, you would then need to do some "basic" image processing: this example is for an image that is to the right of the text, like your example Run an edge-detection algorithm on the image (probably the Sobel algorithm, because of it's simplicity and speed) to find the borders. Alternatively, if you can guarantee that the image will have a solid background, you could opt to simply threshold the image against that background color to obtain a segmentation of the image's subject from the background. Given your line-height, iterate through the rows of the image to find the max distance from the image's border to the start of the image's subject (the part we segmented) for each line of text that will border the image. Take that maximum value and subtract it from the total width of the image to obtain the amount of distance from the right side of the image. Push this width onto an array arr. At the start of the DOM node that contains your text, add arr.length <div> nodes, each of which would have style="height: [your text's line-height]; width: [value of arr at current element]; margin-left: [desired margin]; float: right; clear: right" Edit I wrote up a jQuery plugin for this technique, you can find it on plugins.jquery.com or at it's home page at http://jwf.us/projects/jQSlickWrap
{ "pile_set_name": "StackExchange" }
Q: How to position image above other image on mouseover? I tried to find any solution but I coudn't find. I have some images that each one is on the other.I want that when I mouseover the first image the images that behnd will be above the first image. For example: Normal: Mouseover: In the basic the second and the third image is behind the first image. Sorry for my english and thanks in advance! A: This solution requires the boxes to be absolutely positioned and in a container. var prop = "bottom", moveAmount = 50; $('.container').hover( function() { var moved = $(this).find(".box"); for (var i = (moved.length - 1), pad = 0; i >= 0; i--) { $(moved[i]).css(prop, (pad++ * moveAmount) + "px"); } }, function() { var moved = $(this).find(".box"); for (var i = 0; i < moved.length; i++) { $(moved[i]).css(prop, "0px"); } } ); .container { background-color: #eeeeee; position: relative; width: 45px; height: 45px; } .box { background: red; width: 40px; height: 40px; transition: bottom 0.3s ease-in-out; position: absolute; bottom: 0px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <br><br><br><br><br><br> <div class="container"> <div class="box">3</div> <div class="box">2</div> <div class="box">1</div> </div>
{ "pile_set_name": "StackExchange" }
Q: not declared in this scope I'm getting an error msg DataReader.h:13: error: 'String' was not declared in this scope DataReader.cpp:5: error: redefinition of 'std::vector<Data*, std::allocator<Data*> > DataReader' DataReader.h:13: error: 'std::vector<Data*, std::allocator<Data*> > DataReader' previously declared here DataReader.cpp:5: error: 'String' was not declared in this scope this is my cpp file #include "DataReader.h" using namespace std; vector<Data*> DataReader(String textFile) //line 5 that's giving error {........} and this my header file #include <fstream> #include <iostream> #include <vector> #include <string> #ifndef DATA_H #define DATA_H #include "Data.h" #endif std::vector<Data*> DataReader(String something); they work fine when i take out the string parameter and hard code the name of the string. but i need to use this function several times and would like to be able to pass in a string as a parameter. the string that i'm passing is name of a text file. am i mistaken somewhere? i can't seem to figure it out.. i mean what does it mean 'String' was not declared in this scope?? I am passing it and I included . something wrong with my parameter?? if you can shed some light to this matter, it would be greatly appreciated.. Dean A: string should be lower case or std::string A: Change String to string.
{ "pile_set_name": "StackExchange" }
Q: Can I use 2uF or 10uF capacitor instead of a 1uF with the LP2951 voltage regulator? I want to learn to program and use microcontrollers, and therefore I'm setting up a small power supply. The voltage regulator I've selected says I need a 1uF capacitor at the input pin. So my question is, is this the exact value I need or is it the minimum? Can I use a 2uF or even a 10uF capacitor instead? I'm planning on using a 9V battery as the power source. EDIT: The voltage regulator is the LP2951. See page 15 and down. However, I've been looking around a little more, and I wondered if I can use this regulator instead? http://www.digikey.com/scripts/DkSearch/dksus.dll?Detail&itemSeq=156827308&uq=635456207616008876 Does it matter that its 800 mA instead of 100 mA on the Texas Instruments Regulator? A: Yes, you can use a bigger capacitor on the regulator input (and typically anywhere that they're used to smooth out supply voltage spikes or ripples). And you can use regulators rated for higher currents; that's the maximum it's capable of but it won't push in more current than what the circuit consumes.
{ "pile_set_name": "StackExchange" }
Q: And operator in Hibernate (lucene) search I am using the following code for search using hibernate-search. But this tokenizes the search query and does an OR search, whereas I want to do an AND search. How do I do that? FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em); String searchQuery = "test query"; QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Customer.class).get(); TermMatchingContext onFields = qb.keyword().onFields("customer.name","customer.shortDescription","customer.longDescription"); org.apache.lucene.search.Query query = onFields.matching(searchQuery).createQuery(); FullTextQuery persistenceQuery = fullTextEntityManager.createFullTextQuery(query, Customer.class); List<Customization> result = persistenceQuery.getResultList(); A: The OR logic is the default for Lucene. You can use a boolean DSL query as described here - http://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#search-query-querydsl, however, that might not solve your problem yet, because you seem to have both query terms in a single string. Depending on your usecase (if for example the search string is provided by the user) it might be better to get the Lucene query from the Lucene query parser. A: FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em); QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Customer.class).get(); TermMatchingContext onFields = qb.keyword().onFields("customer.shortDescription", "customer.longDescription"); BooleanJunction<BooleanJunction> bool = qb.bool(); org.apache.lucene.search.Query query = null; String[] searchTerms = searchQuery.split("\\s+"); for (int j = 0; j < searchTerms.length; j++) { String currentTerm = searchTerms[j]; bool.must(onFields.matching(currentTerm).createQuery()); } query = bool.createQuery(); FullTextQuery persistenceQuery = fullTextEntityManager.createFullTextQuery(query, Customer.class); resultList = persistenceQuery.getResultList();
{ "pile_set_name": "StackExchange" }
Q: How to find a conformal mapping of the first quadrant. Find a conformal mapping of the first quadrant onto the unit disc mapping the points $1+i$ and $0$ onto the points $0$ and $i$ respectively. I think that i need to use "the change of variables $w=z^k$" but how? And why do we apply this? Please can someone explain thisstep by step? Thanks alot:) A: The composition of conformal maps is conformal, so to obtain a conformal map between two domains, we can - if it seems more simple - map the first domain conformally to a simpler intermediate domain, and then map that intermediate domain conformally to the target (perhaps with more intermediate steps). One needs to know some standard conformal maps of course. A well-known family of conformal maps are the Möbius transformations. These allow us to map any (open) haf-plane conformally to any (open) disk, mapping any prescribed point in the interior of the half-plane to the centre of the disk. Knowing that, we need a conformal map from the quadrant to a half-plane. The boundary of the quadrant has a vertex where the two straight half-lines making up the boundary meet at a right angle. The boundary of a half-plane has no vertex, in the plane, it is a straight line, in the sphere, a circle. So we need something that straightens the right angle of the boundary of the quadrant. Now one should remember that the power maps $z \mapsto z^k$ multiply angles at $0$ by $k$ - writing $z = \rho e^{i\varphi}$, we have $z^k = \rho^k e^{ik\varphi}$ - so to straighten the right angle at $0$ of the boundary of the quadrant, we need $k = 2$ (generally, to straighten an angle $\alpha$, we need the power $\pi/\alpha$ [which need not be an integer]). So the first part of our map is $$s \colon Q \to \mathbb{H};\quad z \mapsto z^2$$ that maps the first quadrant $Q = \{ x+iy \in \mathbb{C} : x > 0, y > 0\}$ conformally to the upper half-plane $\mathbb{H} = \{ z \in \mathbb{C} : \operatorname{Im} z > 0\}$. Then we need a conformal map $T \colon \mathbb{H} \to \mathbb{D}$ from the upper half-plane to the unit disk, that maps $s(1+i) = (1+i)^2 = 2i$ to $0$ and $s(0) = 0$ to $i$. A Möbius transformation mapping $2i$ to $0$ and the real line (the boundary of the upper half-plane) to the unit circle is $$T_0 \colon z \mapsto \frac{z-2i}{z+2i}.$$ That does not yet quite do what we want, since $T_0(0) = \frac{-2i}{2i} = -1$, so we compose it with a rotation that takes $-1$ to $i$, and that is multiplication by $-i$, so we get $$T\colon z \mapsto -i\frac{z-2i}{z+2i}$$ for our conformal map from the upper half-plane to the unit disk. Composing the two conformal maps, we get $f = T \circ s \colon Q \to \mathbb{D}$, given by $$f(z) = -i\frac{z^2-2i}{z^2+2i}.$$ (Note: That is the only map with the required properties; if $g \colon Q \to \mathbb{D}$ is conformal with $g(1+i) = 0$ and $g(0) = i$, then $g\circ f^{-1}$ is an automorphism of $\mathbb{D}$ that fixes $0$, hence a rotation, and also fixes $i$, hence the rotation must be the identity.)
{ "pile_set_name": "StackExchange" }
Q: In Django, is it Bad to Import and use Template Tags outside a Template? I'm using Django 1.9 and Django Rest Framework. In Django, there's a method named timesince() and it is used in a templatetag called humanize, in a method called 'naturaltime'. The natural time method returns what I want (a pretty formatted date). Timesince isn't that usable in an app. Anyway, I'm in a serializer.py file for DRF, and I imported that method with: from django.contrib.humanize.templatetags.humanize import naturaltime Since there's an annotation @register.filter at the top of the method and register = template.Library() at the top of the templatetag file, can it cause problems when I import that not from a template? A: No it shouldn't cause problems. You can use the function as a regular python function. The @register.filter is a decorator that decorates the function as a filter while register = template.Library() makes it usable as a template tag. However, it can also be called using the right signature in plain python code. So you can do: from django.contrib.humanize.templatetags.humanize import naturaltime from datetime import datetime as dt my_human_time = naturaltime(dt.now()) print(my_human_time) # 'now'
{ "pile_set_name": "StackExchange" }
Q: Long double 1.#QNAN Running the code below from Chapter 2 of "An Introduction to the C Programming Language and Software Design" by Tim Bailey works fine in C4Droid on Android but using CodeBlocks with the GCC compiler in Windows gives -1.#QNAN0e+000 for the upper limit of long double (LDBL_MAX). I understand that to mean "there's no such number", but presumably that means wrong coding and not "there's no limit" (I believe the correct answer is 1.797693e+308). So, possible reasons I've checked: Typo: I don't see it (and I've also selected LDBL_MAX from the CodeBlocks editor). Type mismatch: I don't think so (%e should be fine). LDBL_MAX not included in float.h: It is included. Any suggestions gratefully received #include <stdio.h> #include <limits.h> #include <float.h> int main (void) { printf("Integer range:\t\t%d\t%d\n", INT_MIN, INT_MAX); printf("Long range:\t\t%ld\t%ld\n", LONG_MIN, LONG_MAX); printf("Float range:\t\t%e\t%e\n", FLT_MIN, FLT_MAX); printf("Double range:\t\t%e\t%e\n", DBL_MIN, DBL_MAX); printf("Long double range:\t%e\t%e\n", LDBL_MIN, LDBL_MAX); printf("Float-Double epsilon:\t%e\t%e\n", FLT_EPSILON, DBL_EPSILON); } A: If you read e.g. this printf reference you will see that all floating points format without any modifiers (including plain "%e") is for the type double. If you want to print the value of a long double you need the L modifier prefix, as in "%Le". Mismatching format specifier and type leads to undefined behavior.
{ "pile_set_name": "StackExchange" }
Q: calculate percentage change between first and last row of each column in a matrix I would like to find a way to calculate the percentage change in the first and last row of each column in the matrix below. I have tried playing around with for loops and tail(df[i],1)/head(df[i],1) -1 but I can't seem to get it right. Apologize for the dummy question, but I have gotten pretty frustrated here.. df=matrix(c(3,9,3,4,3,9,3,5,3,8,8,8),4,3) df ### return list/vector of 3 elements where values are 4/3 -1, 5/3 -1, and 8/3 -1 ....the returns of the last over first A: Try with apply: > df <- matrix(c(3,9,3,4,3,9,3,5,3,8,8,8),4,3) > df [,1] [,2] [,3] [1,] 3 3 3 [2,] 9 9 8 [3,] 3 3 8 [4,] 4 5 8 > apply(df, 2, function(col) (col[nrow(df)]/col[1]) - 1) [1] 0.3333333 0.6666667 1.6666667
{ "pile_set_name": "StackExchange" }
Q: jquery add/remove styles/classes I have been trying to edit the jquery buttons in order to modify them one by one but the problem I seem to be having is that even when adding the class they seem to be getting overwritten. How can I remove a class and then add one? Classes: (one of these does default button style) .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default (one of these does hover on button) .ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus I can figure out which does what by trial and error unless someone knows right away, but whats going to be best way to remove the class and add my own? A: $(element).removeClass(classesToRemove).addClass(classesToAdd);
{ "pile_set_name": "StackExchange" }
Q: show a graph is not 2-choosable I want to prove that the following graph is not 2-choosable: If I let $\{1,2\}$ be the list at each vertex, then it is possible to colour the graph; you start with say 1, and then colour each vertex in clock-wise manner 2-1-2-1-2. So I've trying to use some variation in my lists. Say each list except for one is $\{1,2\}$, and the different list is $\{1,3\}$ or $\{2,3\}$, then wherever we place it, we are able to find a proper colouring. Now I've checked other possibilities too (though not each one), like e.g. when we have two lists that are different, and the rest is $\{1,2\}$. But now it's become senseless counting/checking. Is there a way for me to go about this smartly? There are too many possibilities to check by hand. The only theorem that came to mind is to look for a kernel-perfect orientation such that $1+d^+(x)=2$ for each vertex, but I didn't even manage to find an orientation with that property. I tried removing the middle vertical edge and finding a kernel-perfect orientation for the remaining cycle, but that's impossible if we want $1+d^+(x)=2$ for each vertex (because there are only two orientation possible; a clockwise and an anti-clockwise one, and these are not kernel-perfect). Apart form that, I have no idea how to proceed. A: Start by assigning the list $\{1,2\}$ to each of the two middle vertices. Then there are two ways to colour those two vertices: (I) give colour $1$ to the top middle vertex, colour $2$ to the bottom middle vertex; or (II) give colour $2$ to the top middle vertex, colour $1$ to the bottom middle vertex. Now the plan is to make something go wrong on the left side in case (I), and to make something else go wrong on the right side in case (II). In case (I), with the top middle vertex coloured $1$ and the bottom middle vertex coloured $2,$ we will get stuck on the left side if the upper left vertex has list $\{1,3\}$ and the lower left vertex has list $\{2,3\}.$ I leave case (II) as an exercise for the reader.
{ "pile_set_name": "StackExchange" }
Q: fixeddocument to pdf by pdfsharp 1.32 I want to save the fixeddocument to pdf file in wpf c#4.0, I use pdfsharp version 1.32,it has no Xps module, how can I transfer to pdf A: IIRC the latest PDFsharp version that included the XPS code was 1.31 (or was it 1.30?). Take the source code of PDFsharp 1.32 and copy the XPS code from the older version. This should require little or no changes.
{ "pile_set_name": "StackExchange" }
Q: How can I superpose an md-dialog on md-dialog I tried to open a md-dialog from an opened one ,but the problem is that the first md-dialog closed when the second opened // the controller of the first popUp class popUpOneController{ constructor($mdDialog){ this.$mdDialog=$mdDialog; . . . } others methods codes...... // the second $mdDialog to be opened from the first // this function will be executed by clicking on a html button openPopUp2(){ // here we call a component into the $mdDialog this.$mdDialog.show({ template: '<interlo-sibel data-to-pass='+data+' index-selectedElm='+index+' type='+type+' ></interlo-sibel>', targetEvent: event, escapeToClose: false }) } popUpOneController.$inject=['$mdDialog']; export default popUpOneController A: I found the answer , we have just add the following attiribute 'skipHide: true' openPopUp2(){ // here we call a component into the $mdDialog this.$mdDialog.show({ template: '<interlo-sibel data-to-pass='+data+' index-selectedElm='+index+' type='+type+' ></interlo-sibel>', targetEvent: event, skipHide: true }) } the demo link on plunker : https://plnkr.co/edit/jaDD79A1JII4XKhXP64Y?p=preview
{ "pile_set_name": "StackExchange" }
Q: Is there a limit to how many loops I can have in my code? This may be a really stupid question, but I feel the need to ask it. Is there any limit to how many e.g. if statements I can have in my code? At the moment I'm creating PHP pages for a website. One of the pages is integrating some database tables into the PHP code. I may have created it a bit stupid so now it's a lot of unnecessary work. My real question is, is there a limit to how many if statements I can have, if so, what limits it? I would guess the loading speed is slowed down if there is a lot to process? E.g: this is a bit of the code I use and this is copied like 50 times and then changed a bit for the specific table and row. <?php require_once('dbconn.php'); $sql = "SELECT week0_th_0 FROM training_week0"; $result = $conn->query($sql); ob_start(); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo $row["week0_th_0"]; } } else { echo "0 results"; } $echo_week0_th_0 = ob_get_clean();?> I'm wondering in code in general, thanks! A: No, there's no explicit limit, or really an implicit limit, from a PHP perspective. There's likely an implicit limit from a human factors / maintainability perspective. Often, if you find yourself repeating the same series of statements again and again, it's worthwhile to create a single reusable function with those statements in it that accepts parameters for things that vary from place to place you want to use it. A: There's no practical limit to the number of if statements. Since you're asking from a practical standpoint, I think that's the best answer for you. I'm sure there are limits around how much php can be read and run, but these limits are so massive you'll have problems reading and knowing what your code does way beforehand (for the academically curious I'm not too sure about php but I know java can handle methods up to about 64k lines, and there's no additional limits on if or for statements or anything like that). As far as speed is concerned, yes it's more code to be read and executed by a machine, but if statements have no practical effect (for the curious you can learn about something in computer science called big-O notation). To address a point a couple of people have commented in your question, copying an pasting code is usually a sign that you could use methods/functions to clean up a lot of that repetition.
{ "pile_set_name": "StackExchange" }
Q: How to disallow the copy constructor and use only move constructor? In following scenario ( its just a sscce ), how can I avoid copy constructor (the commented out code ) ? typedef boost::variant< std::vector<int>, std::vector<char>, std::vector<float> > VecRMPType; struct Widgets{ int widget_id; VecRMPType rmps_vec ; template< typename T> Widgets(int wid, T rmps_vec_ ) : widget_id(wid), rmps_vec( std::move(rmps_vec_) ) { } Widgets( const Widgets&& wids_ ) : widget_id( wids_.widget_id), rmps_vec(wids_.rmps_vec ) { } /* // This constructor I want to disable. Widgets( const Widgets& wids_ ): widget_id( wids_.widget_id), rmps_vec( std::move(wids_.rmps_vec) ) { } */ }; class Layers { int symb_id; std::vector< Widgets > widgets ; Layers(const Layers& ) ; Layers& operator=(const Layers& ) ; public: Layers(int sid_, std::vector<Widgets> wids_ ): symb_id(sid_), widgets(std::move(wids_) ) { } Layers(const Layers&& L_ ): symb_id(L_.symb_id), widgets( std::move(L_.widgets) ) { } }; Currently, compiler throws an error Am I missing something obvious or have any misconception(s) ? PS: I tried searching on related thing on SO, but still not able to find one, if its duplicate, please comment, and I'll delete the question. A: Move constructors usually look like: Foo(Foo&& other) You must also explicitly use std::move on the components. Then, delete the copy constructors: Foo(Foo const&) = delete; although simply omitting them is also acceptable if you have a user provided move constructor.
{ "pile_set_name": "StackExchange" }
Q: Disable option select javascript I Have a problem, I want to enable/show options, if that option has the same name with "ColumnCode" and "IsRow" is true. Other than that, the option is disabled/ hidden. I tried the code below, but it didn't work. var model = { Rows: $('#Rows') }; var columns = [{"ColumnCode":"CollateralType","IsRow":true}, {"ColumnCode":"CollectorUnit","IsRow":true}]; _.each(columns, function (col) { model.Rows.find('option').each(function () { if (this.value != col['ColumnCode'] || (this.value == col['ColumnCode'] && !col['IsRow'])) $(this).attr('disabled', true); }); }); This is the select element : <select name="Rows[]" id="Rows"> <option value="AccountNo">Account No</option> <option value="CollateralType">Collateral Type</option> </select> Can someone please guide? A: You should turn that loop inside out and iterate through the options first and then the array as otherwise your options will get constantly re-set or could end up all disabled all the time. You also might want to add a default option similar to <option value="none">...please select</option> value to ensure nothing is getting selected in case all are disabled. var model = { Rows: $('#Values') // had to change this from #Row for demo to work }; var columns = [ {"ColumnCode": "CollateralType", "IsRow": true}, // change this to see different results {"ColumnCode": "CollectorUnit", "IsRow": true} ]; // enable option if option has the same name as "ColumnCode" and "IsRow" is true model.Rows.find('option').each(function (index, option) { var matchFound = false; var isRow = false; _.each(columns, function (col) { if (option.value == col['ColumnCode']) { matchFound = true; isRow = col['IsRow'] return false; } }); if(matchFound && !isRow || !matchFound){ $(this).attr('disabled', true); //jQuery pre 1.6 //$(this).prop('disabled', true); // jQuery v1.6 or later } }); If you have this happening dynamically and need to reset all disabled attributes, simply do model.Rows.find('option').removeAttr('disabled') or if you are using jQuery 1.6 or later use model.Rows.find('option').prop('disabled', false) before you start the loops. DEMO - Only enable options which are in the list and have isRow set to true
{ "pile_set_name": "StackExchange" }
Q: Como desativar spring security Boa noite, estou aprendendo jsf, então acompanhei uns videos do Leandro Costa no youtube, achei bem didático e etc. No final do curso ele disponibiliza o código fonte, porém como o projeto usa spring security no login e ele não passou o script sql toda página que tento acessar dá o erro HTTP Status 403 - Access to the requested resource has been denied. Já tentei criar o banco manualmente, porém sem sucesso. Então cheguei a conclusão que é melhor tirar a autenticação pra poder usar a aplicação. spring-security.xml <b:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:b="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"> <http auto-config="true" use-expressions="true"> <intercept-url pattern="/login.faces" access="permitAll" /> <intercept-url pattern="/restrict/**" access="isAuthenticated()" /> <intercept-url pattern="/public/**" access="permitAll"/> <form-login login-page="/login.faces" authentication-failure-url="/login.faces?erro=true" default-target-url="/restrict/home.faces"/> <access-denied-handler error-page="/acessonegado.faces" /> </http> <!-- NO PROJETO SEMERU PADRÃO FIZEMOS DESSA FORMA --> <authentication-manager> <authentication-provider> <password-encoder hash="sha"/> <jdbc-user-service data-source-ref="dataSource" users-by-username-query="SELECT Login, Senha, 'true' as enable FROM pessoa WHERE Login=?" authorities-by-username-query="SELECT Login as username, Permissao as authority FROM pessoa WHERE Login=?"/> </authentication-provider> </authentication-manager> <b:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <b:property name="url" value="jdbc:mysql://localhost:3306/semeru_jsf_maven_db" /> <b:property name="driverClassName" value="com.mysql.jdbc.Driver" /> <b:property name="username" value="root" /> <b:property name="password" value="admin" /> </b:bean> Web.xml <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>semeru_jsf_maven</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> <!-- <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file>--> </welcome-file-list> <!-- Duração da sessão --> <session-config> <session-timeout> 30 </session-timeout> </session-config> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring-security.xml </param-value> </context-param> <!-- Configurações do tema do PrimeFaces --> <context-param> <param-name>primefaces.THEME</param-name> <param-value>sam</param-value> </context-param> <!-- Filtros do Spring --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> <dispatcher>FORWARD</dispatcher> <dispatcher>REQUEST</dispatcher> </filter-mapping> <!-- Configurações do JavaServer Faces --> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.faces</url-pattern> </servlet-mapping> <security-constraint> <display-name>Bloqueia o browser de acessar arquivos xhtml</display-name> <web-resource-collection> <web-resource-name>xhtml files</web-resource-name> <url-pattern>*.xhtml</url-pattern> </web-resource-collection> <auth-constraint/> </security-constraint> <!-- Configurações do PrimeFaces --> <servlet> <servlet-name>Resource Servlet</servlet-name> <servlet-class>org.primefaces.resource.ResourceServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Resource Servlet</servlet-name> <url-pattern>/primefaces_resource/*</url-pattern> </servlet-mapping> A: comentei os trechos que ativam o spring security do seu web.xml tentando explicar o que cada trecho é responsável por fazer, é importante salientar, que embora o spring security vá ficar desativado com este web.xml, a aplicação pode estar utilizando este contexto em vários lugares e não funcionar corretamente. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>semeru_jsf_maven</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> <!-- <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file>--> </welcome-file-list> <!-- Duração da sessão --> <session-config> <session-timeout> 30 </session-timeout> </session-config> <!-- Este parâmetro refere-se ao contexto do Spring <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring-security.xml </param-value> </context-param> --> <!-- Configurações do tema do PrimeFaces --> <context-param> <param-name>primefaces.THEME</param-name> <param-value>sam</param-value> </context-param> <!-- Estes filtros são responsáveis por interceptar qualquer request e direcioná-lo para o Spring Filtros do Spring <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> <dispatcher>FORWARD</dispatcher> <dispatcher>REQUEST</dispatcher> </filter-mapping> --> <!-- Configurações do JavaServer Faces --> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.faces</url-pattern> </servlet-mapping> <!-- Aqui como explicado abaixo, é responsável por blqouear acesso ao xhtml caso o usuário não esteja autenticado <security-constraint> <display-name>Bloqueia o browser de acessar arquivos xhtml</display-name> <web-resource-collection> <web-resource-name>xhtml files</web-resource-name> <url-pattern>*.xhtml</url-pattern> </web-resource-collection> <auth-constraint/> </security-constraint> --> <!-- Configurações do PrimeFaces --> <servlet> <servlet-name>Resource Servlet</servlet-name> <servlet-class>org.primefaces.resource.ResourceServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Resource Servlet</servlet-name> <url-pattern>/primefaces_resource/*</url-pattern> </servlet-mapping> Espero ter ajudado.
{ "pile_set_name": "StackExchange" }
Q: Gunslinger Girl II Teatrino: Anime vs Manga I've heard from a lot of people that season 2 of the Gunslinger Girl anime adaptation is significantly more upbeat and brighter than the original, and loses the feeling of dark, morbid 'beauty', yet apparently, the second season follows the manga a lot closer. Does the corresponding parts of the manga also have a more cheerful feel? (I only watched the anime, didn't read the manga) A: Simple answer is no. I think so, because Many gitai (girls) died: Henrietta, Rico, Triela, Angelica, Beatrice, Silvia, ...
{ "pile_set_name": "StackExchange" }
Q: extraction of letters at even positions in strings? string extract(string scrambeledword){ unsigned int index; string output; string input= " "; for (index=0; index <= scrambeledword.length() ; index++); { if (index%2==0) { output+=input ; cout << output; } } return output;} I want to extract the even numbered indexed letters from the 40 letter long word inputted by users. does this make sense? i have not taken arrays yet and do not want to include them. A: Problems: 1. You have a ; after your for loop, the loop body is never run. 2. <= is wrong here since scrambeledword.length() is out of range. Use != or < instead. 3. You need to either assign something to input before adding it to output or get rid of it altogether. 4. As @Aconcagua pointed out, it is worth noting that I removed your declaration of index from the function scope and added it only to the for loop scope. If you also considered doing so, compiler would throw an error (since it'd be undeclared outside of the scope of for) and you'd be noted about the ; problem. Fixed version: string extract(const string &scrambeledword){ // copying strings is expensive // unsigned int index; // obsolete string output; // string input= " "; // obsolete for (size_t index = 0; index != scrambeledword.length(); ++index) // `<=` would be wrong since scrambeledword.length() is out of range { if (index % 2 == 0) { output += scrambeledword[index]; // cout << output; // obsolete. If you just want the characters, print scrambeledword[index] cout << scrambeledword[index]; } } cout << endl; // break the line for better readability return output; }
{ "pile_set_name": "StackExchange" }
Q: How to correctly find, monitor and handle deprecated method calls in Symfony? I have just updated a Symfony 2.7 project to 2.8. Now I am preparing to update the project to Symfony 3. The Profile shows, that a great number (over 1500) of deprecated methods/classes are used on each request. Of course I would like to solve these issues. However as far as I can tell, the deprecated code is uses by Symfony itself and not by my own code. Here is an example: ConfigCache::__toString() is deprecated since version 2.7 and will be removed in 3.0. Use the getPath() method instead. (4 times) ConfigCache::__toString() (called from AllowedMethodsRouterLoader.php at line 51) AllowedMethodsRouterLoader::getAllowedMethods() (called from AllowedMethodsRouterLoader.php at line 51) AllowedMethodsRouterLoader::getAllowedMethods() (called from AllowedMethodsListener.php at line 41) AllowedMethodsListener::onKernelResponse() call_user_func() (called from WrappedListener.php at line 61) WrappedListener::__invoke() call_user_func() (called from EventDispatcher.php at line 184) ...a lot more Twig calls... Twig_Template::displayWithErrorHandling() (called from Template.php at line 347) Twig_Template::display() (called from Template.php at line 358) Twig_Template::render() (called from TwigEngine.php at line 50) TwigEngine::render() (called from TwigEngine.php at line 72) TwigEngine::render() (called from TwigEngine.php at line 97) TwigEngine::renderResponse() (called from Controller.php at line 185) Controller::render() (called from RegistrationController.php at line 71) RegistrationController::registerAction() call_user_func_array() (called from HttpKernel.php at line 144) HttpKernel::handleRaw() (called from HttpKernel.php at line 64) HttpKernel::handle() (called from ContainerAwareHttpKernel.php at line 69) ContainerAwareHttpKernel::handle() (called from Kernel.php at line 185) Kernel::handle() (called from app_dev.php at line 37) Of course my own code also involved in this call stack: The RegistrationController handled the request and used a Twig template to render the page. However the code that uses the deprecated ConfigCache::__toString() method is from within the AllowedMethodsRouterLoader class, which is part of Symfony. Is there anything my code can do to avoid this deprecated code? I am quite surprised, that Symfony code itself uses deprecated code. It there any way to filter out these messages and only get notified about deprecations in my own code? A: You may be interested in the Deprecation Detector from Sensio Labs ( creator of Symfony ). Deprecation Detector on Github I used it quite a bit removing deprecated classes/methods in 2.8 preparing to move to 3.0. Was a great time saver. Highly recommended. I'd also recommend Symfony Upgrade Fixer to save even more time especially regarding form classes.
{ "pile_set_name": "StackExchange" }
Q: iPhone - Tweak the UINavigationController to show a UINavigationBar made into IB I've build a UINavigationBar into Interface Builder, and I have a NavigationController into my app. I'd like to make the one use the other to work. Just to manage the bar into IB and let the controller use it as its view (and adding by itself the Back button if needed), or in another way to do the same thing, let the NavBar use the navcontroller to adjust its display. Do you see a way to do this ? If not, I really don't see the use of the NavigationBar proposed into IB. A: If you create the view controller in IB, you can give it a navigation item (UINavigationItem), and put your buttons in there. If you only create the view in IB and the controller is the owner (you use initWithNibName:bundle:), then you will either have to create the items programatically or put a outlet named navigationItem in your custom controller and connect it to a navigation item in the nib.
{ "pile_set_name": "StackExchange" }
Q: Codename One - Notify something to the user every five minutes I need to notify something to the user every five minutes, regardless the app is running in foreground or background and regardless the user is using the smartphone or not. My first attempt was to use "UITimer" + "Display.getInstance().vibrate(10000)", but the vibrate method doesn't do anything in my Android smartphone. My next attempt was to the LocalNotification. Maybe the LocalNotification API documentation is not correct, because using 10 as time (like in the API example) produces a runtime exception (java.lang.IllegalArgumentException: Cannot schedule a notification to a past time). I guessed that the time is from the epoch, so I wrote the following code. The problem is that it's not working as I need, because it notifies the message to the user only when the user is using the smartphone. I mean that the notification sound is played only when the user is touching the smartphone after "at least" five minutes, but if the user is not touching the smartphone no sound is played. It seems that the app is waiting for the user interaction before launching the notification. To be more clear: I need something like an alarm clock that gets the user attention (with a sound and/or a vibration) every five minutes. Form hi = new Form("Five minutes alert", BoxLayout.y()); hi.add(new Label("Five minutes alert")); hi.show(); UITimer.timer(1000 * 60 * 5, true, () -> { long time = Calendar.getInstance().getTime().getTime() + 1000; LocalNotification ln = new LocalNotification(); ln.setId("LnMessage"); ln.setAlertTitle("Alert title"); ln.setAlertBody("Alert message"); ln.setAlertSound("/notification_sound_bell.mp3"); Display.getInstance().scheduleLocalNotification(ln, time, LocalNotification.REPEAT_NONE); }); A: The time is from System.currentTimeMillis() i.e. absolute time. But local notification will only work properly when the app is in the background not when it's in the foreground. Vibrate should work but might not have worked for your device if it's in complete mute mode.
{ "pile_set_name": "StackExchange" }
Q: CSS tiled, nested div multi-row centering alignment issue After having reviewed several existing questions, and attempting countless combinations, I cannot find a solution that addresses this particular centering issue. I have an outer div that contains a variable number of divs within (using AngularJS). I have several on a row, but on the next row if it contains less divs than a full row, I need those divs centered. (Extending the example below, if there were two boxes on the second row, those two boxes together should be centered on the three boxes above.) This image illustrates the issue: My current code is here: JSFiddle The CSS: .outerbox { background-color: lightblue; margin: 10px auto; width: 350px; position: relative; text-align: center; } .box { background-color: lightgreen; border-style: solid; border-color: black; border-width: 1px; margin: 2px; height: 100px; width: 100px; display: inline-block; float: left; } ... and the related HTML: <div ng-if="show" class="outerbox" ng-repeat="box in boxes"> <div class="box">{{box.name}}</div> </div> A: Here is a working fiddle. Get rid of float in .box Wrap .outer-box inside an .outerbox-container: <div class="outerbox-container"> <div ng-if="show" class="outerbox" ng-repeat="box in boxes"> <div class="box">{{box.name}}</div> </div> </div> Change the css accordingly: .outer-box { display: inline-block; width: 100px; //instead of 350px } .outerbox-container { width: 350px; text-align: center; }
{ "pile_set_name": "StackExchange" }
Q: try-catch error "Not covered by Flow" When I enable the Type Coverage, I get a warning that the error in the catch part of the try-catch is Not covered by Flow. If I try to put catch(err: Error) I get an Unexpected token: try { // do something that fails and throws an Error } catch(err) { console.error('Error: ', err.message, err.stack) } So my question is, is it possible to type check it? and if so, what is the best possible solution? I'm using FlowType 0.30.0. A: I'm guessing that you're using Nuclide and have the type coverage feature enabled. You can click the percentage in the status bar to enable/disable it. The "uncovered" message is not strictly speaking a Flow error. It just informs you that Flow doesn't know the type of something. In this case it's correct. There's no way to know statically what the exception type may be. In JS you can throw any type, so you don't actually know for sure that it's even an error instance. However it's also a benign message in this case. Personally I don't think that 100% coverage is necessarily a good goal. There are cases where it makes sense to have uncovered code, like this.
{ "pile_set_name": "StackExchange" }
Q: Do until condition in Azure logic App doesnt work as expected I have a logic app that used the Until action. The condition checks the status of an API call: "Wait_Until_Cube_Processing_is_finished_": { "actions": { "Get_Status_of_Model": { "inputs": { "authentication": { "audience": "https://*.asazure.windows.net", "clientId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx", "secret": "OxxxxxxxxxxxxzskHxxxxxxxxxxxxxutjODXxxxxxx=", "tenant": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "type": "ActiveDirectoryOAuth" }, "method": "GET", "uri": "https://northeurope.asazure.windows.net/servers/ServerName/models/modelName/refreshes/@{body('Filter_array')[0].refreshId}" }, "runAfter": {}, "type": "Http" } }, "expression": "@equals('status', 'succeeded')", "limit": { "timeout": "PT1H" }, "runAfter": { "Filter_array": [ "Succeeded" ] }, "type": "Until" } }, The API returns such a status: { "startTime": "2019-03-10T15:50:55.1278586Z", "type": "full", "status": "notStarted", "currentRefreshType": "full", "objects": [ { "table": "Table1", "partition": "Partition_03", "status": "notStarted" } ] } My condition is not working. It runs one hour, and after one hour goes in the next step. BUT my http request recieve after 20 minutes the following state: { "refreshId": "dbxxxxxx-exxx-xxxx-xxx-3xxxxxxdaxxx", "startTime": "2019-03-10T15:50:55.48", "endTime": "2019-03-10T16:14:56.267", "status": "succeeded" } Do you have any idea, why my Until action doesnt work? A: It's your condition expression problem. Your expression is "expression": "@equals('status', 'succeeded')". It means you compare string status with string succeeded, they will never be equal. That's why your loop always run into timeout PT1H . The timeout default value is PT1H,it's one hour. So you should get the request body , then compare the state in the body with succeeded. The flow would be like this: The response body is a array format, so if you want to get the state in my example, the expression is @body('HTTP_2')['properties']['state'] and below is my response body, you could refer to this expression.
{ "pile_set_name": "StackExchange" }
Q: Mathematica with MongoDB database I try connect mathematica with my database NOSQL mongoDB but I have problem with create collection. I have Mathematica 10.2 and I download driver .net version 2.2 from this website a link! I unpacking driver to : input : FileNameJoin[{$InstallationDirectory, "SystemFiles", "Links", "NETLink"}] output : "C:\\Mathematica\\SystemFiles\\Links\\NETLink" After unpacking zip folder to "C:\Mathematica\SystemFiles\Links\NETLink" I install this pack and I connect to database and try createCollection but i have problem this is my code with output: In[2]:= InstallNET[] Out[2]= LinkObject["C:\\Mathematica\\SystemFiles\\Links\\NETLink\\\InstallableNET.exe", 127, 4] In[13]:= conn = ConnectToMongoDB["localhost"] Out[13]= NETLink`Objects`NETObject$377462395502593 In[5]:= GetMongoServer[conn_] := Module[{}, conn@GetServer[]] In[6]:= createCollection[conn_, db_String, collectionname_String] := Module[{server, database}, server = GetMongoServer[conn]; database = server@GetDatabase[db]; database@CreateCollection[collectionname] ] In[8]:= createCollection[conn, "mydb", "test"] During evaluation of In[8]:= NET::nomethod: No public instance method named GetServer exists for the .NET type MongoDB.Driver.MongoClient. Out[8]= $Failed[GetDatabase["mydb"]][CreateCollection["test"]] I use MongoDB on Windows and I switch to mydb > use mydb switched to db mydb I have no idea what I'm doing wrong maybe some suggestions? I must use only mathematica because I write engineering work about database connections and I must to use java or .Net. Thank you for this link b.gatessucks but when I use database link in java I have problem this problem: In[1]:= << MongoDBLink` In[4]:= conn = OpenConnection[]; In[5]:= DatabaseNames[conn] Out[5]= {"local"} In[18]:= db = GetDatabase[conn, "local"] In[19]:= CollectionNames[db] Out[19]= {"name", "startup_log"} In[20]:= coll = GetCollection[db, "name"] In[21]:= InsertDocument[coll, {"a" -> #, "b" -> 2 #}] & /@ Range[5] Out[21]= {0, 0, 0, 0, 0} In[23]:= FindDocuments[coll] During evaluation of In[23]:= Java::excptn: A Java exception occurred: java.lang.UnsupportedClassVersionError: MongoDBLinkUtils : Unsupported major.minor version 52.0 at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source). During evaluation of In[23]:= LoadJavaClass::fail: Java failed to load class MongoDBLinkUtils. >> Out[23]= MongoDBLinkUtils`Iterate[JLink`Objects`vm1`\ JavaObject11819681379778561] A: Wolfram Language version 11.3 now has support for MongoDB. You can connect to a MongoDB database via MongoConnect. For example, connecting to a database running locally: In[1]:= Needs["MongoLink`"] client = MongoConnect[]; MongoGetDatabaseNames[client] Out[2]= {"Test", "admin"} A: If you want to bypass .NET and do something that I personally find more intuitive then run it all through the terminal. I'm running OS X 10.10 and have Mongo 3.2 installed. Create a document: json = ExportString[{"old mcdonald" -> {"pig" -> 2, "cow" -> 4}}, "JSON"] "{ \"old mcdonald\": { \"pig\": 2, \"cow\": 4 } }" Then add that document to your collection. Note that you do not have to create the collection ("farm") to begin with, it is automatically created. Ditto the database, called "example" in the code below: ReadList["!/usr/local/mongodb/bin/mongo example --eval 'db.farm.insert(" <> json <> ")'", String] (* {"MongoDB shell version: 3.2.0", "connecting to: example", "WriteResult({ \"nInserted\" : 1 })"} *) Now go to your Mongo shell and verify the new collection: I find this far less clunky than using the Java driver and associated functions (same applies to .NET)
{ "pile_set_name": "StackExchange" }
Q: Dynamically added views disappear on orientation in Android I have created the views to be added in dynamically to a layout from a button click, but when I rotate the device landscape, the views disappear. Could someone please look at my code and explain how to stop this from happening. Here is the code: public class TestContainerActivity extends Activity implements OnClickListener { LinearLayout containerLayout; Button testButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_container); testButton = (Button)findViewById(R.id.testContainerButton1); testButton.setOnClickListener(this); containerLayout = (LinearLayout)findViewById(R.id.testContainerLayout); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.test_container, menu); return true; } @Override public void onClick(View v) { // TODO Auto-generated method stub if(v==testButton){ createNewLayout(); } } public void createNewLayout(){ LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View addView = layoutInflater.inflate(R.layout.container, null); TextView textviewTest = (TextView)addView.findViewById(R.id.containerTextView4); textviewTest.setText("TextView"); containerLayout.addView(addView); } } A: Add this line in your manifest.xml Tags. android:configChanges="keyboardHidden|orientation|screenSize" This will avoid your activity from recreating on orientation change.
{ "pile_set_name": "StackExchange" }
Q: Plot dsolve solution of ODE in MATLAB with multiple constants involved Basic Goal: Solve & Plot the solution of an ODE D2f=a1*f+a0 where a1=k*H*H/c; a0=-H*H*tau0/c; c=0.1; k=1; H=1; tau0=1; I am using dsolve command to find the solution with the above mentioned values of constants. sol=dsolve('D2th=a1*th+a0','th(0)=0','th(1)=0','t'); Instead of getting a solution with assigned values of constants, I get the solution as: sol = (exp(a1^(1/2)*t)*(a0 - a0*exp(-a1^(1/2))))/(a1*(exp(a1^(1/2)) - exp(-a1^(1/2)))) - (exp(-a1^(1/2)*t)*(a0 - a0*exp(a1^(1/2))))/(a1*(exp(a1^(1/2)) - exp(-a1^(1/2)))) - a0/a1 I need MATLAB to automatically replace the values of constants (a1, a0, etc.,) and then solve the equation, so that the results show up in complete simplified form. Secondly, I want to plot the solution of above ODE as follows: t0=0; tf=1; N=100; h=(tf-t0)/N; t=t0+(0:N)'*h; plot(t,sol) I have tried plot(t,sol(t)) but nothing works fine. Summary of question: first solve the ODE by replacing the values of constant in solution, and then plot the solution with respect to a column vector t. A: The solution is a symbolic expression. What you need is substitution in symbolic expressions and plotting of symbolic expressions. A quick search on the Matlab website gives subs and ezplot as suitable functions. I fixed the code but please check the working of those two functions either on the web or in your Matlab. H=1; k=1; c=0.1; tau0=1; a1=k*H*H/c; a0=-H*H*tau0/c; sol=dsolve('D2th=a1*th+a0','th(0)=0','th(1)=0','t'); sol2 = subs(sol, [sym('a0'),sym('a1')], [a0, a1]); t0=0; tf=1; ezplot(sol2, [t0, tf]);
{ "pile_set_name": "StackExchange" }
Q: Unable to get random (doc) from a namespace I want to display random (doc) page for some namespace. The random function name I can get by: user=> (rand-nth (keys (ns-publics 'clojure.core))) unchecked-char When I try to pass this to (doc) I get this: user=> (doc (rand-nth (keys (ns-publics 'clojure.core)))) ClassCastException clojure.lang.PersistentList cannot be cast to clojure.lang.Symbol clojure.core/ns-resolve (core.clj:3883) I'm new to Clojure and I'm not sure how to deal with this... I tried to convert this into regexp and use (find-doc) but maybe there is a better way to do this... A: Explanation The problem here is that doc is a macro, not a function. You can verify this with the source macro in the repl. (source doc) ; (defmacro doc ; "Prints documentation for a var or special form given its name" ; {:added "1.0"} ; [name] ; (if-let [special-name ('{& fn catch try finally try} name)] ; (#'print-doc (#'special-doc special-name)) ; (cond ; (special-doc-map name) `(#'print-doc (#'special-doc '~name)) ; (resolve name) `(#'print-doc (meta (var ~name))) ; (find-ns name) `(#'print-doc (namespace-doc (find-ns '~name)))))) If you're new to Clojure (and lisps), you might not have encountered macros yet. As a devastatingly brief explanation, where functions operate on evaluated code, macros operate on unevaluated code - that is, source code itself. This means that when you type (doc (rand-nth (keys (ns-publics 'clojure.core)))) doc attempts to operate on the actual line of code - (rand-nth (keys (ns-publics 'clojure.core))) - rather than the evaluated result (the symbol this returns). Code being nothing more than a list in Clojure, this is why the error is telling you that a list can't be cast to a symbol. Solution So, what you really want to do is evaluate the code, then call doc on the result. We can do this by writing another macro which first evaluates the code you give it, then passes that to doc. (defmacro eval-doc [form] (let [resulting-symbol (eval form)] `(doc ~resulting-symbol))) You can pass eval-doc arbitrary forms and it will evaluate them before passing them to doc. Now we're good to go. (eval-doc (rand-nth (keys (ns-publics 'clojure.core)))) Edit: While the above works well enough in the repl, if you're using ahead ahead-of-time compilation, you'll find that it produces the same result every time. This is because the resulting-symbol in the let statement is produced during the compilation phase. Compiling once ahead of time means that this value is baked into the .jar. What we really want to do is push the evaluation of doc to runtime. So, let's rewrite eval-doc as a function. (defn eval-doc [sym] (eval `(doc ~sym))) Simple as that.
{ "pile_set_name": "StackExchange" }
Q: How to use INDEX() inside ARRAYFORMULA()? I am trying to use the INDEX() formula inside an ARRAYFORMULA(). As a simple (non-sense) example, with 4 elements in column A, I expected that the following array formula entered in B1 would display all four elements from A in column B: =ARRAYFORMULA(INDEX($A$1:$A$4,ROW($A$1:$A$4))) However, this only fills field B1 with a the value found in A1. When I enter =ARRAYFORMULA(ROW($A$1:$A$4)) in B1, then I do see all numbers 1 to 4 appear in column B. Why does my first array formula not expand similar like the second one does? A: The INDEX function is one that does not support "iteration" over an array if an array is used as one of its arguments. There is no documentation of this that I know of; it simply is what it is. So the second argument will always default to the first element of the array, which is ROW(A1). One clumsy workaround to achieve what you require relies on a second adjacent column existing next to the source data* (although it is unimportant what values are actually in that second column): =ArrayFormula(HLOOKUP(IF(ROW($A$1:$A$4);$A$1);$A$1:$B$4;ROW($A$1:$A$4);0)) or indeed something like: =ArrayFormula(HLOOKUP(IF({3;2;4;1};$A$1);$A$1:$B$4;{3;2;4;1};0)) edit 2015-06-09 * This is no longer a requirement in the newest version of Sheets; the second argument in the HLOOKUP can just be $A$1:$A$4.
{ "pile_set_name": "StackExchange" }
Q: Лихо: что первично? Есть такой сказочный персонаж Лихо Одноглазое. И слово "лихо" является синонимом слов "горе", "беда", "несчастье". А что первично: фольклорный персонаж или абстрактное понятие? Спасибо A: Интересно происхождение слов с корнем ЛИХ/ЛИШ. Исходным является греческий вариант со значением "остаток". Получалось, что лишний - это имеющий остаток, поэтому изобильный, хороший. И другой вариант: лишний - это являющийся остатком, поэтому несчастный, плохой. Отсюда лихой, удалой наездник и лихой враг. От лихой (плохой) образуются названия болезней - лишай, лихорадка. Глагол "лишить" имел первоначальное значение "забрать остаток". Частица "лишь" также имеет значение "лишнего остатка" - это сравнительная степень "лише".
{ "pile_set_name": "StackExchange" }
Q: UITableController in UINavigationController back to previous view / controller I have setup my app such that a UINavigationController manages a MKMapView followed by an UITableViewController. Now, I want to handle selections in the table such that once selected, the focus will go back to the mapview immediately, without having click on the standard back button on top. Should I add a segue here or what is the Apple way to handle this? A: [self.navigationController popViewControllerAnimated:YES]; This line of code causes the navigationController to navigate "back" to the previous view controller.
{ "pile_set_name": "StackExchange" }
Q: How to reset all values in a dictionary {"green": 0, "y3": 1, "m@tt": 0, "newaccount": 0, "egg": 0, "results": 0, "dan": 0, "Lewis": 0, "NewAccount2": 0, "testyear3": 1, "testyear6": 0, "NewAccount1": 0, "testyear4": 0, "testyear5": 0, "Matt1": 0, "swag": 1, "lewis": 1, "matt": 1, "notin": 0} this is the dictionary defined as 'completeddict'. What I want to do, is to change ALL values no matter what they are called to 0. However bear in mind that new account names will be added at any point as 'keys' so I cannot manually do "completeddict[green] = 0", "completeddict[lewis] = 0", etc etc. Is there any way to have python change ALL values within a dictionary back to 0? EDIT: Unfortunately I do not want to create a new dictionary - I want to keep it called 'completeddict' as the program needs to use the dictionary defined as 'completeddict' at many points in the program. A: Another option is to use .fromkeys(): fromkeys(seq[, value]) Create a new dictionary with keys from seq and values set to value. d = d.fromkeys(d, 0) Demo: >>> d = {"green": 0, "y3": 1, "m@tt": 0, "newaccount": 0, "egg": 0, "results": 0, "dan": 0, "Lewis": 0, "NewAccount2": 0, "testyear3": 1, "testyear6": 0, "NewAccount1": 0, "testyear4": 0, "testyear5": 0, "Matt1": 0, "swag": 1, "lewis": 1, "matt": 1, "notin": 0} >>> d.fromkeys(d, 0) {'newaccount': 0, 'swag': 0, 'notin': 0, 'NewAccount1': 0, 'Matt1': 0, 'testyear4': 0, 'Lewis': 0, 'dan': 0, 'matt': 0, 'results': 0, 'm@tt': 0, 'green': 0, 'testyear5': 0, 'lewis': 0, 'NewAccount2': 0, 'y3': 0, 'testyear3': 0, 'egg': 0, 'testyear6': 0} A: Sure, its pretty easy: newDict = {key: 0 for key in completeddict} This is dictionary comprehension and is equivalent to: newDict = {} for key in completeddict: newDict[key] = 0 These dict comprehensions were introduced in v2.7, so older vesions will need to use the expanded form. A: A form that will work in virtually any Python version is just use the dict constructor with a list comprehension or generator: >>> d={"green": 10, "y3": 11, "m@tt": 12, "newaccount": 22, "egg": 55, "results": 0, "dan": 0, "Lewis": 0, "NewAccount2": 0, "testyear3": 1, "testyear6": 0, "NewAccount1": 0, "testyear4": 0, "testyear5": 0, "Matt1": 0, "swag": 1, "lewis": 1, "matt": 1, "notin": 0} >>> d=dict((k, 0) for k in d) >>> d {'newaccount': 0, 'swag': 0, 'notin': 0, 'NewAccount1': 0, 'Matt1': 0, 'testyear4': 0, 'Lewis': 0, 'dan': 0, 'matt': 0, 'results': 0, 'm@tt': 0, 'green': 0, 'testyear5': 0, 'lewis': 0, 'NewAccount2': 0, 'y3': 0, 'testyear3': 0, 'egg': 0, 'testyear6': 0} Which you can then use with a mutable argument or some form of callable: >>> d=dict((k, list()) for k in d) Now each element of d is a new list (or whatever else mutable or not you would want to set the value portion of the tuple to be).
{ "pile_set_name": "StackExchange" }
Q: Plot grouped point data using only base R code I am doing an assignment in which I am only allowed to use base R, no packages. Here is some sample data: set.seed(1) variables <- paste0('V_', seq(1,16,1)) data <- data.frame(t(rbind(variables, rnorm(16,0,1),rnorm(16,0,1), rnorm(16,0,1)))) colnames(data) <- c('variables','OLS', 'IV', '2SLS')}'' I know how to do this on ggplot2, but not on base R. I would like to plot the value of each variable with points in a way that each type of model is color coded. On my x-axis we would have all factors, going from V_1 to V_16 (it would be nice if all labels in the axis where shown). Any suggestions, please? Thank you! A: set.seed(1) variables <- paste0('V_', seq(1,16,1)) data <- data.frame(t(rbind(variables, rnorm(16,0,1),rnorm(16,0,1), rnorm(16,0,1)))) colnames(data) <- c('variables','OLS', 'IV', '2SLS') attach(data) #> The following object is masked _by_ .GlobalEnv: #> variables variables <- factor(variables, levels = variables[order(as.numeric(gsub("V_","", variables)))]) plot.default(variables,as.double(OLS),type='p',xaxt='n', ylab="value", cex=1, col="red") points(x=variables, y=as.double(IV), col="blue") points(x=variables, y=as.double(`2SLS`), col="green") axis(side = 1, at = as.numeric(variables), labels = variables) detach(data) Created on 2019-06-19 by the reprex package (v0.3.0)
{ "pile_set_name": "StackExchange" }
Q: Initializing QColorDialog with Qt::black always returns black I am creating a QColorDialog using the static function like so: QColor c = QColorDialog::getColor(Qt::black); if (c.isValid()) { std::cout << c.red() << std::endl; std::cout << c.green() << std::endl; std::cout << c.blue() << std::endl; } If I now choose a color in the dialog and press OK, it always returns black (as in RGB(0, 0, 0)). Also the RGB values in the dialog are not updating. If I create the dialog like this: QColor c = QColorDialog::getColor(Qt::white); Everything works as expected. What am I doing wrong here? A: Your Value in the HSV is 0! Thats why all is black.
{ "pile_set_name": "StackExchange" }
Q: Printing with indentation in C Which way is the best for line up all the output on the right ? Example: for powers of 2: 2 4 8 16 32 64 128 256 512 1024 2048 ... 134217728 If my last number has N digits, how print the first one (which in this case has just one digit) with (N - 1) spaces on left ? A: You can supply a computed field width to printf() using *. So after you calculate the maximum number of digits, you can do: printf("%*d\n", max_digits, value);
{ "pile_set_name": "StackExchange" }
Q: How to use pca results for linear regression I have a data set of 11 variables with allot of observations for each one. I want to make linear regression on the variables with the observed $\vec{y}=\alpha +\beta*\vec{X}$ when X is matrix. I'm trying to reduce my parameters so I activate pca algorithm on X. I get the "loading" data but i don't understand how to use it to get only four (for example) variables to estimate instead of 11. somebody can help? A: Welcome to the site! So, the outcome which you get from PCA explain the most of your original dataset. You need to name them based on your business understanding(Assuming that you know about data, as you mentioned that you wanted to apply, Linear Regression) else you might need some Subject Matter Experts expertise. Of-course, the Features won't be same with the original data or else what is the point in performing PCA(I know that you understood this part). To decide on the number of features, you need to look at Scree Plot. PCA is a Dimensionality Reduction algorithm which helps you to derive new features based on the existing ones. PCA is an Unsupervised Learning Method, used when the has many features, when you don't understand anything about the data, no data dictionary etc.For better understanding on PCA you can go through this link-1,link-2. Now before performing Linear Regression, you need to check if these new features are explaining the Target Variable by applying Predictor Importance test(PI Test), you can go through the Feature Selection test in the python,R. Based on the outcome of PI Test you can go ahead and use those important feature for modeling and discarding the features which are not explaining the target variable well. Finally, you can achieve the results which you are looking for. Let me know if you are stuck somewhere.
{ "pile_set_name": "StackExchange" }
Q: How to remove open documents from the dock in Mac OS Catalina My dock in Mac OS Catalina shows icons for all open docs in my open apps (Finder, Word, Skim,...) If I right click on any of these apps and press "Hide" the doc icons disappear from the dock, but the moment I use the app again, they all reappear again. Is there any way to make the doc icons disappear completely. They are shown to the right of my apps in this screenshot: A: The behavior shown in the image in your OP is the normal default for macOS when application windows are minimized. If you do not want to see minimized windows in the Dock, then do the following: Go to System Preferences > Dock and check the     [√] Minimize windows into application icon checkbox. In Terminal run the following command: killall Dock This will restore all the application windows so they are not minimized to the Dock. Now you can minimize the application windows you do not want to currently see and they will minimize into the application's icon on the Dock, not the the normal default position as shown in the image in your OP. To then access a minimized window, when in the application, you can go to the Window menu on the menu bar, or either click-hold or right-click on the Application's Dock Tile and select the target window.
{ "pile_set_name": "StackExchange" }
Q: Bouldering vs aid climbing vs free climbing vs free solo climbing What re the differences between these 4 styles of rock climbing? Bouldering Aid Climbing Free Climbing Free solo climbing A: All of the above are styles of rock climbing. The differences/similarities are highlighted below: Bouldering Low-level climbing (usually up to about 3m) without the use of a rope. Falls are typically protected against by the use of large portable mats (bouldering mats). Concentrates on technically difficult short climbs. Usually (though not exclusively) performed on boulders, as opposed to cliff faces (hence the name). Aid Climbing Uses ropes. The rock itself is climbed utilising special ladder-like equipment called "aiders". Items of equipment are placed onto or into the rock face and an aider is attached. The climber then climbs the aider. Part of the climbing may be done using hands and feet, but at least some portions use aid. At least in Europe it is also called technical climbing. One of the earliest forms of rock climbing coming out of the alpinist movement of the 1930s. With enough effort practically everything can be climbed. Therefore countermovement of free climbing evolved in the 1970s. "Siege tactics" can be used. This can involve people taking months to climb difficult climbs, coming up and down at will (see the 1958 climb by Warren Harding and team to climb the 3,000 foot "Nose" of El Capitan in Yosemite) Free Climbing What most non-climbers think climbing is. Uses ropes. Climber climbs using hands and feet only. Using aid to climb on can be considered "cheating" and will degrade the climb to an aid climb. Gear is placed in the rock face to protect against falling only, but is not used to help the climber in gaining height. Free climbing may be trad or sport, single-pitch or multi-pitch. Free solo climbing Climbing without rope or protection whatsoever in height where a fall will most likely kill you. Falls can be fatal and no attempt is made to protect against falling and hitting the ground. Considered the most dangerous of all climbing styles. An Especially psychological variety of climbing.
{ "pile_set_name": "StackExchange" }
Q: Qt 5.4/QML: How do I correctly implement a custom C++ class as a global QML singleton instance and implement code for its signals (in QML)? I have a little C++ class that I want to register with QML so I can access it from QML code and provide a safe API for the QML developer - while keeping the complex stuff "under the hood" and hidden from the perspective of QML. So far I have written my custom class like this: main.cpp static QObject *myapi_singletontype_provider(QQmlEngine *engine, QJSEngine *scriptEngine) { Q_UNUSED(engine) Q_UNUSED(scriptEngine) MyApi *apiInstance = new MyApi(); return apiInstance; } int main(int argc, char *argv[]) { QApplication app(argc, argv); qmlRegisterSingletonType<MyApi>("com.example.myapi", 1, 0, "MyApi", myapi_singletontype_provider); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("http://server.com/myqml.qml"))); return app.exec(); } MyApi.h #ifndef MyApi_H #define MyApi_H #include <QObject> #include <QtNetwork> #include <QtCore/QDebug> #include <QtCore/QObjectList> class MyApi : public QObject { Q_OBJECT public: explicit MyApi(QObject *parent = 0); ~MyApi(); signals: void downloadStarted(const QString &uuid); void downloadFinished(const QString &uuid); void downloadError(const QString &uuid, const QString &errorText); void downloadProgress(const QString &uuid, const float progress); public slots: void downloadArchiveInBackground(const QString &uuid); }; #endif // MyApi_H MyApi.cpp #include "MyApi.h" void MyApi::downloadArchiveInBackground(const QString &uuid) { // I would like to connect these signals to JS methods in QML! emit downloadStarted(uuid); emit downloadProgress(uuid, 0.3); } QML (pseudo) MyApi { id: myapi onDownloadStarted: { console.log("OK STARTED") dialogDownload.open() } } Actually I have no idea how to implement this. I'm aware that I'm creating an instance here, and with Singletons that's not required since it's a singleton instance - but I need some pointers on how to implement the signal handlers in QML that I emit from C++. A: You can use Connection QML type. import com.example.myapi 1.0 Connections { target: MyApi onDownloadFinished: //do something }
{ "pile_set_name": "StackExchange" }
Q: How to make LUA script read my config file I want make lua script read custom config file personal.txt [user4] id=1234 code=9876 [user3] id=765 code=fh723 so i can read or write data A: You can use lua module to make your config: -- config.lua local _M = {} _M.user3 = { id = 765, code = "fh723", } _M.user4 = { id = 1234, code = "9876", } return _M Then you can require the module, and use the field in module table as you like: -- main.lua local config = require "config" print (config.user3.id) print (config.user3.code) print (config.user4.id) print (config.user4.code) -- Also you can edit the module table config.user4.id = 12345 print (config.user4.id) Output: 765 fh723 1234 9876 12345
{ "pile_set_name": "StackExchange" }
Q: "Without any problem" or "without any problems" What is the correct form: "Without any problem" or "Without any problems"? A: Either will do. It's actually pretty amazing just how interchangeably they're used: A: Any means one or more, which means that both options mentioned by you, are correct. A: Both are correct. You can use either one.
{ "pile_set_name": "StackExchange" }
Q: Use a generator within a while loop to blit text onto the screen I have a class that initializes a population of the same word in different variations then over time rearranges the letters into the desired word. In pygame I'm trying to have the current word be displayed onto the screen then change depending on what variation the class is on in real time. The problem I'm facing is being able to call the class and update the screen at the same time. I was told that I should use a generator and yield the variation and then enter back into the main loop, however this does not work since my Population class does all of the work within a while loop inside of it's __init__. How could I yield the current variation that I want to change the text being blit onto the screen within the main loop? code: class Population: def __init__(self, size): ... while variation.fitness < len(target): # unknown amount of variations self.selection() # restarts selection process ... pg.init() top = '' ... while not done: ... if event.key == pg.K_RETURN: Population(1000) top = # I want to make this variable be the current variation within Popualtion ... top_sentence = font.render((top), 1, pg.Color('blue')) screen.blit(top_sentence, (400,400)) A: Why do you continuously create a new Population object in the loop? It is a class, so you can add interfaces (methods) to communicate with the object and to commit and retrieve data. The statement self.selection() hast to be in a method of the class rather than the constructor. See the concept of Classes. Create a method (e.g. NextVariation) which does a single call to self.selection() rather than multiple "selections" in a loop. The method returns the current variation. The method doesn't need an inner loop, because it is called continuously in the main application loop: class Population: def __init__(self, size): self.size = size # [...] def SetTarget(self, target): self.target = target def NextVariation(self): if variation.fitness < len(self.target): # unknown amount of variations self.selection() # restarts selection process return variation # return current variation population = Population(1000) top = '' while not done: # [...] if event.key == pg.K_RETURN: population.SetTarget(...) top = population.NextVariation() # [...] top_sentence = font.render((top), 1, pg.Color('blue')) screen.blit(top_sentence, (400,400)) This can also be with an iterator that yields the variations, as demonstrated in the answer to your previous question - Update text in real time by calling two functions Pygame Note, alternatively it is even possible to create a new instance of the class when return is pressed. But it depends on your need if you need to create a new object, which restart to process, or if you just want to change a parameter of the process: population = Population(1000) top = '' while not done: # [...] if event.key == pg.K_RETURN: population = Population(...) top = population.NextVariation() # [...] top_sentence = font.render((top), 1, pg.Color('blue')) screen.blit(top_sentence, (400,400))
{ "pile_set_name": "StackExchange" }
Q: Laravel Authentication for multiple users I have 4 types of users in my application and details are stored in 4 different tables, so how can I implement Laravel's Authentication? Route::post('/adlogin', 'mainController@adminlogin'); Route::get('/sellerlogin', function () { return view('seller.pages.login'); }); Route::post('/sellerlog_in', 'mainController@sellerlogin'); A: Use this as your controller <?php namespace App\Http\Controllers\Auth; use Illuminate\Http\Request; use App\Http\Controllers\Controller; //Use Dependencies use Auth; class AdminLoginController extends Controller { Middleware used here is admin which you have to create in config/auth.php public function __construct() { $this->middleware('guest:admin', ['except'=>'logout']); } Create a view for your admin Login public function showLoginForm() { return view('auth.admin_login'); } public function login(Request $request) { //Validate the Form Data $this->validate($request, [ 'email'=>'required|email', 'password'=>'required|min:5' ]); //Attempt to log the Admin In $email= $request->email; $password= $request->password; $remember= $request->remember; After Successfully login where you want to redirect like here I am redirecting toadmin.dashboard //If Successful redirect to intended location if (Auth::guard('admin')->attempt(['email' => $email, 'password' => $password], $remember)) { return redirect()->intended(route('admin.dashboard')); } //If Unsuccessful redirect back to login form with form data return redirect()->back()->withInput($request->only('email', 'remember')); } /** * Log the Admin out of the application. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function logout() { Auth::guard('admin')->logout(); return redirect()->route('admin.login'); } } After logout redirect back to login page Make sure you are using right guard for right User. Create same functionality for more user types as you want create guards for them. In config/app.php 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], 'admin' => [ 'driver' => 'session', 'provider' => 'admins', ], 'admin-api' => [ 'driver' => 'token', 'provider' => 'admins', ], ], As admin and admin-api created here create for your user types Add providers 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\User::class, ], 'admins' => [ 'driver' => 'eloquent', 'model' => App\Admin::class, ], ], At last for resetting passwords use this. 'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_resets', 'expire' => 60, ], 'admins' => [ 'provider' => 'admins', 'table' => 'password_resets', 'expire' => 10, ], ], In http/middleware/redirectIfAuthenticated.php add this to your handle function //Check for admin login guard switch ($guard) { case 'admin': if (Auth::guard($guard)->check()) { return redirect()->route('admin.dashboard'); } break; default: if (Auth::guard($guard)->check()) { return redirect('/dashboard'); } break; } You can add more cases for your user types. This is all you want to create multi auth. As you created different table for different roles you have to follow this process. Create LoginController for all user types or use your logic to log them in. Add your guards for every user type in auth.php Add your cases to RedirectIfAuthenticated
{ "pile_set_name": "StackExchange" }
Q: Decay factor and volatility (2 assets): do you keep simple correlation to calculate vol? or exponentially weighted correlation? I have calculated exponentially weighted variances (and covariance) for a future and the underlying index. Now that I have exponentially weighted variances for my 2 assets using a lookback period of 1 year, and knowing that the portfolio of 2 assets volatility depends on the correlation between these 2 assets, do I need to use the simple correlation (simple returns with no decay) or do I need to use the correlation between the new exponentially weighted variances? A: From a theoretical point of view, you are supposed to use the correlation calculated under the same measure (i.e. multiplying daily excess returns and weighting that product by your weights). In practice, I have seen both approaches: Weighted correlations and weighted variances, i.e. a weighted covariance matrix, and a mixture: unweighted correlations with weighted variances. Again, the first approach is theoretically sound and should be preferred.
{ "pile_set_name": "StackExchange" }
Q: How can i define user detail view in multiuser blog app? I'm building a blog app with multi users and i'd like to have this ability that every logged user could click on every username (post author) and see details of this profile my current function gives me only details for current logged in user no mattew what user i click. i have similar CBV function working for post list view that shows me all the posts for each user and i've tried to do the same but it didn't worked.. Please help ;) view > @login_required def profile_detail(request): context = { 'profile': Profile.objects.all() } return render(request, 'users/user_detail.html', context) model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args,**kwargs): super().save(*args,**kwargs) img = Image.open(self.image.path) if img.height >300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) url pattern path('profile-detail/', user_views.profile_detail, name='user_detail'), link <a class="mr-2" href="{% url 'user_detail' %}">{{ post.author }}</a> A: Showing the profile of the logged in user You obtain the Profile object for the logged in user with: from django.shortcuts import get_object_or_404 @login_required def profile_detail(request): context = { 'profile': get_object_or_404(Profile, user=request.user) } return render(request, 'users/user_detail.html', context) Showing the profile of the author If you want to show the profile of the author, then you should pass it to the url. You thus can make a path that looks like: urlpatterns = [ # …, path('profile/<int:pk>', views.profile_detail, name='user_detail') # …, ] in your template, you can render the url with: <a class="mr-2" href="{% url 'user_detail' pk=post.author.pk %}">{{ post.author }}</a> and in the view, you can then use the primary key of that user: from django.shortcuts import get_object_or_404 @login_required def profile_detail(request, pk): context = { 'profile': get_object_or_404(Profile, pk=pk) } return render(request, 'users/user_detail.html', context)
{ "pile_set_name": "StackExchange" }
Q: Keras: How to feed input directly into other hidden layers of the neural net than the first? I have a question about using Keras to which I'm rather new. I'm using a convolutional neural net that feeds its results into a standard perceptron layer, which generates my output. This CNN is fed with a series of images. This is so far quite normal. Now I like to pass a short non-image input vector directly into the last perceptron layer without sending it through all the CNN layers. How can this be done in Keras? My code looks like this: # last CNN layer before perceptron layer model.add(Convolution2D(200, 2, 2, border_mode='same')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2))) model.add(Dropout(0.25)) # perceptron layer model.add(Flatten()) # here I like to add to the input from the CNN an additional vector directly model.add(Dense(1500, W_regularizer=l2(1e-3))) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(1)) Any answers are greatly appreciated, thanks! A: You didn't show which kind of model you us, but I assume that you initialized your model as Sequential. In a sequential model you can only stack one layer after another - so adding a "short-cut" connection is not possible. For this reason authors of Keras added option of building "graph" models. In this case you can build a graph (DAG) of your computations. It's a more complicated than designing a stack of layers, but still quite easy. Check the documentation site to look for more details. A: Provided your Keras's backend is Theano, you can do the following: import theano import numpy as np d = Dense(1500, W_regularizer=l2(1e-3), activation='relu') # I've joined activation and dense layers, based on assumption you might be interested in post-activation values model.add(d) model.add(Dropout(0.5)) model.add(Dense(1)) c = theano.function([d.get_input(train=False)], d.get_output(train=False)) layer_input_data = np.random.random((1,20000)).astype('float32') # refer to d.input_shape to get proper dimensions of layer's input, in my case it was (None, 20000) o = c(layer_input_data)
{ "pile_set_name": "StackExchange" }
Q: Unable to type a response in an tag Goal: I am trying to make a form for users to submit their school schedule Problem: the first of my input tags will not let me type an input. All the input sections are set up the same accept for their place holder text. they all follow the same pattern and have the same classes applied. Notes: I know you are able to type in the input field inside of the snippet but it does not work when implemented into my full webpage. Also I'm fairly new to HTML/CSS so excuse the fact that my code is kinda messy. Any constructive criticism is openly accepted. .form { width: 680px; height: 870px; } .inputConatiner { height: 75px; width: 680px; display: inline-block; float: left; } .textContainer { height: 75px; width: 405px; display: inline-block; } .submitContainer { width: 100%; height: 40px; position: relative; } .submit { height: 40px; width: 150px; display: inline-block; position: absolute; left: 50%; top: 2075%; margin: 0 0 0 -75px; } input[type="text"] { border: black 0px solid; border-radius: 20px; background-color: rgb(230, 230, 230); padding-top: 13px; padding-bottom: 13px; font-family: "Arial"; } input[type="radio"] { height: 30px; width: 30px; margin: 0; vertical-align: middle; } input[type="submit"] { height: 40px; width: 150px; border: black 0px solid; border-radius: 20px; } label[for="A"], label[for="B"] { display: inline-block; width: 160px; font-family: "Arial"; } fieldset { border: black 0px solid; padding: 0px; } .label { width: 270px; height: 40px; font-family: "Nunito Sans"; font-size: 30px; display: inline-block; background-color: rgb(104, 255, 144); border-radius: 20px; text-align: center; vertical-align: middle; } input { width: 200px; } <head> <title>Side Project</title> <link rel="stylesheet" type="text/css" href="css/styles.css"> <link href="https://fonts.googleapis.com/css?family=Nunito+Sans" rel="stylesheet"> </head> <div class="form"> <form method="post" action="#" name="getStudentInfo"> <div class="inputConatiner"> <h1 class="label">Enter Your Name</h1> <div class="textContainer"> <input type="text" placeholder="First" required /> <input type="text" placeholder="Last" required /> </div> </div> <div class="inputConatiner"> <h1 class="label">1A Class</h1> <div class="textContainer"> <input type="text" placeholder="Class" required /> <input type="text" placeholder="Teacher" required /> </div> </div> <div class="inputConatiner"> <h1 class="label">2A Class</h1> <div class="textContainer"> <input type="text" placeholder="Class" required /> <input type="text" placeholder="Teacher" required /> </div> </div> <div class="inputConatiner"> <h1 class="label">3A Class</h1> <div class="textContainer"> <input type="text" placeholder="Class" required /> <input type="text" placeholder="Teacher" required /> </div> </div> <div class="inputConatiner"> <h1 class="label">4A Class</h1> <div class="textContainer"> <input type="text" placeholder="Class" required /> <input type="text" placeholder="Teacher" required /> </div> </div> <div class="inputConatiner"> <h1 class="label">A Day Lunch</h1> <input type="radio" id="A" name="lunchADay" /> <label for="A">First Lunch</label> <input type="radio" id="B" name="lunchADay" /> <label for="B">Second Lunch</label> </div> <div class="inputConatiner"> <h1 class="label">1B Class</h1> <div class="textContainer"> <input type="text" placeholder="Class" required /> <input type="text" placeholder="Teacher" required /> </div> </div> <div class="inputConatiner"> <h1 class="label">2B Class</h1> <div class="textContainer"> <input type="text" placeholder="Class" required /> <input type="text" placeholder="Teacher" required /> </div> </div> <div class="inputConatiner"> <h1 class="label">3B Class</h1> <div class="textContainer"> <input type="text" placeholder="Class" required /> <input type="text" placeholder="Teacher" required /> </div> </div> <div class="inputConatiner"> <h1 class="label">4B Class</h1> <div class="textContainer"> <input type="text" placeholder="Class" required /> <input type="text" placeholder="Teacher" required /> </div> </div> <div class="inputConatiner"> <h1 class="label">B Day Lunch</h1> <input type="radio" id="A" name="lunchBDay" /> <label for="A">First Lunch</label> <input type="radio" id="B" name="lunchBDay" /> <label for="B">Second Lunch</label> </div> <div class="submitContainer"> <div class="submit"> <input type="submit" placeholder="Submit" /> </div> </div> </form> </div> A: You have floated the row elements but not cleared them. As a result, the submit button's container element sits at the top of the page, partially overlapping the rows, even though the button itself has been pushed to the bottom (using absolute positioning). Instead of doing this, you need to first clear the floated elements using .submitContainer, and center-align the button within it: .submitContainer { width: 100%; height: 40px; position: relative; /* CLEAR THE FLOATED ROWS */ clear: both; /* CENTER-ALIGN THE CONTENTS OF THIS CONTAINER */ text-align: center; } Next, remove the absolute positioning from the .submit element itself, as well as the negative margin (since it is now being aligned by its container): .submit { height: 40px; width: 150px; display: inline-block; /* position: absolute; <- REMOVE THIS */ /* left: 50%; <- REMOVE THIS */ /* top: 2075%; <- REMOVE THIS */ /* margin: 0 0 0 -75px; <- REMOVE THIS */ } That will allow the submit container and button to sit below the form without having to push it down.
{ "pile_set_name": "StackExchange" }
Q: Apply visible binding progmatically with knockout I am writing a custom binding but as part of it I need to apply a data bind for the visible binding via javascript. There seems to be little problem in getting it to work up front, however when the observable being used is updated the binding does not get re-evaluated. Upon looking in the source code for KO there is no init event so not sure if some space magic happens at some layer to get it to re-evaluate the dom elements on the observable changing but I am unable to find this info. So is there some specific way to create an artificial binding which re-evaluates, or do I need to create my own subscribe callback to keep re-evaluating the visible binding? Here is the code I am using: ko.bindingHandlers.visible.update(element, isVisibleObservable, allBindingsAccessor, viewModel); I know I could write my own show and hide logic, but I just thought it would be simpler on first glance to use the existing binding which does it under the hood. Here is a simple example of the scenario with the code usage: ko.bindingHandlers.someCustomBinding = { init: function(element, valueAccessor, allBindingsAccessor, viewModel) { var allBindings = allBindingsAccessor(); var customBindings = allBindings.someCustomBinding; var someReferencedElement = $(customBindings.target)[0]; var isVisible = (customBindings.isDefault) ? true : false; var visibleObservable = ko.observable(isVisible); knockout.bindingHandlers.visible.update(someReferencedElement, visibleObservable, allBindingsAccessor, viewModel); element.onclick = function() { var toggledValue = !visibleObservable(); visibleObservable(toggledValue) }; } }; I have heavily simplified the scenario, so removed validation of parameters etc but that should highlight the main usage and issue. When I click on the element with the custom binding it is toggling the value (as I can see this in the debugger) although it does not update the visibility of the referenced DOM element. A: Check out this post - Reapply bindings in knockout The problem is that you can add new bindings to Knockout and force them to re-evaluate but what you are trying to do is apply a binding to existing bindings and clean the node and re-evaluate, which is a grey area as shown in that question I linked. At this point I would implement a custom binding handler to do what you are trying to do using show/hide logic there until a more stable solution can be found. You could just incorporate the code into your custom binding handler for now - ko.bindingHandlers['visible'] = { 'update': function (element, valueAccessor) { var value = ko.utils.unwrapObservable(valueAccessor()); var isCurrentlyVisible = !(element.style.display == "none"); if (value && !isCurrentlyVisible) element.style.display = ""; else if ((!value) && isCurrentlyVisible) element.style.display = "none"; } }; If you show a better example and include your binding handler I can help update it.
{ "pile_set_name": "StackExchange" }
Q: PHP class with single variable I'm using this PHP code for creating PHP class with default single variable. But it's not work perfectly. Note : I need to store data in single variable. <?PHP class hello { public $data; } $test = new hello(); $test->data->user1->name = "Charan"; $test->data->user1->sex = "male"; $test->data->user1->age = "25"; $test->data->user2->name = "Kajal"; $test->data->user2->sex = "female"; $test->data->user2->age = "21"; print_r($test->data->user1); ?> I got this error : Please help me , how to fix it ? A: You have only declared the variable, but you havent set it up as a "type". For example youre trying to assign values to properties n an object... but $data is not an object - its not anything. You need to either assign an object to $data in the constructor for the class, or assign it from outside the class. Constructor: class hello { public $data; public function __construct() { $this->data = new StdClass(); // assuming you want the users set up here as well $this->data->user1 = new StdClass(); $this->data->user2 = new StdClass(); } } From Outside: // assume we are use the same class definition from your orginal example $test = new hello(); $test->data = new StdClass(); $test->data->user1 = new StdClass(); $test->data->user2 = new StdClass(); $test->data->user1->name = "Charan"; $test->data->user1->sex = "male"; $test->data->user1->age = "25"; $test->data->user2->name = "Kajal"; $test->data->user2->sex = "female"; $test->data->user2->age = "21";
{ "pile_set_name": "StackExchange" }
Q: Runtime Error: SwiftUI: No image named '' found in asset catalog for main bundle This is the error I'm getting: runtime: SwiftUI: No image named '' found in asset catalog for main bundle (/Users/yun/Library/Developer/CoreSimulator/Devices/623B1BB3-5C34-4311-AA41-86C42FE27439/data/Containers/Bundle/Application/8E87B349-36CA-41B8-A34C-02BBB2F00472/Travel.app) The image doesn't have a name, just '', so I can't find the cause of the error. // AppDelegate.swift <br> class AppDelegate: UIResponder, UIApplicationDelegate { <-- this is the break point... A: The error that you are receiving means that somewhere in your code you are initiating an Image("some name") and passing in an empty string "". Try a search for Image( in Xcode and see if there are any Image views maybe, with default values that are blank. Also, if you really want to debug this issue, and find the missing image name among potentially thousands of lines of code, you can try out this nifty extension: #if DEBUG extension Image { init(_ str: String) { guard let img = UIImage(named: str) else { print(str) fatalError("found an image that doesn't exist, see: https://stackoverflow.com/a/63006278/11161266") } self.init(uiImage: img) } init(systemName sys: String) { guard let img = UIImage(systemName: sys) else { print(sys) fatalError("found an image that doesn't exist, see: https://stackoverflow.com/a/63006278/11161266") } self.init(uiImage: img) } } #endif It will force a crash when it finds a missing image, and you can navigate directly to the line of code that caused it: Alternatively, you could easily modify the above extension to actually provide a default value to all your empty images: extension Image { init(_ str: String) { self.init(uiImage: UIImage(named: str) ?? UIImage(named: "Some default image")! ) } }
{ "pile_set_name": "StackExchange" }
Q: Why does the query take a long time in mysql even with a LIMIT clause? Say I have an Order table that has 100+ columns and 1 million rows. It has a PK on OrderID and FK constraint StoreID --> Store.StoreID. 1) select * from 'Order' order by OrderID desc limit 10; the above takes a few milliseconds. 2) select * from 'Order' o join 'Store' s on s.StoreID = o.StoreID order by OrderID desc limit 10; this somehow can take up to many seconds. The more inner joins I add, slows it down further more. 3) select OrderID, column1 from 'Order' o join 'Store' s on s.StoreID = o.StoreID order by OrderID desc limit 10; this seems to speed the execution up, by limiting the columns we select. There are a few points that I dont understand here and would really appreciate it if anyone more knowledgeable with mysql (or rmdb query execution in general) can enlighten me. Query 1 is fast since it's just a reverse lookup by PK and DB only needs to return the first 10 rows it encountered. I don't see why Query 2 should take for ever. Shouldn't the operation be the same? i.e. get the first 10 rows by PK and then join with other tables. Since there's a FK constraint, it is guaranteed that the relationship will be satisfied. So DB doesn't need to join more rows than necessary and then trim the result, right? Unless, FK constraint allows null FK? In which case I guess a left join would make this much faster than an inner join? Lastly, I'm guess query 3 is simply faster because less columns are used in those unnecessary joins? But why would the query execution need the other columns while joining? Shouldn't it just join using PKs first, and then get the columns for just the 10 rows? Thanks! A: My understanding is that the mysql engine applies limit after any join's happen. From http://dev.mysql.com/doc/refman/5.0/en/select.html, The HAVING clause is applied nearly last, just before items are sent to the client, with no optimization. (LIMIT is applied after HAVING.) EDIT: You could try using this query to take advantage of the PK speed. select * from (select * from 'Order' order by OrderID desc limit 10) o join 'Store' s on s.StoreID = o.StoreID;
{ "pile_set_name": "StackExchange" }
Q: scripting in css with some creativity I found the following creative accepted answer jQuery('.get-close-to').hover(function() { var offset = jQuery(this).css('offset'); alert( 'Left: ' + offset.left + '\nTop: ' + offset.top ); }); I wanted to know how .css('offset') is working so I made a jsfiddle but it's alerting "undefined". Can anyone describes about this, working and is correct way? Comment: I know to use .offset() but I don't mean to use this, but my question regards how the accepted answer's code is working ....... with .css('offset')? That's all. A: There's no offset property in CSS. with jQuery.css(propertyName) you can only access properties that exist. Everything else will return null. for example: jQuery.css('myImaginativePropertyname'); // returns null jQuery.css('border'); // would return '0px none rgb(0, 0, 0)' However You can access the event.target (DOM element) like this: jQuery('.get-close-to').hover(function(e) { var elem = e.target; alert( 'Left: ' + elem.offsetLeft + '\nTop: ' + elem.offsetTop ); }, function(e){}); I added the second function so that the code won't be executed twice. If you have only single function as input on jQuery.hover(), it will execute both in hover and blur. If you add a second function as a parameter, the first one will be executed on hover, while the second will be executed on blur of the element. Here's the fiddle: http://jsfiddle.net/JLAK4/2/ Some people may argue to use jQuery(this).offset() instead, but why waste cpu cycles for yet another method call while you already have your DOM element populated and at your disposal? jQuery is a nice compatibility layer, I give you that. But abusing and overusing it makes no sense at all.
{ "pile_set_name": "StackExchange" }
Q: Ceil positive float and floor negative float Is there a shorter way of doing this instead of checking whether the float is positive or not and do the if statement as following? (Using Unity5 with c# script) Expecting 1.0, 1.4, 1.7 => 2 (I figured that Ceil 1.0 yields 1.. any help with this too?) -1.0, -1.4, -1.7 => -2 (Floor -1.0 yields -1..) if (float < 0) { Mathf.Floor (float); } else { Mathf.Ceil (float); } Thanks in advance, A: You could try Mathf.Sign(x)*Mathf.Ceil(Mathf.Abs(x))
{ "pile_set_name": "StackExchange" }
Q: Unable to chain-access tuple types Given: struct NameType([u8;64]); name: (NameType, NameType); I can do: let def = &name.0 OR &name.1 but I cannot do: let def = &name.0.0 OR &name.1.0 to access the internals. I have to do it twice: let abc = &name.0; let def = &abc.0; why am I unable to chain it to access inner sub-tuples, tuple-structs etc? rustc 1.0.0-nightly (ecf8c64e1 2015-03-21) (built 2015-03-22) A: As mentioned in the comments, foo.0.0 will be parsed as having a number. This was originally mentioned in the RFC, specifically this: I'd rather not change the lexer to permit a.0.1. I'd rather just have that be an error and have people write out the names. We could always add it later. You can certainly file a bug, but as a workaround, use parenthesis: (foo.0).0 In my opinion, you shouldn't be nesting tuples that deep anyway. I'd highly recommend giving names to fields before you slowly go insane deciding if you wanted foo.0.1.2 or foo.1.2.0.
{ "pile_set_name": "StackExchange" }
Q: How can I save automatically my files to OneDrive or Google Drive without store in my computer? I'm a web developer and I have Windows 10 installed on a very small SSD (128GB). The problem is, when I want to save my file to a cloud service, I need to store the files on my computer, so that the OneDrive or the Google Drive client can synchronize them. My free space is very low, so I can't afford that. Is it possible to save files to the cloud (directly), without them needing to first download them to my computer? A: This method will allow you to accomplish what you require without installing additional software. You can upload files to OneDrive without even having the OneDrive application installed or enabled. I use many computers on a daily basis that aren't mine and this is exactly what I can do. This is also a workaround for the "placeholders" issue people have complained about with the OneDrive client. Furthermore, you can automate this process Login into www.onedrive.com You should see the link comes back as https://onedrive.live.com/?id=root&cid=XXXXXXXX. Note all of the Xs which is your unique CID For demonstration purposes, open Notepad and paste this code in (all one line): net use n: "https://d.docs.live.net/XXXX/YY/ZZZ" /USER:[email protected] /P:No Save the file as map.bat (batch file, not text file). Adjust XXXX to your CID, and adjust the file path accordingly to the folder you need. Change [email protected] to your actual email address, and you can change drive N: to any letter you choose that is not currently being used. Run the batch file In "This PC" you will see the OneDrive folder you chose mapped as a network drive. The space free does not reflect your OneDrive storage, rather it reflects your computer's hard drive's storage (they're exactly the same). You can disregard this. You don't need to map OneDrive as a network drive. You can utilize UNC, instead of accessing it like \\server\share you will just need to use the path in your batch file. Instead of using http://, use \\d.docs.live.net@SSL\CID\etc... - and you will be prompted for credentials. You can either use the command-line switch /P:Yes instead of /P:No in my example, or click Remember Credentials if you use the GUI. Please keep in mind that since the files are not locally on your system, you are essentially mapping OneDrive as a drive when the resources are all on remote Microsoft servers. So it will be slower than if you had them synced locally, albeit not much. This method above works only for OneDrive. Google Drive does not support any of this technology. Dropbox does not support it natively, but there is a paid service called DropDav you can look into. Alternatively, a service called Otixo will allow you to map Google Drive as a drive but in order to do so, you need WebDav which is a paid feature. OneDrive provides this for free. Automation: You can and you should automate all of this if possible. I don't know how you interact with OneDrive, but since this can all be done with a batch file, you can leverage automation in order to make this easy and as effortless as possible.
{ "pile_set_name": "StackExchange" }
Q: Disable USB Port on Raspberry Pi 3 I recently bought a Raspberry Pi 3. But unfortunately the first one I got was damaged. We managed to get it going but one USB port was rendered useless. Now I want to know whether it would cut down power consumption by disabling the use of the USB(if so how?) or does it do the same thing just tearing the port off? By the way I am running Raspbian. A: The USB ports run off a single USB controller so you can't just disable a single one. And the ethernet also runs off the controller, so you wouldn't be able to use it if you disabled it. Even if you did disable USB, it would save very little power. Wifi, CPU and RAM use the most energy, as well as the graphics processor. To use less power you could also disable the LEDs which would probably help more than turning off the USB controller. So reduce the software running on your Pi that uses a lot if CPU, that will help the most. And use ethernet instead of wifi if you can. Disable graphical output if you're working headless. "Tearing" off the USB ports is a really bad idea, and wouldn't do anything anyway.
{ "pile_set_name": "StackExchange" }
Q: AMO get partitions where data are processed but not indexes I am writing a script that return all unprocessed partitions within a measure group using the following command: objMeasureGroup.Partitions.Cast<Partition>().Where(x => x.State != AnalysisState.Processed) After doing some experiments, it looks like this property indicates if the data is processed and doesn't mention the indexes. After searching for hours, i didn't find any method to list the partitions where data is processed but indexes are not. Any suggestions? Environment: SQL Server 2014 SSAS multidimensional cube Script are written within a SSIS package / Script task A: First, ProcessIndexes is an incremental operation. So if you run it twice the second time will be pretty quick because there is nothing to do. So I would recommend just running it on the cube and not worrying about whether it was previously run. However if you do need to analyze the current state then read on. The best way (only way I know of) to distinguish whether ProcessIndexes has been run on a partition is to study the DISCOVER_PARTITION_STAT and DISCOVER_PARTITION_DIMENSION_STAT DMVs as seen below. The DISCOVER_PARTITION_STAT DMV returns one row per aggregation with the rowcount. The first row of that DMV has a blank aggregation name and represents the rowcount of the lowest level data processed in that partition. The DISCOVER_PARTITION_DIMENSION_STAT DMV can tell you about whether indexes are processed and which range of values by each dimension attribute are in this partition (by internal IDs, so not super easy to interpret). We assume at least one dimension attribute is set to be optimized so it will be indexed. You will need to add a reference to Microsoft.AnalysisServices.AdomdClient also to simplify running these DMVs: string sDatabaseName = "YourDatabaseName"; string sCubeName = "YourCubeName"; string sMeasureGroupName = "YourMeasureGroupName"; Microsoft.AnalysisServices.Server s = new Microsoft.AnalysisServices.Server(); s.Connect("Data Source=localhost"); Microsoft.AnalysisServices.Database db = s.Databases.GetByName(sDatabaseName); Microsoft.AnalysisServices.Cube c = db.Cubes.GetByName(sCubeName); Microsoft.AnalysisServices.MeasureGroup mg = c.MeasureGroups.GetByName(sMeasureGroupName); Microsoft.AnalysisServices.AdomdClient.AdomdConnection conn = new Microsoft.AnalysisServices.AdomdClient.AdomdConnection(s.ConnectionString); conn.Open(); foreach (Microsoft.AnalysisServices.Partition p in mg.Partitions) { Console.Write(p.Name + " - " + p.State + " - "); var restrictions = new Microsoft.AnalysisServices.AdomdClient.AdomdRestrictionCollection(); restrictions.Add("DATABASE_NAME", db.Name); restrictions.Add("CUBE_NAME", c.Name); restrictions.Add("MEASURE_GROUP_NAME", mg.Name); restrictions.Add("PARTITION_NAME", p.Name); var dsAggs = conn.GetSchemaDataSet("DISCOVER_PARTITION_STAT", restrictions); var dsIndexes = conn.GetSchemaDataSet("DISCOVER_PARTITION_DIMENSION_STAT", restrictions); if (dsAggs.Tables[0].Rows.Count == 0) Console.WriteLine("ProcessData not run yet"); else if (dsAggs.Tables[0].Rows.Count > 1) Console.WriteLine("aggs processed"); else if (p.AggregationDesign == null || p.AggregationDesign.Aggregations.Count == 0) { bool bIndexesBuilt = false; foreach (System.Data.DataRow row in dsIndexes.Tables[0].Rows) { if (Convert.ToBoolean(row["ATTRIBUTE_INDEXED"])) { bIndexesBuilt = true; break; } } if (bIndexesBuilt) Console.WriteLine("indexes have been processed. no aggs defined"); else Console.WriteLine("no aggs defined. need to run ProcessIndexes on this partition to build indexes"); } else Console.WriteLine("need to run ProcessIndexes on this partition to process aggs and indexes"); } A: I am posting this answer as additional information of @GregGalloway excellent answer After searching for a while, the only way to know if partition are processed is using DISCOVER_PARTITION_STAT and DISCOVER_PARTITION_DIMENSION_STAT. I found an article posted by Daren Gossbel describing the whole process: SSAS: Are my Aggregations processed? In the artcile above the author provided two methods: using XMLA One way in which you can find it out with an XMLA discover call to the DISCOVER_PARTITION_STAT rowset, but that returns the results in big lump of XML which is not as easy to read as a tabular result set. example <Discover xmlns="urn:schemas-microsoft-com:xml-analysis"> <RequestType>DISCOVER_PARTITION_STAT</RequestType> <Restrictions> <RestrictionList> <DATABASE_NAME>Adventure Works DW</DATABASE_NAME> <CUBE_NAME>Adventure Works</CUBE_NAME> <MEASURE_GROUP_NAME>Internet Sales</MEASURE_GROUP_NAME> <PARTITION_NAME>Internet_Sales_2003</PARTITION_NAME> </RestrictionList> </Restrictions> <Properties> <PropertyList> </PropertyList> </Properties> </Discover> using DMV queries If you have SSAS 2008, you can use the new DMV feature to query this same rowset and return a tabular result. example SELECT * FROM SystemRestrictSchema($system.discover_partition_stat ,DATABASE_NAME = 'Adventure Works DW 2008' ,CUBE_NAME = 'Adventure Works' ,MEASURE_GROUP_NAME = 'Internet Sales' ,PARTITION_NAME = 'Internet_Sales_2003') Similar posts: How to find out using AMO if aggregation exists on partition? Detect aggregation processing state with AMO?
{ "pile_set_name": "StackExchange" }
Q: In JQuery UI, How to know the current status ( expanded or collapsed ) of the Accordion? I am using JQuery accordion. On click, I want to know the current status of it. How can I know it? A: Jquery sets a class on the active/opened accordion: "ui-state-active" vs. ".ui-state-default" (these are the classes on the Accordion demo on Jquery website: http://docs.jquery.com/UI/Accordion) Edit: You can of course then check each accordion to see if it has the active vs. default class A: try this if($('#my_accordion h3′).hasClass('ui-state-active')) { // accordion is open } else { // accordion is closed }
{ "pile_set_name": "StackExchange" }
Q: how redirect and respond of save action works in grails 2.3.0 controller request.withFormat { form { redirect humanInstance //Explain : old grails redirect like redirect(action: "show", id: humanInstance.id) //but in 2.3.0 by redirect humanInstance this statement i saw it goes to def show(Human humanInstance) action //Q1: how it understand that it has to redirect def show(Human humanInstance) action ? //cause here so many methods which receives humanInstance //Q2: And where it get processed ? } '*' { respond humanInstance, [status: CREATED] } //Explain : I tested it that in the above {works for normalCall}'*'{works for restCall} //Q3: What is '*' operator do here what it's name? } A: The '*' is kind of a catch-all which is associated with a block of code that should execute if none of the other blocks matched the accept header. See the following... request.withFormat { xml { // execute this if the request content type is xml } json { // execute this if the request content type is json } '*' { // execute this if neither of the other 2 matched the request's content type } } There is quite a bit that you probably want to understand around this including the mime types that you have configured. You should look at the Content Negotiation section of the official user guide at http://grails.org/doc/2.3.x/guide/theWebLayer.html#contentNegotiation. I hope that is helpful. UPDATE: When you call redirect(someDomainClassInstance) you end up at https://github.com/grails/grails-core/blob/v2.3.8/grails-plugin-controllers/src/main/groovy/org/codehaus/groovy/grails/plugins/web/api/ControllersApi.java#L270 That calls https://github.com/grails/grails-core/blob/v2.3.8/grails-plugin-controllers/src/main/groovy/org/codehaus/groovy/grails/plugins/web/api/ControllersApi.java#L248 That calls https://github.com/grails/grails-core/blob/v2.3.8/grails-plugin-controllers/src/main/groovy/org/codehaus/groovy/grails/web/metaclass/RedirectDynamicMethod.java#L160 That calls https://github.com/grails/grails-core/blob/v2.3.8/grails-web/src/main/groovy/org/codehaus/groovy/grails/web/mapping/DefaultLinkGenerator.groovy#L175. At that point the value of "method" is "GET_ID". The value in https://github.com/grails/grails-core/blob/v2.3.8/grails-web/src/main/groovy/org/codehaus/groovy/grails/web/mapping/DefaultLinkGenerator.groovy#L56 which is associated with GET_ID is "show" and that is what dictates that you will redirect to the show method.
{ "pile_set_name": "StackExchange" }
Q: Which C/C++/Objective C compiler should i choose in xcode 4.2? Trying to archive my app to submit to app store. The app can run nicely on Simulator/Device but while archiving I got the below error for cocos2d libraries. Unsupported compiler 'GCC 4.2' selected for architecture 'armv7' In Build settings, Compiler for C/C++/Objective C are - Default Compiler (Apple LLVM compiler 3.0) - Apple LLVM compiler 3.0 - LLVM GCC 4.2 Which compiler will be the better choice ? Appreciate for any help. Thanks =) A: Apple LLVM compiler 3.0 is the default beginning with Xcode 4.2. I would generally advise to use LLVM 3.0 not just because it's the default but also because it reports warnings and errors for potentially dangerous code that will pass by LLVM GCC. For example, LLVM 3.0 can check in many situations if an array access is out of bounds. It is also reporting warnings for potential "undeclared selector sent to instance" at compile time, rather than at runtime. Another point is that LLVM 3.0 is now the default for both platforms (iOS and Mac). So if you want to develop for both platforms and want to avoid unwanted surprises, you should definitely use LLVM 3.0.
{ "pile_set_name": "StackExchange" }
Q: Drawing a dynamic graph that changes in real time I have this code ..it prints real time tweets based on a filter applied by me and searches for the following sub strings in the tweet, if there then that particular counter specific to that sub string gets incremented. Now , I want to draw a graph taking these 2 counters as input and showing real time variations. Please tell me any api to use or any method by which it can be done. Thanks StatusListener listener; listener = new StatusListener(){ int count1=0,count2=0; String s1="#rcb"; String s2="#kxip"; String s3="#RCB"; String s4="#KXIP"; @Override public void onStatus(Status status) { t.append("\n" + status.getUser().getName() + " : " + status.getText() + "\n"); String str=status.getText(); if(str.contains(s1)||str.contains(s3)) count1++; else if(str.contains(s2)||str.contains(s4)) count2++; t.append("Count1:"+count1); t.append("Count2:"+count2); DefaultCategoryDataset barChartData=new DefaultCategoryDataset(); barChartData.setValue(count1,"Popularity","RCB"); barChartData.setValue(count2,"Popularity","KXIP"); JFreeChart barChart= ChartFactory.createBarChart("Popularity Meter","Teams", "Popularity Count", barChartData, PlotOrientation.VERTICAL, rootPaneCheckingEnabled, rootPaneCheckingEnabled, rootPaneCheckingEnabled); CategoryPlot barchrt=barChart.getCategoryPlot(); barchrt.setRangeGridlinePaint(Color.ORANGE); ChartPanel barPanel= new ChartPanel(barChart); jPanel2.removeAll(); jPanel2.add(barPanel,BorderLayout.CENTER); jPanel2.validate(); } A: JFreeChart is a popular Java charting library: http://www.jfree.org/jfreechart/ Drive the chart from a model, update the model with your values, and then tell the chart the model data has changed.
{ "pile_set_name": "StackExchange" }
Q: How can I produce an HTML list structure from JavaScript data structure? I need to traverse this data structure to render a set of lists. With a structure where nested data has the same structure as parent, it would be no problem - but here all models are different. There will be one list where each item contains a list of each level in this structure. Like so: Desired result: Unselected | Countries | Provinces | Cities | <--- Top ul --------------------------------------- |-China | | | <--- Sub uls |-Denmark | | | Selected | Countries | Provinces | Cities | --------------------------------------- |-China X |-Matjii X |- Go Neng | |-Denmark |-Pausiu |- Tsau Pei X | The Xs represent a selected option. If an item is selected, only it's information should be shown in subsequent lists. As you see above, since China is selected, the following lists have no data from Denmark shown. Data structure: { countries: { china: { name: "China", provinces: { matjii: { name: "Matjii", cities: { goneng: { name: "Go Neng" }, tsauPei: { name: "Tsau Pei" } } }, pausiu: { name: "Pausiu", cities: {...} } } }, denmark: { name: "Denmark", counties: { borjskada: { name: "Borjskada", towns: { fjollmaska: { name: "Fjollmaska" } } }, larvmauda: { name: "Larvmauda", towns: { tarnaby: { name: "Taernaby" } } } } } } } I've tinkered with two different recursive approaches, but what stops me is always that I can not anticipate what the next level might be called (city, town or matjii). Am I missing some simple obvious solution? Pseudo code is fine, I'm looking for a general approach to this. A: Basically, i believe the key lies in normalizing the data, either from the backend or frontend (js). In this reply, I would assume you have no choice but to do it from the front end. Each country have different naming conventions for their geographical locations, Eg. some name it city, counties, towns, village, etc.. Despite the differences in naming, they all follow a tree like hierarchical structure. Hence, this is your angle of attack. Normalize them based on hierarchical level. The following sample code will print out your sample data in hierarchical level. Their levels are contrasted by the amount of indentation. Copy and paste the following code and run it in your browser console. Data: var data = { countries: { china: { name: "China", provinces: { matjii: { name: "Matjii", cities: { goneng: { name: "Go Neng" }, tsauPei: { name: "Tsau Pei" } } }, pausiu: { name: "Pausiu", } } }, denmark: { name: "Denmark", counties: { borjskada: { name: "Borjskada", towns: { fjollmaska: { name: "Fjollmaska" } } }, larvmauda: { name: "Larvmauda", towns: { tarnaby: { name: "Taernaby" } } } } } } } Functions: function traverseDataStructure(rootNode, nodeLevel){ if(!rootNode) return; if(nodeLevel > 3) return; //just a secondary protection for infinite recursion if(!nodeLevel) nodeLevel = 0; var indentationForPrinting = ''; for(var i=0;i<nodeLevel;i++){ indentationForPrinting += ' '; } console.log(indentationForPrinting + 'Traversing level ' + nodeLevel); for(var prop in rootNode){ //prop may either by countries (level 0) or provinces (level 1) or counties (level 1) or cities (level 2) or towns (level 2) var regionType = prop; var regionList = getRegionList(rootNode[prop]); console.log(indentationForPrinting + 'regionType: ' + regionType); console.log(indentationForPrinting + 'regionList: ' + regionList); if(regionList.length <= 0) return; //then iterate the list of regions for(var i=0;i<regionList.length; i++){ for(var subRegion in regionList[i]){ if (subRegion == 'name'){ var regionName = regionList[i][subRegion]; console.log(indentationForPrinting + 'regionName: ' + regionName); } else { traverseDataStructure({subRegion: regionList[i][subRegion]}, nodeLevel+1); } } } } } function getRegionList(obj){ var list = []; for(var location in obj){ list.push(obj[location]); } return list; } Run it: traverseDataStructure(data); Expected output: Hope this can give you an alternative to tackle your problem
{ "pile_set_name": "StackExchange" }
Q: Choosing OpenLayers or Leaflet? I was debating with one of my collegues on OpenLayers v/s Leaflet. I made a point that OpenLayers is much better API if we wish to build a project, where you need direct connectivity to the Geoserver and PostGIS. Then I found Open Data Kit, which looks pretty new but has the features of connectivity with the Geoserver and PostGIS. So my project details are as follows, Use the map interface to fetch Feature Info Create a customized tool that takes the lat/lon from user as to where he/she clicks on the map and then fetches the Climate Data from the raster (which is handled by a py script on the server) Allows user to upload excel, which is sent to the py script, which returns a GeoJSON, which creates Vector Features on the map Allow user to create vector polygons, which will fetch the Features it intersects from the WFS Layer. Fetches Layer from the PostGIS Datastore on GeoServer and displays the layers on the map. So now I am confused on which is better and why using OpenLayers over Leaflet makes more sense or not? A: I have used both OpenLayers and Leaflet in my apps. There has been so much discussion on this topic in this forum and others on planet-internet. They usually fall into 2 camps - features and flexibility of OpenLayers versus simplicity of Leaflet. I would not be surprised if someone spawns an "OpenLeaf" initiative soon marrying the best of both worlds! I found Leaflet very simple to use, a petite 64K size, compared to over 700K Openlayers, and in very few steps you can create apps that have the freshness and eye-candy of today's web and mobile GIS apps. Your stack - GeoServer, PostGIS etc., is a standard stack, so OpenLayers or Leaflet could easily be incorporated. Having said that, I would still go with OpenLayers for the following reasons There is just a TON of material around OpenLayers. It is a lot more mature than Leaflet. Check out the comparison on commits and users. OpenLayers, GeoServer, PostGIS stack is so proven in the FOSS world that you are going on a path that is solid. OpenLayers has tad bit more features on Map Controls. While its a bit more work to create transitions and visual-effects, it can be done in OpenLayers. A: Leaflet all the way. I feel like Leaflet is the next step on the evolution of the open source tile based browser clients. Ka-Map -> OpenLayers -> Leaflet. Leaflet is simple to use and does exactly what it says on the tin. OpenLayers has become bloated by trying to to be all things to all people, Leaflet does the 20% of things that are required 80% of the time. A: Though I used Leaflet in my webGIS application, OpenLayers has much more advantages over Leaflet. For example if you want to use your application in mobile devices, OpenLayers is a must for the time being. There are lots of resources related with OpenLayers, however I think developing application with Leaflet is easier than OpenLayers (it is easier to read a code and understand the structure). If you have a time limitation and have a little experience with JavaScript, using Leaflet might be a better solution to get it done faster. Or if you want to develop a very simple application, Leaflet can be much easier to adapt at first. But after I developed an application with Leaflet, now I say I wish I had used OpenLayers at the beginning. Because when your application becomes complex (such as calling complex layers from a database, developing a robust mobile application, etc.), Leaflet starts to limit your abilities. So, I think spending a little more time to understand and learn OpenLayers structure at the learning stage will eventually worth it. As the project details considered; Use the map interface to fetch Feature Info: Both Leaflet and OpenLayers can perfectly do that. The point here is to get the click event's coordinates and send request to the server. The request link will be the same for both applications. Create a customized tool that takes the lat/lon from user as to where he/she clicks on the map and then fetches the Climate Data from the raster (which is handled by a py script on the server): I achieved that myself in Leaflet (I was also calling the climate data by the way). I wasn't fetching the raster data from a server but the point here is to create a request link, which is easy for both applications. However if you want to select a polygon at this stage it is a bit hard on Leaflet to achieve. Allows user to upload excel, which is sent to the py script, which returns a GeoJSON, which creates Vector Features on the map: Approximately the same line of work for both Leaflet and OpenLayers. I can't say which one is better. Allow user to create vector polygons, which will fetch the Features it intersects from the WFS Layer: I have no idea about OpenLayers editing abilities but Leaflet has a plugin called Leaflet Draw, which is easy to use and manipulate the drawings (on javascript side) after drawing is completed. Also Leaflet has a WFS-T support if you want to manipulate the spatial data on WFS server. OpenLayers might be better than that, I don't know. Fetches Layer from the PostGIS Datastore on GeoServer and displays the layers on the map: Definitely OpenLayers is better for this job as it is easier to connect PostGIS server. By the way, there is an application suite called OpenGeo Suite that includes OpenLayers, GeoServer and PostGIS; which will solve all the problems a web based GIS application developer has.
{ "pile_set_name": "StackExchange" }
Q: is this the right approach to calculate cosine similarity? If you guys can please review if the following approach (pseudo-code) is good to go to calcualte cosine similarity between 2 vectors: var vectorA = [2,5,7,8]; var referenceVector= [1,1,1,1]; //Apply weights to vectors (apply positive or negative weights to elements) var weightageVector = [1,0.5,2,1.5]; var weighted vectA = GetWeightedVector(vectorA); //normalize each element to a value beteen 0 and 1 //@see http://stn.spotfire.com/spotfire_client_help/norm/norm_scale_between_0_and_1.htm as calcuated here:http://jsfiddle.net/snehilw/86jqo1sm/4/ var normalizedVectorA = GetNormalizedVector(vectorA); //using the formula above var cosineSimilarityScore = GetCosineSimilarityScore(referenceVector, normalizedVectorA ); can someone please advise if this is correct approach as this is not giving me correct results. As requested, here is the code snippet: var defaultVectorWeights = [1,0.5,2,1.5]; var referenceVector = [1, 1, 1, 1] //Default values for the reference vector (Do not change these); var supportedVectorLength = referenceVector.length; function getNormalizedVector(multiDimArray, vector){ var normalizedVector = []; if(vector.length == supportedVectorLength){ var normalizedValue = 0; for(var j = 0; j < supportedVectorLength ; j++){ var min = getMinMaxForMultidimensionalArrayColumn(multiDimArray,j)[0]; var max = getMinMaxForMultidimensionalArrayColumn(multiDimArray,j)[1]; normalizedValue = (max == min) ? 0.5 : (vector[j] - min) / (max - min); normalizedVector.push(normalizedValue); } } //console.log('normalizedVector='+normalizedVector); return normalizedVector; } function getCosineSimilarityScore(vectorA, vectorB) { var similarityScore; if((vectorA.length == supportedVectorLength) && (vectorB.length == supportedVectorLength)){ var lenVectA = vectorA.length, product = 0, normVectorA = 0, normVectorB = 0; for (var i = 0; i < lenVectA ; i++) { product += vectorA[i] * vectorB[i]; normVectorA += vectorA[i] * vectorA[i]; normVectorB += vectorB[i] * vectorB[i]; } similarityScore = product / (Math.sqrt(normVectorA) * Math.sqrt(normVectorB)); } else { //TODO: Handle exception/ Fire an event to notify the server about this exception console.log("Cosine similarity workload vectors are of unequal lengths"); } return similarityScore; } function getWeightedVector(vector) { var vectorArray = []; //Initialize if(vector.length == supportedVectorLength){ for(var j = 0; j < supportedVectorLength ; j++){ vectorArray.push(defaultVectorWeights[j]*vector[j]); } } else{ //TODO: Handle exception/ Fire an event to notify the server about this exception console.log("Cosine similarity workload vector is of unsupported length"); } return vectorArray; } function getMinMaxForMultidimensionalArrayColumn(multiDimArray, column){ var _MIN_MAX = []; //[min,max] var columnarArray = []; if(column < supportedVectorLength){ //Extract columnar array from the multi-dimensional array $.map(multiDimArray, function( arrayVect) { columnarArray.push(arrayVect[column]); }); //Find the MIN and MAX _MIN_MAX.push(Math.min.apply(Math,columnarArray)); _MIN_MAX.push(Math.max.apply(Math,columnarArray)); } else{ //TODO: Handle exception/ Fire an event to notify the server about this exception console.log("Cosine similarity workload vectors are of unequal lengths"); } return _MIN_MAX; } function getAssociateWorkloadScore(multiDimArray,queryVector){ var workloadScore; var weightedQueryVector = []; var weightedMultiDimArr = []; var normalizedMultiDimArr = []; var normalizedQueryVector = []; //Apply feature scaling weightedQueryVector = getWeightedVector(queryVector); weightedMultiDimArr = getWeightedMultiDimArr(multiDimArray); normalizedQueryVector = getNormalizedVector(weightedMultiDimArr, weightedQueryVector); workloadScore = getCosineSimilarityScore(referenceVector, normalizedQueryVector); console.log('weightedQueryVector='+weightedQueryVector); console.log('weightedMultiDimArr='+JSON.stringify(weightedMultiDimArr)); console.log('normalizedMultiDimArr='+JSON.stringify(normalizedMultiDimArr)); console.log('normalizedQueryVector='+normalizedQueryVector); console.log('workloadScore='+JSON.stringify(workloadScore)); return workloadScore; } function getTeamWorkloadScore(multiDimArray){ var workloadScores = []; for(var j = 0; j < multiDimArray.length ; j++){ workloadScores.push(getAssociateWorkloadScore(multiDimArray,multiDimArray[j])); } return workloadScores; } A: A cosine similarity is just a dot product divided by the product of norms. So why not make a dot product function and a norm function and divide the results? (dotproduct from http://c2.com/cgi/wiki?DotProductInManyProgrammingLanguages) function dotproduct(a,b) { var n = 0, lim = Math.min(a.length,b.length); for (var i = 0; i < lim; i++) n += a[i] * b[i]; return n; } function norm2(a) {var sumsqr = 0; for (var i = 0; i < a.length; i++) sumsqr += a[i]*a[i]; return Math.sqrt(sumsqr);} function similarity(a, b) {return dotproduct(a,b)/norm2(a)/norm2(b);} Now similarity([1,0,0], [0,1,1]) == 0
{ "pile_set_name": "StackExchange" }
Q: How to make property of property in Protégé? I have a following problem to model in OWL using Protégé: Multiple Songs could be performed in different Performances. Each Song could be arranged by different Arranger in different Performance. I already know how to relate a Song to a Performance using object property. Now, how to map a Song-Performance pair to an Arranger? (In relational database, I would call this as a "descriptive attribute" of a many-to-many Song-Performance relationship). I know that I could use an annotation to an object property, but I would like to be able to infer something from this property. (For example: what Song has an Arranger arranged, and in which Performance?) As far as I know, I am not able to do inference from an annotation. A: It's not necessary to add properties of properties to model this scenario, although a property is an object (a uri) and therefore can include any property, not just annotation properties. rdfs:subPropertyOf is a good example. Statement reification isn't necessary either. It's a matter of creating an object that holds information about the song and performance. Here is a model that represents an Arranger's relationship to a Song-Performance: ex:SongPerformance a owl:Class . ex:Arranger a owl:Class . ex:arranged rdfs:domain ex:Arranger ; rdfs:range ex:SongPerformance . ex:songPerformed rdfs:domain ex:SongPerformance ; rdfs:range ex:Arranger . ex:performedIn rdfs:domain ex:SongPerformance ; rdfs:range ex:Arranger . Given this list, an example instance is: ex:Arranger-1 ex:arranged ex:SP1 . ex:SP1 ex:performedIn ex:Performance_1 ; ex:songPerformed ex:Song1 . Then you can find which songs has an arranger arranged in a given performance through the following SPARQl query: SELECT ?arranger ?song ?performance WHERE { ?arranger a ex:Arranger ; ex:arranged ?sp . ?sp ex:songPerformed ?song ; ex:performedIn ?performance . }
{ "pile_set_name": "StackExchange" }
Q: serialize::Decodable is not implemented for the type `&str` I have a structure I want to be able to decode from json: #[derive(RustcDecodable)] struct MyStruct<'a> { aa: Option<&'a str>, bb: Option<u64>, } It doesn't compile: error: the trait `rustc_serialize::serialize::Decodable` is not implemented for the type `&str` [E0277] src/my_file.rs:31 #[derive(RustcDecodable)] Why is that and how to fix it? A: If you check out the documentation for Decodable, you can see a list of all the base types that can be decoded to. You'll notice that &str is not in the list. This is the root cause of your error. Perusing that list shows that you can never decode to a borrowed type. If decoding to a string slice were possible, then the decoded struct would forever be tied to the lifetime of the input string and chances are that entire classes of decoders would become impossible — think of a decoder that directly reads from a file or a network stream, where the entire input data is never fully read in memory. To fix it, switch your struct to own the data: #[derive(RustcDecodable)] struct MyStruct { aa: Option<String>, bb: Option<u64>, } Alternatively, you can use a Cow to express that sometimes the data is owned, and sometimes it is borrowed: #[derive(RustcDecodable)] struct MyStruct<'a> { aa: Option<Cow<'a, str>>, bb: Option<u64>, }
{ "pile_set_name": "StackExchange" }
Q: How to suppress missing rows in a pivottable drill down action Is it possible in icCube version 5.0.2 to have a navigation strategy that drills-down to its children, but only shows children with data (so a NON EMPTY). I managed to get this working in the previous versin 4.8 using custom MDX but the MDX syntax has changed and my solution does not work anymore!. Enclosed a picture on the live demo dashboard called "pivottable" indicating what I would like to achieve. embedded picture If I verify the MDX that is generated I see a new custom MDX syntax, like: axis 0 {....} axis 1 {drill down parent MDX statement} The text between curly brackets is the drilldown MDX statement. What I want to achieve, MDX-wise, is a NON EMPTY in front of the statement, e.g.: axis 1 NON EMPTY {drill down parent MDX statement} Any suggestion how to achieve this is welcomed. This example can be found here A: This issue has been solved in 5.1. I was not looking in the right direction. To enforce a non empty drilldown on children do the following: open the widget select the tab Navigation select drilldown strategy mdxExpression and for the MDX expression type: non empty $member.children And voila, you only see the rows with data Checking the generated MDX shows: SELECT ... ON COLUMNS ... ON ROWS FROM ... CELL PROPERTIES VALUE, FORMATTED_VALUE, FORMAT_STRING axis 0 ... axis 1 NON EMPTY ...
{ "pile_set_name": "StackExchange" }
Q: Android trying to run my project in eclipse and end up with xml.out Sometimes when I am working on a projects layout in Eclipse I hit the run button while the active thing on the screen is still the layout.xml file. This causes eclipse to try to run just the xml file instead of the actual android project. I know that when I do this I can fix it by just deleting the xml.out file that gets created and clean/build on my project. However I remember using Eclipse at some point in the past when it didn't do this, if I hit run while working with an xml it still ran the Android project, just as if I had clicked run while editing a java file. My question is does anyone know if there is some sort of setting I can modify that will change the behavior back to that so that I don't have to switch back and forth to a java file just to run while I am actually doing work on the layout. Edit: That works but now I can't launch any other applications that I am working on without resetting that preference. Is there perhaps a way to make it treat xml files as though they are 'not launchable' so that it will go down to option that I select for what to do if active resource is not launchable? Because the "Launch the associated project" option thats under that seems like exactly what I want it to do when I try to launch an xml file. A: Under Preferences -> Run/Debug -> Launching, you can select "Always launch the previously launched application", so run the proper file once with this option marked and it will keep running the proper file for the rest of your life :) A: Window -> Preferences -> Run/Debug -> Launching On this page, under "Launch Operation", check the box next to "Always launch the previously launched application"
{ "pile_set_name": "StackExchange" }
Q: How do I convert probability into z-score Javascript> If you are in the data science industry, you would be bothered if you don't have normal distribution table. I came across the article in Stackoverflow that converts z-score to probability in JavaScript. What I really want to know is the reverse calculation of this function. /** * @param {number} z - Number of standard deviations from the mean. */ function GetZPercent(z) { // If z is greater than 6.5 standard deviations from the mean // the number of significant digits will be outside of a reasonable // range. if (z < -6.5) return 0.0; if (z > 6.5) return 1.0; var factK = 1; var sum = 0; var term = 1; var k = 0; var loopStop = Math.exp(-23); while (Math.abs(term) > loopStop) { term = 0.3989422804 * Math.pow(-1, k) * Math.pow(z, k) / (2 * k + 1) / Math.pow(2, k) * Math.pow(z, k + 1) / factK; sum += term; k++; factK *= k; } sum += 0.5; return sum; } I have a sense of how to convert z-score into the probability. But, I have no idea how to calculate the z-score(Standard deviation) from corresponding probability in javascript. For example, If I put in 0.95 (or 95%), I can expect to get 2.25 standard deviation. Above code gives me 95%, if I enter 2.25. A: Here is a function that does an opposite calculation (probability to z-score): function percentile_z(p) { var a0= 2.5066282, a1=-18.6150006, a2= 41.3911977, a3=-25.4410605, b1=-8.4735109, b2= 23.0833674, b3=-21.0622410, b4= 3.1308291, c0=-2.7871893, c1= -2.2979648, c2= 4.8501413, c3= 2.3212128, d1= 3.5438892, d2= 1.6370678, r, z; if (p>0.42) { r=Math.sqrt(-Math.log(0.5-p)); z=(((c3*r+c2)*r+c1)*r+c0)/((d2*r+d1)*r+1); } else { r=p*p; z=p*(((a3*r+a2)*r+a1)*r+a0)/((((b4*r+b3)*r+b2)*r+b1)*r+1); } return z; } Grabbed from easycalculation.com
{ "pile_set_name": "StackExchange" }
Q: Using accompaniment styles? Can you use the accompaniment styles on keyboards for your own composition if you don't have a backup band? Any singers or bands using rhythms machines, accompaniment styles in their songs? A: It would be perfectly normal to use the built in styles while songwriting, in place of a full band or production. It is unusual to use built-in keyboard styles in finished arrangements, but there are exceptions, such as John Shuttleworth:
{ "pile_set_name": "StackExchange" }
Q: Odd redirect location causes proxy error with urllib2 I am using urllib2 to do an http post request using Python 2.7.3. My request is returning an HTTPError exception (HTTP Error 502: Proxy Error). Looking at the messages traffic with Charles, I see the following is happening: I send the HTTP request (POST /index.asp?action=login HTTP/1.1) using urllib2 The remote server replies with status 303 and a location header of ../index.asp?action=news urllib2 retries sending a get request: (GET /../index.asp?action=news HTTP/1.1) The remote server replies with status 502 (Proxy error) The 502 reply includes this in the response body: "DNS lookup failure for: 10.0.0.30:80index.asp" (Notice the malformed URL) So I take this to mean that a proxy server on the remote server's network sees the "/../index.asp" URL in the request and misinterprets it, sending my request on with a bad URL. When I make the same request with my browser (Chrome), the retry is sent to GET /index.asp?action=news. So Chrome takes off the leading "/.." from the URL, and the remote server replies with a valid response. Is this a urllib2 bug? Is there something I can do so the retry ignores the "/.." in the URL? Or is there some other way to solve this problem? Thinking it might be a urllib2 bug, I swapped out urllib2 with requests but requests produced the same result. Of course, that may be because requests is built on urllib2. Thanks for any help. A: The Location being sent with that 302 is wrong in multiple ways. First, if you read RFC2616 (HTTP/1.1 Header Field Definitions) 14.30 Location, the Location must be an absoluteURI, not a relative one. And section 10.3.3 makes it clear that this is the relevant definition. Second, even if a relative URI were allowed, RFC 1808, Relative Uniform Resource Locators, 4. Resolving Relative URLs, step 6, only specifies special handling for .. in the pattern <segment>/../. That means that a relative URL shouldn't start with ... So, even if the base URL is http://example.com/foo/bar/ and the relative URL is ../baz/, the resolved URL is not http://example.com/foo/baz/, but http://example.com/foo/bar/../baz. (Of course most servers will treat these the same way, but that's up to each server.) Finally, even if you did combine the relative and base URLs before resolving .., an absolute URI with a path starting with .. is invalid. So, the bug is in the server's configuration. Now, it just so happens that many user-agents will work around this bug. In particular, they turn /../foo into /foo to block users (or arbitrary JS running on their behalf without their knowledge) from trying to do "escape from webroot" attacks. But that doesn't mean that urllib2 should do so, or that it's buggy for not doing so. Of course urllib2 should detect the error earlier so it can tell you "invalid path" or something, instead of running together an illegal absolute URI that's going to confuse the server into sending you back nonsense errors. But it is right to fail. It's all well and good to say that the server configuration is wrong, but unless you're the one in charge of the server, you'll probably face an uphill battle trying to convince them that their site is broken and needs to be fixed when it works with every web browser they care about. Which means you may need to write your own workaround to deal with their site. The way to do that with urllib2 is to supply your own HTTPRedirectHandler with an implementation of redirect_request method that recognizes this case and returns a different Request than the default code would (in particular, http://example.com/index.asp?action=news instead of http://example.com/../index.asp?action=news).
{ "pile_set_name": "StackExchange" }
Q: GraphViz doesn't make a png file when it is started from C# code In my class describing graph I would like to make one method generating GraphViz code and save it to the .dot file, and other making png graphics file with that graph. I tried: private void MakeDotFile() { FileStream fileStream = new FileStream("tmp.dot", FileMode.Create, FileAccess.Write); StreamWriter streamWriter = new StreamWriter(fileStream); streamWriter.Write("graph { a -- b }"); streamWriter.Close(); fileStream.Close(); } public void MakePngFile() { MakeDotFile(); Process process = new Process(); process.StartInfo = new ProcessStartInfo("<< dot.exe location >>", "-Tpng << .dot file location >> > << .png file location >>"); process.Start(); process.WaitForExit(); } but unfortunately it is finishing making a terible sound like "beep" and doing nothing (not creating png file). When I debugged, I had found that process exit code is 3. I checked many times if paths are good. Interesting is that the same program with the same arguments in cmd.exe is running right. What do you think? Where is the problem? What is the solution? Thanks in advance A: Instead of redirecting the output, you should use the -o parameter of dot. process.StartInfo = new ProcessStartInfo(@"D:\graphviz\bin\dot.exe", @"-Tpng D:\tmp.dot -o D:\tmp.png");
{ "pile_set_name": "StackExchange" }
Q: Is "put in all" grammatic for written english? It sound like the tutorial is saying if you want to you can go ahead and put in all your bottoms and then put in all your tops I guess "put in all" is easy to understand in everyday speech. The question is, is that grammatic for written english? A: The video is about building a framework that includes pieces of wood along the bottom of the intended structure ('bottoms') and pieces of wood along the top ('tops'). Both the tops and the bottoms need to be incorporated into the structure ('put in' - a perfectly grammatical term). The speaker is saying that you can do that for the bottoms and then for the tops. None of what he says is colloquial. It is certainly not ungrammatical. You just have to understand that 'bottoms' and 'tops' refer to pieces of wood at the bottom or top respectively of the intended structure.
{ "pile_set_name": "StackExchange" }
Q: Como colocar o ISNULL no Subselect com case? Como faço para em vez retornar Null retornar como Não. Estou com dúvidas quanto ao uso do ISNULL dentro do Subselect junto com o case. Resultado: Projeto teste Null Projeto OK Sim. Em vez de Null quero que me retorne NÃO, como faço? SELECT DISTINCT concat(CC.Descricao,'-',U1.UsuNome), C.CompDesc QtdeCNPJs, (SELECT top 1 Faturado = CASE T1.TarEstagioID WHEN 112 THEN 'SIM' ELSE 'NÃO' END FROM Projetos P INNER JOIN Tarefa T1 ON P.ProjID = T1.ProjID WHERE T1.TarStatus = 9 AND T1.TarTitulo = 'Treinamento Realizado - Emitir Boleto Setup' AND P.ProjID = PP.ProjID AND T1.TarTipID = 674) Faturado FROM PROJETOS PP INNER JOIN Tarefa T ON PP.ProjID = T.ProjID INNER JOIN Usuario U ON T.UsuIDResponsavel = U.UsuID INNER JOIN Usuario U1 ON T.UsuIDCliente = U1.UsuID LEFT JOIN Complemento C ON C.UsuID = T.UsuIDCliente AND C.CompID = 1 LEFT JOIN CurvaABC CC ON (CC.CurvaID = U1.CurvaID) WHERE CC.CurvaID = 1 A: Renan, Utilizei a função ISNULL do sqlServer. Exemplo: SELECT ISNULL(STATUS, 0) AS STATUS FROM T_TESTE Nesta situação, caso o campo status venha nullo o mesmo será substituido por 0. Se não conseguir, da uma olhada nesse post: http://t-sql.com.br/como-utilizar-a-funcao-isnull-funcoes-sql-server-parte-5/
{ "pile_set_name": "StackExchange" }
Q: Why is NPoco ignoring column and property names and mapping almost randomly? I'm using the NPoco ORM (a branch of PetaPoco) but I've just noticed it's mapping the columns incorrectly in some cases. I'm using a stored procedure and my POCO property names are identical to the column names produced by the stored procedure: string sql = "EXEC API_GetVenueSummaryByID @@venueID = @venueID"; var venue = db.FirstOrDefault<VenueSummary>(sql, new { venueID = venueID }); The stored procedure is a simple SELECT statement with a couple of variables included (removing them doesn't help): DECLARE @hasOffers bit IF EXISTS(SELECT * FROM Offers WHERE dbo.Offers.EntryType='V' AND Offers.EntryID = @VenueID AND GETDATE() <= validToDate) SET @hasOffers = 1 SELECT Venue.VenueID, VenueName, Town, County, Country, PackageCode, MeetingRoomsNo, MaxMeetingCapacity, BedroomsNo, MetaDescription AS ShortDescription, 'dummyresult.jpg' AS PrimaryImageFilename, @hasOffers AS HasSpecialOffers, CAST(TimeStamp AS BIGINT) AS RecordVersion FROM dbo.Venue WHERE Venue.VenueID = @VenueID Is there a function in NPoco which causes it to guess the mappings (ignoring their names)? If so, how I can I disable this and force it to only match based on the column and property names? Currently the only work around seems to be to use the column attribute <-- doesn't work either At the moment, even someone auto-formatting stored procedure (or any change which results in a change of column order) is breaking the application. Edit 2 I've noticed that if I restart the website application (eg by editing web.config or updating application code) then the column order fixes itself. So I can only assume the problem is related to NPoco internally caching the column indexes - and if the indexes change, the mappings will then be incorrect. I'm not sure if there's a mechanism to clear the cache that's perhaps not working? A: This is a problem with how NPoco (and PetaPoco) caches the codegen that is used to map from a SQL statement to a POCO. Usually this isn't a problem if you are changing the code when you are changing the SQL as the cache will be rebuild, however if you create your POCO first then start to change the SP after the first initial run the mappings will be incorrect. This issues has now been fixed in 2.5.83-beta, and it will now look at the column names and their positions to determine the cache key. Thanks for the help @NickG
{ "pile_set_name": "StackExchange" }
Q: How to get ASINs XPATH from 2 different Amazon pages that have the same parent nodes? I made a web scraping program using python and webdriver and I want to extract the ASIN from 2 different pages. I would like xpath to work for these 2 links at the same . These are the amazon pages:https://www.amazon.com/Hydro-Flask-Wide-Mouth-Flip/dp/B01ACATW7E/ref=sr_1_3?s=kitchen&ie=UTF8&qid=1520348607&sr=1-3&keywords=-gfds and https://www.amazon.com/Ubbi-Saving-Special-Required-Locking/dp/B00821FLSU/ref=sr_1_1?s=baby-products&ie=UTF8&qid=1520265799&sr=1-1&keywords=-hgfd&th=1. They have the same parent nodes(id, classes). How can I make this program work for these 2 links at the same time? So the problem is on these lines of code: 36, 41 asin = driver.find_element_by_xpath('//div[@id="detail-bullets"]/table/tbody/tr/td/div/ul/li[4]').text and asin = driver.find_element_by_xpath('//div[@id="detail-bullets_feature_div"]/div[@id="detail-bullets"]/table/tbody/tr/td/div/ul/li[5]').text. I have to change these lines to output in the csv the ASINs for these 2 products. For the first link it prints the wrong information and for the second it prints the ASIN. I attached the code. I will appreciate any help. from selenium import webdriver import csv import io # set the proxies to hide actual IP proxies = { 'http': 'http://5.189.133.231:80', 'https': 'https://27.111.43.178:8080' } chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--proxy-server="%s"' % ';'.join(['%s=%s' % (k, v) for k, v in proxies.items()])) driver = webdriver.Chrome(executable_path="C:\\Users\Andrei-PC\Downloads\webdriver\chromedriver.exe", chrome_options=chrome_options) header = ['Product title', 'ASIN'] with open('csv/bot_1.csv', "w") as output: writer = csv.writer(output) writer.writerow(header) links=['https://www.amazon.com/Hydro-Flask-Wide-Mouth-Flip/dp/B01ACATW7E/ref=sr_1_3?s=kitchen&ie=UTF8&qid=1520348607&sr=1-3&keywords=-gfds', 'https://www.amazon.com/Ubbi-Saving-Special-Required-Locking/dp/B00821FLSU/ref=sr_1_1?s=baby-products&ie=UTF8&qid=1520265799&sr=1-1&keywords=-hgfd&th=1' ] for i in range(len(links)): driver.get(links[i]) product_title = driver.find_elements_by_xpath('//*[@id="productTitle"][1]') prod_title = [x.text for x in product_title] try: asin = driver.find_element_by_xpath('//div[@id="detail-bullets"]/table/tbody/tr/td/div/ul/li[4]').text except: print('no ASIN template one') try: asin = driver.find_element_by_xpath('//div[@id="detail-bullets_feature_div"]/div[@id="detail-bullets"]/table/tbody/tr/td/div/ul/li[5]').text except: print('no ASIN template two') try: data = [prod_title[0], asin] except: print('no items v3 ') with io.open('csv/bot_1.csv', "a", newline="", encoding="utf-8") as output: writer = csv.writer(output) writer.writerow(data) A: You can simply use //li[b="ASIN:"] to get required element on both pages
{ "pile_set_name": "StackExchange" }
Q: Mathematical terminology for primes $(q+1)/2$ such that $q$ is also prime So I know that if both $p$ and $2p + 1$ are primes, then $p$ is a Sophie Germain prime from the Prime Glossary. My question is this: How do we call a prime $r=(q+1)/2$ such that $q=2r-1$ is also prime? I searched for the first $6$ terms via OEIS and I got sequence A005383: $$3, 5, 13, 37, 61, 73, \ldots$$ However, there does not seem to be any explicit mention of a specific terminology for such primes $r=(q+1)/2$ in the literature and on the Internet. Does anybody here know of an existing terminology for such primes $r$? Thanks! A: $r$ is the base of a Cunningham chain of the second kind. A Sophie-Germain prime is the base of a Cunningham chain of the first kind.
{ "pile_set_name": "StackExchange" }
Q: Count number of vowels in a word and generate a report summary using SQL in Oracle I have a requirement to count number of vowels in a word. Is it possible to do it in SQL? I can easily implement it using a function(PL/SQL). But I want it to be done in SQL. I have no clue about how to start. To enhance my requirement, it is not just vowels. Just to count whatever alphabets list given. also To display the the number of occurences as well. Example : STACKOVERFLOW A 1 E 1 I 0 O 2 U 0 Note on possible duplicate The possible duplicate link you suggest just count the letters; in order to generate a report, that approach won't help! If you wish, please re-evaluate. A: SELECT vowel_list.chr, COUNT(my_string.chr) FROM (SELECT UPPER(SUBSTR('STACKOVERFLOW',level,1)) AS chr FROM dual CONNECT BY level <=LENGTH('STACKOVERFLOW') ) my_string, (SELECT UPPER(SUBSTR('AEIOU',level,1)) AS chr FROM dual CONNECT BY level <=LENGTH('AEIOU') ) vowel_list WHERE vowel_list.chr = my_string.chr(+) GROUP BY vowel_list.chr ORDER BY 1; CONNECT BY level <= n generates n virtual rows with level from 1,2... n SUBSTR() extracts one character at a time, and finally the word is split into columns. Outer join with the vowels word table, and you're done!
{ "pile_set_name": "StackExchange" }