pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
15,272,491 | 0 | How to check if connection lost <p>How can I check if my connection with the server lost ? (Client or Server side no matter) I'm using TCP connection, and the server recv unlimit clients. for each client the server create thread. and with that's way I can recv / send for each client.</p> |
727,269 | 0 | Web service response is null, but SOAP message response is valid <p>I am writing a web service starting with writing the WSDL. I have been generating server-side skeleton code using wsimport and then writing my own implementing class. I'm running the web service on an Axis2 server. When using soapUI, the SOAP messages coming to and from the service look fine, but when using a web service client, I'm getting null in the client-side stubs. I've heard that this could be a namespace issue, but I see anything wrong. Here is my copy of the WSDL. Any help would be appreciated.</p> <pre><code><?xml version="1.0" encoding="UTF-8"?> <wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns1="http://org.apache.axis2/xsd" xmlns:ns="http://test.sa.lmco.com" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://test.sa.lmco.com"> <!-- **************** --> <!-- ** Types ** --> <!-- **************** --> <wsdl:types> <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://test.sa.lmco.com"> <xs:element name="sayHello"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="s" nillable="true" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="sayHelloResponse"> <xs:complexType> <xs:sequence> <xs:element minOccurs="0" name="return" nillable="true" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getTaxonomyNode"> <xs:complexType> <xs:sequence> <xs:element name="taxonomyId" minOccurs="1" maxOccurs="1" type="xs:int" /> <xs:element name="nodeId" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getTaxonomyNodeResponse"> <xs:complexType> <xs:sequence> <xs:element name="resultNode" type="ns:TaxonomyNode" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getChildren"> <xs:complexType> <xs:sequence> <xs:element name="taxonomyId" minOccurs="1" maxOccurs="1" type="xs:int" /> <xs:element name="parentNodeId" minOccurs="1" maxOccurs="1" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="getChildrenResponse"> <xs:complexType> <xs:sequence> <xs:element name="childNodes" minOccurs="0" maxOccurs="unbounded" type="ns:TaxonomyNode" /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="TaxonomyNode"> <xs:sequence> <xs:element name="taxonomyId" type="xs:int" /> <xs:element name="nodeId" type="xs:int" /> </xs:sequence> </xs:complexType> <xs:complexType name="LCD"> <xs:sequence> <xs:element name="language" type="xs:string" /> <xs:element name="content" type="xs:string" /> <xs:element name="description" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:schema> </wsdl:types> <!-- ***************** --> <!-- ** Messages ** --> <!-- ***************** --> <wsdl:message name="sayHelloRequest"> <wsdl:part name="parameters" element="ns:sayHello"/> </wsdl:message> <wsdl:message name="sayHelloResponse"> <wsdl:part name="parameters" element="ns:sayHelloResponse"/> </wsdl:message> <wsdl:message name="getTaxonomyNodeRequest"> <wsdl:part name="parameters" element="ns:getTaxonomyNode" /> </wsdl:message> <wsdl:message name="getTaxonomyNodeResponse"> <wsdl:part name="parameters" element="ns:getTaxonomyNodeResponse" /> </wsdl:message> <wsdl:message name="getChildrenRequest"> <wsdl:part name="parameters" element="ns:getChildren" /> </wsdl:message> <wsdl:message name="getChildrenResponse"> <wsdl:part name="parameters" element="ns:getChildrenResponse" /> </wsdl:message> <!-- ******************* --> <!-- ** PortTypes ** --> <!-- ******************* --> <wsdl:portType name="HelloWSPortType"> <wsdl:operation name="sayHello"> <wsdl:input message="ns:sayHelloRequest" wsaw:Action="urn:sayHello"/> <wsdl:output message="ns:sayHelloResponse" wsaw:Action="urn:sayHelloResponse"/> </wsdl:operation> <wsdl:operation name="getTaxonomyNode"> <wsdl:input message="ns:getTaxonomyNodeRequest" wsaw:Action="urn:getTaxonomyNode" /> <wsdl:output message="ns:getTaxonomyNodeResponse" wsaw:Action="urn:getTaxonomyNodeResponse" /> </wsdl:operation> <wsdl:operation name="getChildren"> <wsdl:input message="ns:getChildrenRequest" wsaw:Action="urn:getChildren" /> <wsdl:output message="ns:getChildrenResponse" wsaw:Action="urn:getChildrenResponse" /> </wsdl:operation> </wsdl:portType> <!-- ****************** --> <!-- ** Bindings ** --> <!-- ****************** --> <wsdl:binding name="HelloWSServiceSoap11Binding" type="ns:HelloWSPortType"> <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/> <wsdl:operation name="sayHello"> <soap:operation soapAction="urn:sayHello" style="document"/> <wsdl:input> <soap:body use="literal"/> </wsdl:input> <wsdl:output> <soap:body use="literal"/> </wsdl:output> </wsdl:operation> <wsdl:operation name="getTaxonomyNode"> <soap:operation soapAction="urn:getTaxonomyNode" style="document" /> <wsdl:input> <soap:body use="literal" /> </wsdl:input> <wsdl:output> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> <wsdl:operation name="getChildren"> <soap:operation soapAction="urn:getChildren" style="document" /> <wsdl:input> <soap:body use="literal" /> </wsdl:input> <wsdl:output> <soap:body use="literal" /> </wsdl:output> </wsdl:operation> </wsdl:binding> <!-- **************** --> <!-- ** Service ** --> <!-- **************** --> <wsdl:service name="HelloWS"> <wsdl:port name="HelloWSServiceHttpSoap11Endpoint" binding="ns:HelloWSServiceSoap11Binding"> <soap:address location="http://162.16.129.25:9090/axis2/services/HelloWS"/> </wsdl:port> </wsdl:service> </code></pre> <p></p> |
29,386,599 | 0 | <p>As of <strong>April 3, 2015</strong>, the <strong>BabelJS</strong> team has released <code>v5.0</code> 3 days ago which includes support for the said shorthand as stated in their <a href="http://babeljs.io/blog/2015/03/31/5.0.0/" rel="nofollow">blog post</a>.</p> <blockquote> <p>Lee Byron's stage 1 additional export-from statements proposal completes the symmetry between import and export statement, allowing you to easily export namespaces and defaults from external modules without modifying the local scope.</p> <p><strong>Exporting a default</strong></p> <pre><code>export foo from "bar"; </code></pre> <p>equivalent to:</p> <pre><code>import _foo from "bar"; export { _foo as foo }; </code></pre> </blockquote> <p><strong>Old Answer</strong>:</p> <p>This export notation</p> <pre><code>export v from "mod"; </code></pre> <p>does not supported in ES6 (look at supported examples <a href="https://people.mozilla.org/~jorendorff/es6-draft.html#table-42" rel="nofollow">in the specification</a>), but it can be supported in ES7 (look at <a href="https://github.com/leebyron/ecmascript-more-export-from" rel="nofollow">this proposal</a>).</p> <p>To achieve <em>exactly</em> the same result you must use <code>import</code> for now:</p> <pre><code>import Outer from './Outer'; export {Outer}; </code></pre> |
3,118,675 | 0 | How do I get 'rake test:acceptance' to run successfully on Windows? <p>I am currently investigating using the selenium-on-rails plug-in for testing an upcoming web app that we are developing. I've written some tests, and can get them to run successfully in the test runner in the browser, however when I try to run them from the command line using 'rake test:acceptance' I see the following error:</p> <pre><code>rake aborted! fork() function is unimplemented on this machine </code></pre> <p>I have installed the win32-open3 gem and win32-process, neither of these seem to have helped. Any ideas how I can get this working?</p> |
30,828,372 | 0 | <p>He may also be running the MS test adapter which you can get from the nunit site</p> |
1,684,333 | 0 | <p>The first thing you should do is <a href="http://www.sql-server-performance.com/tips/query_execution_plan_analysis_p1.aspx" rel="nofollow noreferrer">analyze the query plan</a>, to see what indexes (if any) SQL Server is using.</p> <p>You can probably benefit from some <a href="http://www.sql-server-performance.com/tips/covering_indexes_p1.aspx" rel="nofollow noreferrer">covering indexes</a> in this query, since you only use columns in <code>Lineinfo</code> and <code>Order_Header</code> for the join and the query restriction (the WHERE clause).</p> |
28,505,332 | 0 | <p>I have it working now. I have decided to change things around so the default css page loaded has the styles necessary for the newer model phones which support overflow:scroll. So therefore I have set the heights of the body, container_wrappper and side menu to 100% to begin with instead of changing that after receiving a positive response to checking if overflow: scroll is supported... Instead I check if overflow scroll is not supported and then if not supported i dynamically add a new stylesheet which has the heights of the body and container_wrapper as height: auto; instead of height:100%. it seems that this way around ie changing from height:100% to height: auto displays it correctly as opposed to the way i was doing it starting with no height and adding in height 100% if overflow scroll is* supported.. it was to do with the speed of things loading but when i do it this way even though there is a delay in loading the second stylesheet it still displays correctly after loading. so i add the following code to my head:</p> <pre><code><link rel="stylesheet" type="text/css" href="css/main_style_new_phones.css"/> <script> if(!canOverflowScroll()){ var lnk=document.createElement('link'); lnk.href='css/main_style_old_phones.css'; lnk.rel='stylesheet'; lnk.type='text/css'; (document.head||document.documentElement).appendChild(lnk); } </code></pre> <p>and this is the css in main_style_new_phones.css </p> <pre><code>body{ margin-top: 0px; /*moves #container right up to top of page so no gap*/ font-family:Arial,Helvetica,sans-serif; width: 100%; overflow: auto; z-index: 1; height: 100%; } #container_wrapper{ position: absolute; left: 0px; top: 0px; display: block; margin: 0 auto; width: 100%; background: #120F3A; overflow: auto; max-width: 100%; /*same width as full logo image width so that when on full screen the background color of the container doesn't spread across*/ z-index: 4; -webkit-transition: .3s; /* Android 2.1+, Chrome 1-25, iOS 3.2-6.1, Safari 3.2-6 */ -moz-transition: .3s; -o-transition: .3s; transition: .3s; /* Chrome 26, Firefox 16+, iOS 7+, IE 10+, Opera, Safari 6.1+ */ height: 100%; } #headernav { width: 100%; position:fixed; top: 0px; left: 0px; z-index: 10; background: #000; padding-bottom: 2px; -webkit-transition: .3s; /* Safari */ transition: .3s; } </code></pre> <p>and in the css for phones that do not support overflow scroll in main_style_old_phones.css:</p> <pre><code>body{ height: auto; } #container_wrapper{ height: auto; } #headernav { position:absolute; } #swipe_menu_right{ height: auto; } </code></pre> |
4,121,467 | 0 | Stretchable/expandable vertically aligned text (relative to image) <p>I would like to place some text next to an image where the text is vertically aligned relative to the image. However, I do not know how wide the window will be and so I would like the text container to expand to fill the available space.</p> <p>I have tried simply putting vertical-align:middle on the text container. That kind of works, but the text will wrap below the image if the text is too long. In order to combat this, I used display:inline-block on the text container. However, this then puts the whole text container below the image!</p> <p>So far, I have something like this:</p> <pre><code><span><img src="img.gif" /></span> <span style="display:inline-block; vertical-align:middle">Text goes here</span> </code></pre> |
32,848,427 | 0 | OpsHub-014371 Error (404)Not Found on User Mapping Page <p>I am trying to migrate source code from TFS 2010 SP1 (local on prem) to TFS Online. When I get to the User Mapping page, I get this error:</p> <blockquote> <p>com.opshub.eai.metadata.MetadataException: OpsHub-014371: Could not instantiate metadata implementation for For User List | TFS Source 1443539882111 ALM TFS 1443539882115, due to (404)Not Found</p> </blockquote> <p>I am running this on the TFS App Tier itself with the database being local. I have stopped the McAfee services. I ran the utility as Admin. I have only 2 users in the project and they are in both projects (I am the TFS Admin locally). I have performed the steps in the Walkthrough, except for the process template. We shouldn't need that because we're migrating source code only. I have cleared the cache folders.</p> <p>The error entry in the log file:</p> <blockquote> <p>09/29/2015 11:18:02,344 ERROR [http-8989-1] (com.opshub.eai.config.service.ConfigServiceImpl) - OpsHub-014371: Could not instantiate metadata implementation for For User List | TFS Source 1443539882111 ALM TFS 1443539882115, due to (404)Not Found com.opshub.eai.metadata.MetadataException: OpsHub-014371: Could not instantiate metadata implementation for For User List | TFS Source 1443539882111 ALM TFS 1443539882115, due to (404)Not Found at com.opshub.eai.tfs.common.metadata.impl.TFSMetadataImpl.getProjectsMeta(TFSMetadataImpl.java:63) at com.opshub.eai.tfs.common.metadata.impl.TFSMetadataImpl$$EnhancerByCGLIB$$5a4e716d.CGLIB$getProjectsMeta$0() at com.opshub.eai.tfs.common.metadata.impl.TFSMetadataImpl$$EnhancerByCGLIB$$5a4e716d$$FastClassByCGLIB$$465c721.invoke() at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:167) at com.opshub.eai.core.adapters.caching.MetadataCacheHandler.intercept(MetadataCacheHandler.java:40) at com.opshub.eai.tfs.common.metadata.impl.TFSMetadataImpl$$EnhancerByCGLIB$$5a4e716d.getProjectsMeta() at com.opshub.eai.config.business.ConfigServiceBusiness.getUserList(ConfigServiceBusiness.java:926) at com.opshub.eai.config.service.ConfigServiceImpl.getUserList(ConfigServiceImpl.java:407) at com.opshub.eai.config.service.ConfigServiceImpl$$EnhancerByCGLIB$$f3d793b0.CGLIB$getUserList$6() at com.opshub.eai.config.service.ConfigServiceImpl$$EnhancerByCGLIB$$f3d793b0$$FastClassByCGLIB$$148b3d41.invoke() at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:167) at com.opshub.eai.config.service.ServiceInterception.intercept(ServiceInterception.java:44) at com.opshub.eai.config.service.ConfigServiceImpl$$EnhancerByCGLIB$$f3d793b0.getUserList() at com.opshub.eai.config.service.ConfigService.getUserList(ConfigService.java:97) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.axis.providers.java.RPCProvider.invokeMethod(RPCProvider.java:397) at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:186) at org.apache.axis.providers.java.JavaProvider.invoke(JavaProvider.java:323) at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32) at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118) at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83) at org.apache.axis.handlers.soap.SOAPService.invoke(SOAPService.java:453) at org.apache.axis.server.AxisServer.invoke(AxisServer.java:281) at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:699) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source)</p> </blockquote> <p>From OVSMU.log file:</p> <blockquote> <p>2015-09-29 11:18:02,351 [1] ERROR com.opshub.eai.metadata.MetadataException: OpsHub-014371: Could not instantiate metadata implementation for For User List | TFS Source 1443539882111 ALM TFS 1443539882115, due to (404)Not Found System.ServiceModel.FaultException: com.opshub.eai.metadata.MetadataException: OpsHub-014371: Could not instantiate metadata implementation for For User List | TFS Source 1443539882111 ALM TFS 1443539882115, due to (404)Not Found</p> </blockquote> <p>Server stack trace: </p> <blockquote> <p>at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)</p> </blockquote> <p>Exception rethrown at [0]: </p> <blockquote> <p>at TFSMigrationUI.ViewModel.UserMappingViewModel.worker_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e) in e:\OVSMUBranch\TFSMigrationUI\ViewModel\UserMappingViewModel.cs:line 416 at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)</p> </blockquote> <p>Is it possible that this has something to do with the Java runtime? Perhaps I need to install a newer JRE?</p> |
40,098,668 | 0 | <p>I have tried two ways for this that works:</p> <pre><code>$str = "RestaurantSmith Family Restaurant"; echo preg_replace("/Restaurant(\w+)/", "$1", $str); </code></pre> <p>and:</p> <pre><code>echo preg_replace("/Restaurant\B/", "", $str); </code></pre> |
11,388,600 | 0 | cant get values printed in to a file <p>Iam trying to pass the value stored in the variable fieldCSV to file data.csv...Ive used javascript and php to do this.. I have triggered an ajax request when a value is stored in to the variable fieldCSV, bt this is nt working as the file that gets downloaded prints the php error inside it instead of csv..</p> <pre><code>$.ajax({ type: "POST", url: "/test/fileDownload.php", data: { name: fieldCSV}, }); <?php $name = $_POST["name"]; header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=data.csv'); $output = fopen('php://output', 'w'); fputcsv($output, $name); ?> </code></pre> <p>What am I doing wrong?</p> |
33,582,617 | 0 | <p>This is how the function should be:</p> <pre><code>void swap(chat *a, char *b) { char tmp = *b; *b = *a; *a = tmp; } </code></pre> <p>You don't need to pass 5 arguments to it; only 2, which are the two characters you want to swap.</p> <p>And don't dereference the <code>tmp</code> variable, since it is not a pointer.</p> |
28,364,040 | 0 | WebRTC DTLS-SRTP OpenSSL Server Handshake Failure <p><strong><em>Here is my procedure in OpenSSL Server Mode,</em></strong></p> <p><strong>Initialization Part of SSL and BIO variables:</strong> </p> <pre><code>map<int, SSL> m_SSLMap; map<int, BIO> m_BioWriteMap; map<int, BIO> m_BioReadMap; int InitializeServerNegotiationMode(int iFd) { SSL *pServSslFd; BIO *pWb, *pRb; pServSslFd = SSL_new(m_pCtx); assert(pServSslFd); if ( SSL_version(pServSslFd) == DTLS1_VERSION) { pWb = BIO_new(BIO_s_mem()); pRb = BIO_new(BIO_s_mem()); assert(pWb); assert(pRb); SSL_set_bio(pServSslFd, pRb, pWb); SSL_set_accept_state(pServSslFd); } m_SSLMap[iFd] = *pServSslFd; m_BioReadMap[iFd] = *pRb; m_BioWriteMap[iFd] = *pWb; return INITIALIZATION_SUCCESS; } </code></pre> <p><strong>Server Mode Negotiation Operations when DTLS data comes to the server:</strong></p> <pre><code>int ServerModeDTLSNegotiation(int iChannel, const char *pBuff, const int iLen, int iFd) { SSL *pServSslFd; BIO *pRbio; BIO *pWbio; pServSslFd = &m_SSLMap[iFd]; pRbio = &m_BioReadMap[iFd]; pWbio = &m_BioWriteMap[iFd]; char buff[4096]; memset(buff, 0, strlen(buff)); BIO_write(pRbio, pBuff, iLen); if(!SSL_is_init_finished(pServSslFd)) { int iRet = SSL_do_handshake(pServSslFd); } int iNewLen = BIO_read(pWbio, buff, 2048); if(iNewLen>0) { char *pNewData = new char[iNewLen+1]; for(int i=0;i<iNewLen;i++) pNewData[i] = buff[i]; m_pEventHandler->SendReply(iChannel, (unsigned char *)pNewData, iNewLen); } else { printf("[DTLS]:: HandShaking Response failed for this data, return -1; } return NEGOTIATION_SUCCESS; } </code></pre> <p>Here I am attaching Wireshark TCP-Dump for better monitoring about the issue. </p> <p><a href="https://www.dropbox.com/s/quidcs6gilnvt2o/WebRTC%20DTLS%20Handshake%20Failure.pcapng?dl=0">https://www.dropbox.com/s/quidcs6gilnvt2o/WebRTC%20DTLS%20Handshake%20Failure.pcapng?dl=0</a></p> <p>Now, I am confident about my initialization of SSL_CTX variable. Because, Sometimes Handshake successfully negotiate for every port. But sometimes Handshake fails for one or two port. I am working for 5 days to solve WebRTC DTLS Server Mode Negotiation for Google Chrome. But I haven't found the root cause for this problem. </p> |
22,346,803 | 0 | <p>the thing about the max being assigned as -999, max is meant to check the maximum values, and min is checking the minimum values, so its suppose to ask at each position if the column indices if even then if it is, its asking if the greatest value (which are usually positive) bigger than -999, and if they would be less than 1000, and so on.. until i get maximums and minimums, because -2000 is actually smaller than -999 so if i entered that, its suppose to be kept in minimum not max ^_^</p> |
28,977,630 | 1 | How to reference to a Method inside a Class in urls.py <p>I have this <code>views.py</code></p> <pre><code>from django.shortcuts import render from forms import ReferenceTableForm class ReferenceTable(object): def createReferenceTable(request): form = ReferenceTableForm() return render(request, "DataImport/createReferenceTable.html", {'form': form}) </code></pre> <p>And this is my <code>urls.py</code></p> <pre><code>from django.conf.urls import patterns, include, url import views urlpatterns = patterns('', url(r'^$', views.createReferenceTable), ) </code></pre> <p>But when I go to my url, <code>http://localhost:8000/create_reference_table/</code> (I am using a different <code>urls.py</code> for each app), I get this error:</p> <pre><code>'module' object has no attribute 'createReferenceTable' </code></pre> <p>If I move the method <code>createReferenceTable</code> to out of the class, it works fine.</p> <p>I think it is because as I am calling a method that is inside a class it is expecting it to be called from an instance of this class, but as I am not very experienced, I really don't know how to sort it out (either if it is the problem or not).</p> <p>Could someone explain what is going on and how I can solve it and prevent from happening next time?</p> <p>Thanks in advance!</p> |
7,328,732 | 0 | How to get stroke count of Chinese character? <p>How to get stroke count of Chinese character?</p> <p>Example></p> <p>一 => 1</p> <p>十 => 2</p> <p>日 => 4</p> |
9,717,516 | 0 | <p>Have a look at the <a href="http://msdn.microsoft.com/en-us/library/system.string.split.aspx" rel="nofollow"><code>String.Split()</code> function</a>, it tokenises a string based on an array of characters supplied.</p> <p>e.g.</p> <pre><code> string[] lines = text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries); </code></pre> <p>now loop through that array and split each one again</p> <pre><code>foreach(string line in lines) { string[] pair = line.Split(new[] {':'}); string key = pair[0].Trim(); string val = pair[1].Trim(); .... } </code></pre> <p>Obviously check for empty lines, and use <code>.Trim()</code> where needed...</p> <p>[EDIT] <strong>Or alternatively as a nice Linq statement...</strong></p> <pre><code>var result = from line in text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries) let tokens = line.Split(new[] {':'}) select tokens; Dictionary<string, string> = result.ToDictionary (key => key[0].Trim(), value => value[1].Trim()); </code></pre> |
35,545,382 | 0 | <pre><code>std::list<std::string> myList; inputList(myList); std::vector<std::vector<std::string>>myVector(1); for (const auto& str : myList) { if (str == "endOfRow") myVector.push_back({}); else myVector.back().emplace_back(str); } if (myList.empty()) myVector.clear(); // there is no need to update these values inside the loop int vectorRow = (int)myVector.size(); int vectorCol = (int)myVector.back().size(); </code></pre> <blockquote> <p>1) Am I able to iterate through the list, and grab the string that the iterator is currently at? If so, how am I able to add that string into the vector?</p> </blockquote> <p>Yes. The way you are doing it is correct, though you can use better syntax. To add it to the vector, just emplace_back() or push_back().</p> <blockquote> <p>3) When initializing the 2d vector, would pushback work to be able to increase the size as you insert each element?</p> </blockquote> <p>It will. But as you said, if you know the size of the list in the beginning, you can easily initialize it to make it more optimized. If you don't want to initialize the vector, but still want to reserve the space, you can also use vector.reserve()</p> |
25,778,028 | 0 | <p>You have to choose one way of the following :</p> <p>Re-installing a package by it's name in all solution's projects:</p> <pre><code>Update-Package –reinstall <packageName> </code></pre> <p>Re-installing a package by it's name and ignoring it's dependencies in all solution's projects:</p> <pre><code>Update-Package –reinstall <packageName> -ignoreDependencies </code></pre> <p>Re-installing a package by it's name in a project:</p> <pre><code>Update-Package –reinstall <packageName> <projectName> </code></pre> <p>Re-installing all packages in a specific project:</p> <pre><code>Update-Package -reinstall -ProjectName <projectName> </code></pre> <p>Re-installing all packages in a solution:</p> <pre><code>Update-Package -reinstall </code></pre> |
24,952,566 | 0 | <p>If you are using <code>GUIDE</code> for developing, every time you add a button to your <code>GUI</code> a chunk of code is generated:</p> <pre><code>% --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) </code></pre> <p>This function is called every time you push the said button. So, if you need something to be executed when you click the button you just need to add the lines of code you want to execute below that generated chunk of code. For example, imagine you have an <code>edit text</code> variable called <code>edit1</code> with value</p> <pre><code>edit1 = 'hello'; </code></pre> <p>If you want to interact with it you need to call <code>handles</code>, but first you need to create a global variable:</p> <pre><code>%set the current figure handle to main application data setappdata(0,'figureHandle',gcf); %set the handles to figure's application data setappdata(gcf,'EDIT1',handles.edit1); </code></pre> <p>Then, in the callback function of your button you need write the following:</p> <pre><code>% --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) figureHandle = getappdata(0,'figureHandle'); EDIT1 = getappdata(figureHandle,'EDIT1 '); new_string = 'updated string'; set(EDIT1, 'String', new_string); </code></pre> <p>Hope this helps</p> |
13,378,466 | 0 | <pre><code>function check(mail) { return !mail.match(/^\.|\.$/); } check('[email protected]'); // true check('[email protected].'); // false check('[email protected]'); // false </code></pre> <p>The function check expects a mail address as a String and checks if there is <strong>no</strong> dot(.) at the beginning or end.</p> <p>For detecting multiple dots(...) as well your function would look like this:</p> <pre><code>function check(mail) { return !mail.match(/^\.|\.{2,}|\.$/); } </code></pre> |
6,529,843 | 0 | Financial Company Logos API <p>Is there a way to dynamically pull company logos for banks and brokerages into a webpage without individually downloading each logo or building a list of URL's to link to them directly? I'm looking for any site that has an API to get company logos given a ticker symbol, company name, or website URL.</p> |
1,017,332 | 0 | Segmentation fault in QHash <p>I got the following crash in <code>QHash</code>. I am unable to find any thing into. I am using Qtopia-Core-4.3.3 on Linux Machine.</p> <p>The log is as follows:</p> <blockquote> <p>ASSERT: "*node == e || (*node)->next" in file<br> /usr/local/Trolltech/QtopiaCore-4.3.3-400wrl/include/QtCore/qhash.h, line 824<br> Segmentation fault</p> </blockquote> <p>Can anybody help me in this?</p> |
15,214,852 | 1 | depth of a tree python <p>i am new to programming and am trying to calculate the depth of a python tree. I believe that my error is because depth is a method of the Node class and not a regular function. I am trying to learn oop and was hoping to use a method. This might be a new bee error... Here is my code:</p> <pre><code>class Node: def __init__(self, item, left=None, right=None): """(Node, object, Node, Node) -> NoneType Initialize this node to store item and have children left and right. """ self.item = item self.left = left self.right = right def depth(self): if self.left == None and self.right == None: return 1 return max(depth(self.left), depth(self.right)) + 1 i receive this error: >>>b = Node(100) >>>b.depth() 1 >>>a = Node(1, Node(2), Node(3)) >>>a.depth() Traceback (most recent call last): File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 1, in <module> # Used internally for debug sandbox under external interpreter File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 15, in depth builtins.NameError: global name 'depth' is not defined </code></pre> |
15,198,592 | 0 | <p>To vertically align a text in a container, <a href="http://www.vanseodesign.com/css/vertical-centering/" rel="nofollow">multiple techniques</a> can be used. However, most of them have additional script calculation at runtime (if the height of the text container is changing) which can mess with the business logic.</p> <p>A hack can be used in your particular situation. You can add an image container with empty src inside your text container with <strong>100% height</strong> and <strong>0 width</strong> set by css.</p> <pre><code><label id="uppgift" class="uppgifter" style="display:inline-block;"><img scr=""/>Abc</label> <label id="uppgift2" class="uppgifter" style="display:inline-block;"><img scr=""/>123</label> //and css .uppgifter img{ height:100%; width:0; } </code></pre> <p><strong><a href="http://jsfiddle.net/jQ6Ua/12/" rel="nofollow">Example</a></strong></p> <p>This way you would not have to write logic for additional added layers.</p> |
3,816,595 | 0 | <p>Perhaps CCTray gets around this? </p> <p>what's the authentication mechanism you are using (forms, windows auth, federated, etc.)? </p> <p>Our CC.Net servers I make changes to about every 5 minutes while I'm working on setting up a project and have never seen this error. Everyone does run CCTray, but the cc.net servers are not internet accessible so no login is required. The IIS manages authentication seamlessly through ActiveDirectory. Is your cc.net server internet facing?</p> |
8,202,673 | 0 | <p>There is no difference. The fact is that in recursive function call you will return a specific value or you return a return of same function call.</p> |
2,705,296 | 0 | <p>They use a system simmlar to OpenID</p> <p><a href="http://www.windley.com/archives/2006/04/how_does_openid.shtml" rel="nofollow noreferrer">http://www.windley.com/archives/2006/04/how_does_openid.shtml</a></p> |
20,172,692 | 0 | 'if' statements on C++ template arguments <p>The following code gives me a warning when using the Intel compiler icpc13.</p> <pre><code>#include <iostream> template<int N> class base { public: double x[N]; }; template<int N> class derived : public base<2*N> { public: void print() { if (N==1) { std::cout << this->x[1] << std::endl; } else if (N==2) { std::cout << this->x[3] << std::endl; } } }; int main(int argc, char* argv[]) { derived<1> temp1; derived<2> temp2; temp1.print(); temp2.print(); } </code></pre> <blockquote> <p>Result: % icpc-13.1.163 main.cpp main.cpp(29): warning #175:</p> <p>subscript out of range std::cout<x[3]< <p>during instantiation of "void derived::print() [with N=1]" at line 41</p> </blockquote> <p>This is obviously not a danger since the if statement protects this line of code if the template argument is 1.</p> <p>I know that I "should" do template specialization for such things, but there is some shared code in the real functions that make the if statements on template arguments really handy.</p> <p>Question is…is this a "bad" thing to do, or is this incorrect compiler behavior? I don't get warnings with gcc, or xlc.</p> <p>I chose the pragma solution. This ends up looking like this:</p> <pre><code>void print() { #ifdef __INTEL_COMPILER #pragma warning push #pragma warning disable 175 #endif if (N==1) { std::cout<<this->x[1]<<std::endl; } else if (N==2) { std::cout << this->x[3] << std::endl; } #ifdef __INTEL_COMPILER #pragma warning pop #endif } }; </code></pre> <p>From what I can tell, the push saves the warning flags before the disable, and the pop restores them.</p> |
16,320,164 | 0 | <p>You don't need to size the parameter in the declaration and can't because the [][] syntax requires compile time constants. </p> <p>Replace with string world[][] and it should work. </p> <p>If it doesn't then use string[]* world (an array of array of strings is actually an array of pointers to an array of string)</p> <p>I hope this helps, my C++ is becoming increasingly rusty.</p> |
7,006,605 | 0 | <p>Cout works right to left in your compiler so first rightmost is evaluated then left one. :) So the value of referenced variable isn't changed.</p> |
20,909,727 | 0 | <p>You can pull the map into something like <a href="http://tilemill.com" rel="nofollow">TileMill</a> using <a href="https://www.mapbox.com/tilemill/docs/guides/reprojecting-geotiff/" rel="nofollow">this guide</a> to turn your image into a GeoTIFF. Since it's from a video game, it won't have real coordinates, but you can basically choose some fake coordinates for its corners and everything inside will be interpolated. You would export this map and use it with the <a href="http://mapbox.com/mapbox-ios-sdk" rel="nofollow">Mapbox iOS SDK</a>, which is an open source rewrite of MapKit but with more customizability. </p> <p>Technically you could also use the map in MapKit as an <code>MKTileOverlay</code> but it would have to be hosted online. With the above solution, you could export directly to an <a href="http://mbtiles.org" rel="nofollow">MBTiles</a> file and use it local to the app. </p> |
8,601,300 | 0 | <p>The problem is that the <code>SOUNDEX</code> algorithm is disabled by default and you have to use the compiler flag <code>-DSQLITE_SOUNDEX=1</code> when building <a href="http://www.sqlite.org/compile.html#soundex" rel="nofollow"><code>sqlite</code></a>. </p> <p>So you have to build the <code>sqlite</code> driver with this flag on, and then build the plugin by linking it to your <a href="http://lists.trolltech.com/qt4-preview-feedback/2005-05/thread01021-0.html" rel="nofollow"><code>sqlite</code> build</a>.</p> |
1,760,515 | 0 | How to build an hierarchy? <p>I want to analyze a piece of document and build an ontology from it. There could be many characteristics of this document, and it could be a hierarchy.</p> <p>What is the best programming method to build this hierarchy with unlimited height? A tree?</p> <p>I am looking for a broad "way" of programming, not necessary code.</p> |
11,455,088 | 0 | <p>That code in the tutorial will work if you are adding new rows to a blank worksheet. Since you have a template that you are using that does have rows you will need to do a lot more work in order to add a row in the middle of your worksheet. You pretty much need to use the same code to add in the row, but then you have to manually update the row index of every row after the row you insert. You also have to update the merged cell references and the hyperlinks references as well. There might be more that you have to update, but I never had to update more than these three things. The main method to insert a row is below:</p> <pre><code> /// <summary> /// Inserts a new row at the desired index. If one already exists, then it is /// returned. If an insertRow is provided, then it is inserted into the desired /// rowIndex /// </summary> /// <param name="rowIndex">Row Index</param> /// <param name="worksheetPart">Worksheet Part</param> /// <param name="insertRow">Row to insert</param> /// <param name="isLastRow">Optional parameter - True, you can guarantee that this row is the last row (not replacing an existing last row) in the sheet to insert; false it is not</param> /// <returns>Inserted Row</returns> public static Row InsertRow(uint rowIndex, WorksheetPart worksheetPart, Row insertRow, bool isNewLastRow = false) { Worksheet worksheet = worksheetPart.Worksheet; SheetData sheetData = worksheet.GetFirstChild<SheetData>(); Row retRow = !isNewLastRow ? sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == rowIndex) : null; // If the worksheet does not contain a row with the specified row index, insert one. if (retRow != null) { // if retRow is not null and we are inserting a new row, then move all existing rows down. if (insertRow != null) { UpdateRowIndexes(worksheetPart, rowIndex, false); UpdateMergedCellReferences(worksheetPart, rowIndex, false); UpdateHyperlinkReferences(worksheetPart, rowIndex, false); // actually insert the new row into the sheet retRow = sheetData.InsertBefore(insertRow, retRow); // at this point, retRow still points to the row that had the insert rowIndex string curIndex = retRow.RowIndex.ToString(); string newIndex = rowIndex.ToString(); foreach (Cell cell in retRow.Elements<Cell>()) { // Update the references for the rows cells. cell.CellReference = new StringValue(cell.CellReference.Value.Replace(curIndex, newIndex)); } // Update the row index. retRow.RowIndex = rowIndex; } } else { // Row doesn't exist yet, shifting not needed. // Rows must be in sequential order according to RowIndex. Determine where to insert the new row. Row refRow = !isNewLastRow ? sheetData.Elements<Row>().FirstOrDefault(row => row.RowIndex > rowIndex) : null; // use the insert row if it exists retRow = insertRow ?? new Row() { RowIndex = rowIndex }; IEnumerable<Cell> cellsInRow = retRow.Elements<Cell>(); if (cellsInRow.Any()) { string curIndex = retRow.RowIndex.ToString(); string newIndex = rowIndex.ToString(); foreach (Cell cell in cellsInRow) { // Update the references for the rows cells. cell.CellReference = new StringValue(cell.CellReference.Value.Replace(curIndex, newIndex)); } // Update the row index. retRow.RowIndex = rowIndex; } sheetData.InsertBefore(retRow, refRow); } return retRow; } </code></pre> <p>Then here are the following helper methods to update the row indices, hyperlinks, and merged cell references:</p> <pre><code> /// <summary> /// Updates all of the Row indexes and the child Cells' CellReferences whenever /// a row is inserted or deleted. /// </summary> /// <param name="worksheetPart">Worksheet Part</param> /// <param name="rowIndex">Row Index being inserted or deleted</param> /// <param name="isDeletedRow">True if row was deleted, otherwise false</param> private static void UpdateRowIndexes(WorksheetPart worksheetPart, uint rowIndex, bool isDeletedRow) { // Get all the rows in the worksheet with equal or higher row index values than the one being inserted/deleted for reindexing. IEnumerable<Row> rows = worksheetPart.Worksheet.Descendants<Row>().Where(r => r.RowIndex.Value >= rowIndex); foreach (Row row in rows) { uint newIndex = (isDeletedRow ? row.RowIndex - 1 : row.RowIndex + 1); string curRowIndex = row.RowIndex.ToString(); string newRowIndex = newIndex.ToString(); foreach (Cell cell in row.Elements<Cell>()) { // Update the references for the rows cells. cell.CellReference = new StringValue(cell.CellReference.Value.Replace(curRowIndex, newRowIndex)); } // Update the row index. row.RowIndex = newIndex; } } /// <summary> /// Updates the MergedCelss reference whenever a new row is inserted or deleted. It will simply take the /// row index and either increment or decrement the cell row index in the merged cell reference based on /// if the row was inserted or deleted. /// </summary> /// <param name="worksheetPart">Worksheet Part</param> /// <param name="rowIndex">Row Index being inserted or deleted</param> /// <param name="isDeletedRow">True if row was deleted, otherwise false</param> private static void UpdateMergedCellReferences(WorksheetPart worksheetPart, uint rowIndex, bool isDeletedRow) { if (worksheetPart.Worksheet.Elements<MergeCells>().Count() > 0) { MergeCells mergeCells = worksheetPart.Worksheet.Elements<MergeCells>().FirstOrDefault(); if (mergeCells != null) { // Grab all the merged cells that have a merge cell row index reference equal to or greater than the row index passed in List<MergeCell> mergeCellsList = mergeCells.Elements<MergeCell>().Where(r => r.Reference.HasValue) .Where(r => GetRowIndex(r.Reference.Value.Split(':').ElementAt(0)) >= rowIndex || GetRowIndex(r.Reference.Value.Split(':').ElementAt(1)) >= rowIndex).ToList(); // Need to remove all merged cells that have a matching rowIndex when the row is deleted if (isDeletedRow) { List<MergeCell> mergeCellsToDelete = mergeCellsList.Where(r => GetRowIndex(r.Reference.Value.Split(':').ElementAt(0)) == rowIndex || GetRowIndex(r.Reference.Value.Split(':').ElementAt(1)) == rowIndex).ToList(); // Delete all the matching merged cells foreach (MergeCell cellToDelete in mergeCellsToDelete) { cellToDelete.Remove(); } // Update the list to contain all merged cells greater than the deleted row index mergeCellsList = mergeCells.Elements<MergeCell>().Where(r => r.Reference.HasValue) .Where(r => GetRowIndex(r.Reference.Value.Split(':').ElementAt(0)) > rowIndex || GetRowIndex(r.Reference.Value.Split(':').ElementAt(1)) > rowIndex).ToList(); } // Either increment or decrement the row index on the merged cell reference foreach (MergeCell mergeCell in mergeCellsList) { string[] cellReference = mergeCell.Reference.Value.Split(':'); if (GetRowIndex(cellReference.ElementAt(0)) >= rowIndex) { string columnName = GetColumnName(cellReference.ElementAt(0)); cellReference[0] = isDeletedRow ? columnName + (GetRowIndex(cellReference.ElementAt(0)) - 1).ToString() : IncrementCellReference(cellReference.ElementAt(0), CellReferencePartEnum.Row); } if (GetRowIndex(cellReference.ElementAt(1)) >= rowIndex) { string columnName = GetColumnName(cellReference.ElementAt(1)); cellReference[1] = isDeletedRow ? columnName + (GetRowIndex(cellReference.ElementAt(1)) - 1).ToString() : IncrementCellReference(cellReference.ElementAt(1), CellReferencePartEnum.Row); } mergeCell.Reference = new StringValue(cellReference[0] + ":" + cellReference[1]); } } } } /// <summary> /// Updates all hyperlinks in the worksheet when a row is inserted or deleted. /// </summary> /// <param name="worksheetPart">Worksheet Part</param> /// <param name="rowIndex">Row Index being inserted or deleted</param> /// <param name="isDeletedRow">True if row was deleted, otherwise false</param> private static void UpdateHyperlinkReferences(WorksheetPart worksheetPart, uint rowIndex, bool isDeletedRow) { Hyperlinks hyperlinks = worksheetPart.Worksheet.Elements<Hyperlinks>().FirstOrDefault(); if (hyperlinks != null) { Match hyperlinkRowIndexMatch; uint hyperlinkRowIndex; foreach (Hyperlink hyperlink in hyperlinks.Elements<Hyperlink>()) { hyperlinkRowIndexMatch = Regex.Match(hyperlink.Reference.Value, "[0-9]+"); if (hyperlinkRowIndexMatch.Success && uint.TryParse(hyperlinkRowIndexMatch.Value, out hyperlinkRowIndex) && hyperlinkRowIndex >= rowIndex) { // if being deleted, hyperlink needs to be removed or moved up if (isDeletedRow) { // if hyperlink is on the row being removed, remove it if (hyperlinkRowIndex == rowIndex) { hyperlink.Remove(); } // else hyperlink needs to be moved up a row else{ hyperlink.Reference.Value = hyperlink.Reference.Value.Replace(hyperlinkRowIndexMatch.Value, (hyperlinkRowIndex - 1).ToString()); } } // else row is being inserted, move hyperlink down else { hyperlink.Reference.Value = hyperlink.Reference.Value.Replace(hyperlinkRowIndexMatch.Value, (hyperlinkRowIndex + 1).ToString()); } } } // Remove the hyperlinks collection if none remain if (hyperlinks.Elements<Hyperlink>().Count() == 0) { hyperlinks.Remove(); } } } /// <summary> /// Given a cell name, parses the specified cell to get the row index. /// </summary> /// <param name="cellReference">Address of the cell (ie. B2)</param> /// <returns>Row Index (ie. 2)</returns> public static uint GetRowIndex(string cellReference) { // Create a regular expression to match the row index portion the cell name. Regex regex = new Regex(@"\d+"); Match match = regex.Match(cellReference); return uint.Parse(match.Value); } /// <summary> /// Increments the reference of a given cell. This reference comes from the CellReference property /// on a Cell. /// </summary> /// <param name="reference">reference string</param> /// <param name="cellRefPart">indicates what is to be incremented</param> /// <returns></returns> public static string IncrementCellReference(string reference, CellReferencePartEnum cellRefPart) { string newReference = reference; if (cellRefPart != CellReferencePartEnum.None && !String.IsNullOrEmpty(reference)) { string[] parts = Regex.Split(reference, "([A-Z]+)"); if (cellRefPart == CellReferencePartEnum.Column || cellRefPart == CellReferencePartEnum.Both) { List<char> col = parts[1].ToCharArray().ToList(); bool needsIncrement = true; int index = col.Count - 1; do { // increment the last letter col[index] = Letters[Letters.IndexOf(col[index]) + 1]; // if it is the last letter, then we need to roll it over to 'A' if (col[index] == Letters[Letters.Count - 1]) { col[index] = Letters[0]; } else { needsIncrement = false; } } while (needsIncrement && --index >= 0); // If true, then we need to add another letter to the mix. Initial value was something like "ZZ" if (needsIncrement) { col.Add(Letters[0]); } parts[1] = new String(col.ToArray()); } if (cellRefPart == CellReferencePartEnum.Row || cellRefPart == CellReferencePartEnum.Both) { // Increment the row number. A reference is invalid without this componenet, so we assume it will always be present. parts[2] = (int.Parse(parts[2]) + 1).ToString(); } newReference = parts[1] + parts[2]; } return newReference; } </code></pre> <p>Also some additional pieces you will need:</p> <pre><code>/// <summary> /// Given a cell name, parses the specified cell to get the column name. /// </summary> /// <param name="cellReference">Address of the cell (ie. B2)</param> /// <returns>Column name (ie. A2)</returns> private static string GetColumnName(string cellName) { // Create a regular expression to match the column name portion of the cell name. Regex regex = new Regex("[A-Za-z]+"); Match match = regex.Match(cellName); return match.Value; } public enum CellReferencePartEnum { None, Column, Row, Both } private static List<char> Letters = new List<char>() { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ' }; </code></pre> |
3,573,600 | 0 | <p>Just use the <a href="http://api.jquery.com/css/" rel="nofollow noreferrer"><code>css</code></a> method:</p> <pre><code>$("ul").css("list-style-type", ""); $("li").css("margin", ""); $("li").css("line-height", ""); $("li").css("font", ""); </code></pre> |
30,923,677 | 0 | <p>Your error does not come from Comments but from the fact that you didn't select any "Language" in your BSF Listener.</p> <p>I tried it you can add comments in Beanshell for example using this syntax</p> <blockquote> <p>/** * test */</p> </blockquote> <p>Note there is also a "Comment" field in all elements.</p> |
1,634,644 | 0 | Create a class at runtime - Why do NSClassFromString AND objc_getclass return nil? <p>I've tried using both:</p> <pre><code>NSClassFromString and objc_getclass </code></pre> <p>to return a class, so I can create it at runtime, but both functions return nil for some classes, for example "TestClass". Note that NSClassFromString works for me for 99% of classes.</p> <p>If I add </p> <pre><code>[TestClass class]; </code></pre> <p>before I call NSStringFromClass or objc_getclass it, it works. and if I try to just create the class using a class reference, i.e.:</p> <pre><code>[TestClass alloc]; </code></pre> <p>it works too. So how can I force the class to load at runtime so NSClassFromString or objc_getclass will not return nil?</p> |
23,165,042 | 0 | Tracking Executing Threads <p>I am trying to figure out how I can track all the threads that my application is spawning. Initially, I thought I had it figured out using a CyclicBarrier, however I am seeing threads executing after my await call.</p> <p>Below is the working pseudo code:</p> <pre><code>public class ThreadTesterRunner { public static void main(String[] args) throws InterruptedException { final CyclicBarrier cb = new CyclicBarrier(1); ThreadRunner tr = new ThreadRunner(cb); Thread t = new Thread(tr, "Thread Runner"); t.start(); boolean process = true; // wait until all threads process, then print reports while (process){ if(tr.getIsFinished()){ System.out.println("Print metrics"); process = false; } Thread.sleep(1000); } } } class ThreadRunner implements Runnable { static int timeOutTime = 2; private ExecutorService executorService = Executors.newFixedThreadPool(10); private final CyclicBarrier barrier; private boolean isFinished=false; public ThreadRunner(CyclicBarrier cb) { this.barrier = cb; } public void run(){ try { boolean stillLoop = true; int i = 0; while (stillLoop){ int size; Future<Integer> future = null; try { future = executorService.submit(new Reader()); // sleeps size = future.get(); } catch (InterruptedException | ExecutionException ex) { // handle Errs } if(i == 3){ stillLoop = false; this.barrier.await(); this.isFinished=true; } //System.out.println("i = "+i+" Size is: "+size+"\r"); i++; } } catch (InterruptedException | BrokenBarrierException e1) { e1.printStackTrace(); } } public boolean getIsFinished(){ return this.isFinished; } } class Reader implements Callable { private ExecutorService executorService = Executors.newFixedThreadPool(1); @Override public Object call() throws Exception { System.out.println("Reading..."); Thread.sleep(2000); executorService.submit(new Writer()); return 1000; } } class Writer implements Callable { @Override public Void call() throws Exception { Thread.sleep(4000); System.out.println("Wrote"); return null; } } </code></pre> <p>Can anyone suggest a way to ONLY print "print metrics" after all threads have run?</p> |
44,532 | 0 | What is the best way to send html/image email? <p>Do you attach the images? </p> <p>Use absolute urls? </p> <p>How do you best avoid getting flagged as spam? </p> |
8,940,644 | 0 | jquery to hide txtbox <p>I want to hide my textbox-X in classic asp according to the date entered textbox-Y. textbox-X is in different asp page and textbox-Y in different page but both are contained in one base page default.asp i used the following condition and code to hide my textbox-Y, but in vein. </p> <pre><code>if (document.getElementById('txtAmount')) { alert("Inside first alert"); $("#txtPRAmount1").hide(); alert("Inside second alert"); } </code></pre> <p>here first alert fires and but second alert doesnt. please help me</p> |
14,943,596 | 0 | Strange / unstable behaviour on CreatePivotTable() <p>I am writing VBA code to automate some processes in Excel and I am encountering a very strange behavior for which I have not been able to find documentation / help.</p> <p>I have a procedure <code>MAJ_GF</code> that first executes function <code>GF.Update</code>, checks the result, and then launches procedure <code>GF.Build</code> (which basically takes the data obtained by <code>GF.Update</code> from different worksheets and does a bunch of stuff with it). </p> <p>At some point, this "bunch of stuff" requires using a pivot table, so <code>GF.Build</code> contains the following line:</p> <pre><code>Set pvt = ThisWorkbook.PivotCaches.Create(xlDatabase, _ "'source_GF'!R1C1:R" & j & "C" & k).CreatePivotTable("'TCD_GF'!R4C1", "GFTCD1") </code></pre> <p><strong>The strange behavior is this:</strong></p> <ul> <li>when I run <code>MAJ_GF</code>, VBA properly executes <code>GF.Update</code>, then launches <code>GF.Build</code>, and stops at the line described above complaining "Bad argument or procedure call"</li> <li>when I manually run <code>GF.Update</code>, then manually run <code>GF.Build</code>, everything goes smoothly and <code>GF.Build</code> does what it has to do from beginning to end with no errors</li> <li>even stranger, when I set a break-point on the incriminated line, run <code>MAJ_GF</code> then VBA pauses on the line as expected, and when I say "Continue"... it just continues smoothly and with no errors !</li> </ul> <p>I turned this around and around and around, double-checked the value of every variable, and this just makes no sense.</p> <p>Ideas anybody?</p> |
22,802,233 | 0 | Unset mysql_fetch_field object value MYSQL PHP <p>I have a code like this</p> <p>I have a stored procedure which will fetch all the info. But I want in my php view part to display only selected fields. How can I achieve that. Say for ex: the below code has three fields in db. S.No - BookName - Author Name If I want to unset a field value i.e. S.No - How can I do that</p> <p>I have tried the unset function like this. But dnt work unset($res->name->s_no);</p> <h1>Code</h1> <pre><code> <?php $pa_query = mysql_query("call booklist()"); while($i<mysql_num_fields($pa_query)){ $res=mysql_fetch_field($pa_query,$i); ?> <th><?php echo $res->name; ?></th> <?php $i=$i+1; } ?> </code></pre> <h1>Output</h1> <pre><code> S.No Book Name Author Name </code></pre> <h1>Expected Output</h1> <pre><code> Book Name Author Name </code></pre> |
22,552,361 | 0 | How to understand the `Net pruing` via complexity penalty <p>In Chapter6.10.3 'Net pruning', page53 of <strong>An introduction to neural networks __ Kevin Gurney</strong>. It introduce the <code>complexity penalty</code> into the back-propagation training algorithm. The <code>complexity penalty</code> is like as follow:</p> <p>$$ E_c=\sum_{i}w_i $$<br> $$ E = E_t + \lambda E_c $$ </p> <p><code>Et</code> is error used so far based on input-output differences.<br> Then performing gradient descent on this total risk E. </p> <p><strong>My question</strong> : After doing derivation. The <code>complexity penalty</code> will dissapear. How can it affect the training</p> |
26,514,805 | 0 | <p>1) Option one reduce li font size if client is ok with it font-size: 0.75em; </p> <p>This worked for me and you the search bar was fixed.</p> <p>2) Second option is to trim the text length. There is only so much u can fit in those tight cells.</p> <p>abt the news widget I don't see anything wrong.</p> |
23,551,257 | 0 | <p>In Shadow DOM land, this is called distribution. To distribute light DOM nodes into the shadow dom, you use <code><content></code> insertion points.</p> <p><a href="http://www.polymer-project.org/platform/shadow-dom.html#shadow-dom-subtrees">http://www.polymer-project.org/platform/shadow-dom.html#shadow-dom-subtrees</a></p> <p>It's quite literally a way to render nodes from light dom into placeholders in the shadow dom. If you want to do tricky things with the my-header/my-header-item title/name attributes, you can do something like this:</p> <pre><code><polymer-element name="my-header"> <template> <ul> <template repeat="{{item in items}}"> <li>{{item.name}}</li> </template> </ul> <content id="c" select="my-header-item"></content> </template> <script> Polymer('my-header', { domReady: function() { this.items = [].slice.call(this.$.c.getDistributedNodes()); } }); </script> </polymer-element> </code></pre> <p>Demo: <a href="http://jsbin.com/hupuwoma/1/edit">http://jsbin.com/hupuwoma/1/edit</a></p> <p>I have a more full-fledged tabs demo does this setup over on <a href="https://github.com/ebidel/polymer-experiments/blob/master/polymer-and-angular/together/elements/wc-tabs.html">https://github.com/ebidel/polymer-experiments/blob/master/polymer-and-angular/together/elements/wc-tabs.html</a>.</p> |
39,017,592 | 0 | <p>No string concatenation doesn't do any changes for localization, only String format does. </p> |
33,206,917 | 0 | <p>In this line : </p> <pre><code>Categories.Add(1, new Menuitem() { Name = "Menu1", Image = "Menu1Resource" }); </code></pre> <p>You are setting probably ResourceKey Menu1Resource to Image thinking that you will get an Image object.</p> <p>Do this : </p> <pre><code>Categories.Add(1, new Menuitem() { Name = "Menu1", Image = _getImgFromResKey("Menu1Resource") }); Image _getImgFromResKey(string key) { //access resource from res dictionary } </code></pre> <p>and finally <code><Image Source="{Binding Value.Image}"/></code></p> <p><a href="http://stackoverflow.com/questions/618648/how-can-i-access-resourcedictionary-in-wpf-from-c-sharp-code">How to get resource from Res Dictionary</a></p> |
24,065,916 | 0 | <p>To get a live stream, try switching <code>image2pipe</code> for <code>rawvideo</code>:</p> <pre><code>.fromFormat('rawvideo') .addInputOption('-pixel_format', 'argb') .addInputOption('-video_size', STREAM_WIDTH + 'x' + STREAM_HEIGHT) </code></pre> <p>This will encode the video at very low latency, instantly.</p> <p>You can remove <code>.fromFormat('image2pipe')</code> and <code>.addInputOption('-vcodec', 'mjpeg')</code>.</p> |
17,058,382 | 0 | StreamCorruptedException when connecting to a socket application over internet <p>I have created a chat room application using java sockets which worked well over the LAN at my class. But when I tried to connect it over the internet a StreamCorruptedException was thrown. When the error was thrown both client and server are connected to the internet using HSPA Modems(Because some one told me socket app will not work over ADSL). I searched for an answer and unfortunately I cannot fix this problem. Can you please look into this?</p> <p>Here's my code.</p> <p>1). Server :</p> <pre><code>import java.io.*; import java.util.*; import java.net.*; public class MyServer{ ArrayList<ClientListener> ctr; String uname; private static MyServer instance; public static void main(String asrgs[]){ MyServer server=MyServer.createInstance(); server.start(); } private MyServer(){ } public static MyServer getInstance(){ return instance; } public static MyServer createInstance(){ if(instance==null){ instance=new MyServer(); return instance; }else{ System.out.println("Server is already running"); return instance; } } public void broadcast(String msg, String uname){ for(int i=0;i<ctr.size();i++){ try{ if(ctr.get(i).uname!=uname){ ObjectOutputStream oostream=ctr.get(i).getOOS(); oostream.writeObject(msg+","+uname); } }catch(IOException ioE){ ioE.printStackTrace(); } } } public void start(){ //Start Server ctr=new ArrayList<ClientListener>(); ServerSocket myServer=null; try{ myServer=new ServerSocket(5008); }catch(Exception e){ System.out.println(e); System.exit(0); } //accept requests Socket socket=null; try{ while(true){ System.out.println("Waiting for a request..."); socket=myServer.accept(); ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); InetAddress inet=socket.getInetAddress(); uname=inet.getHostName(); ClientListener ct=new ClientListener(oos,ois,uname); ctr.add(ct); new Thread(ct).start(); System.out.println("User Connected"); //new ChatRoom(oos,ois).setVisible(true); } }catch(IOException e){ System.out.println("No client found.."); } } } </code></pre> <p>2) Client :</p> <pre><code>import java.net.*; import java.io.*; import java.util.*; class MyClient{ public static void main (String[] args){ Socket socket=null; try{ socket=new Socket(args[0],5008); System.out.println("server connected...."); ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); new ChatRoom(oos,ois).setVisible(true); System.out.println("Initiated...."); }catch(IOException e){ // System.exit(0); e.printStackTrace(); } } } </code></pre> <p>3). ClientListener :</p> <pre><code>import java.io.*; import java.util.*; import java.net.*; class ClientListener implements Runnable{ private Socket socket; ObjectOutputStream oos; ObjectInputStream ois; String uname; public ClientListener(Socket socket){ this.socket=socket; } public ClientListener(ObjectOutputStream oos, ObjectInputStream ois, String uname){ this.oos=oos; this.ois=ois; this.uname=uname; } public void run(){ Listen(); } private void Listen(){ while(true){ try{ String msg=(String)ois.readObject(); this.Write(msg,uname); }catch(IOException e){ //JOptionPane.showMessageDialog(this,e.getMessage()); }catch(ClassNotFoundException e){ //JOptionPane.showMessageDialog(this,e.getMessage()); } } } private void Write(String msg,String uname){ MyServer s=MyServer.getInstance(); s.broadcast(msg,uname); } public ObjectOutputStream getOOS(){ return this.oos; } public ObjectInputStream getOIS(){ return this.ois; } } </code></pre> <p>4). ChatRoom(GUI) for Clients:</p> <pre><code>import javax.swing.*; import java.awt.*; import java.io.*; import java.awt.event.*; class ChatRoom extends JFrame implements Runnable{ ObjectOutputStream oos; ObjectInputStream ois; JTextArea textArea; JTextField msgText; JButton sendButton; JMenuBar menubar; JMenu menu; ChatRoom(ObjectOutputStream oos, ObjectInputStream ois){ this.oos=oos; this.ois=ois; setSize(400,500); setResizable(false); setDefaultCloseOperation(3);//EXIT_ON_CLOSE setTitle("iChat"); textArea=new JTextArea(); textArea.setEditable(false); JScrollPane textPane=new JScrollPane(textArea); add("Center",textPane); JPanel southPane=new JPanel(new GridLayout(1,2)); msgText=new JTextField(); msgText.requestFocus(); msgText.addKeyListener(new KeyAdapter(){ public void keyReleased(KeyEvent evt){ if(evt.getKeyCode()==KeyEvent.VK_ENTER){ writeMessage(); } } }); southPane.add(msgText); sendButton=new JButton("Send"); sendButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ect){ writeMessage(); } }); southPane.add(sendButton); add("South",southPane); new Thread(this).start(); } private void writeMessage(){ String msg=msgText.getText(); try{ oos.writeObject(msg); textArea.append("Me : "+msg+"\n"); }catch(IOException e){ JOptionPane.showMessageDialog(this,e.getMessage()); } msgText.setText(null); } public void run(){ while(true){ try{ String token=(String)ois.readObject(); int marker=token.indexOf(","); String msg=token.substring(0,marker); String uname=token.substring(marker); textArea.append(uname+" : "+msg+"\n"); }catch(IOException e){ JOptionPane.showMessageDialog(this,e.getMessage()); }catch(ClassNotFoundException e){ JOptionPane.showMessageDialog(this,e.getMessage()); } } } } </code></pre> |
36,040,988 | 0 | How to detect swipe gesture in mvvmcross <p>I am using <code>mvvmcross</code> pattern. I have a list of datasets. I am showing only one dataset on the view. When user swipes either left or right, then I need to reload the view to show corresponding dataset. </p> <p>My dataset is big (around 100), I am afraid to use <code>viewpager</code>, it might be an issue in terms of memory.</p> <p>I have used the following approach before <a href="http://stackoverflow.com/questions/4139288/android-how-to-handle-right-to-left-swipe-gestures">Android: How to handle right to left swipe gestures</a>, but I wonder how to detect/implement <code>swipe gesture</code> in <code>mvvmcross</code> ?</p> |
23,456,461 | 0 | javascript not counting properly <p>So I have a timer pretty much, but it doesnt count seconds, it just counts up but not in the same speed as a normal second. The application works just fine, but as i said, it counts but it doesnt count in real seconds. So question is how to change the speed. I'm also adding hundreth of a second to this. </p> <pre><code> Timer { id:ticker interval: 100; running: false; repeat: true; onTriggered: point.countIn() } </code></pre> <p>Display:</p> <pre><code>import QtQuick 2.1 Rectangle { id : display width : 320 ; height: 280 color: "#fff" function countIn() { if (seconds == 59) { seconds = 0; countOut(); } else seconds++; } function reset() { seconds = 0; } property int seconds signal countOut property int pointSize : 80 function formatOutput() { if (seconds < 10) return '0' + seconds else return seconds } Text { text: formatOutput() font.pointSize: pointSize; font.bold: true font.family: "Courier" anchors.centerIn: parent } } </code></pre> |
7,648,509 | 0 | <p>Your <code>DataGridTextColumn.ElementStyle</code> should be targetted to a <code>TextBlock</code> and <strong>NOT <code>TextBox</code></strong>.</p> <pre><code><Style TargetType="TextBlock" x:Key="TextBlockStyle"> <Setter Property="VerticalContentAlignment" Value="Center"/> <Setter Property="HorizontalContentAlignment" Value="Center"/> </Style> </code></pre> <p>Your <strong><code>DataGridTextColumn.EditingElementStyle</code></strong> should be the one that targets a <code>TextBox</code> (if your data grid or column is editable)</p> <p>(Simply because readonly text cell has TextBlock and text cell in edit mode has a TextBox in it)</p> |
16,556,013 | 0 | <p>As also said in documentation, <a href="http://docs.jboss.org/hibernate/validator/4.2/api/org/hibernate/validator/constraints/NotBlank.html">@NotBlank</a> is for String type. There is no concept of java.util.Date being blank. It can be null or not null. </p> <blockquote> <p>Validate that the annotated string is not null or empty. The difference to NotEmpty is that trailing whitespaces are getting ignored.</p> </blockquote> <p>If goal is to check is value not null, <a href="http://docs.oracle.com/javaee/6/api/javax/validation/constraints/NotNull.html">@NotNull</a> should be used. According documentation:</p> <blockquote> <p>The annotated element must not be null. Accepts any type.</p> </blockquote> |
18,279,035 | 0 | <p>You can try something like this:-</p> <pre><code>if [[ ${file: -3} == ".gz" ]] </code></pre> |
18,700,478 | 0 | Set Row Height in JavaFX TableView <p>How can I set row Height in JavaFX table View? I tried to increase it by using css but this didn't work:</p> <pre><code>.table-row{ line-height: 50px; } </code></pre> <p>Is there any other way to solve this?</p> |
23,256,487 | 0 | <p>Log files don't have to contain only errors, but various types of messages. Those you pasted are debug messages. You could change <code>dev</code> environment configuration not to do it but I see no reason why would you. </p> <p>If you use your application in <code>prod</code> environment (without app_dev.php) debug messages won't be logged.</p> |
7,477,075 | 0 | <p>Well, when I changed the application pool "Identity" user of my web application from ApplicationPoolIdentity to LocalSystem, it worked. I suppose I could have also changed the user in the service (Control Panel > Services > ANTS Performance Profiler 6 Service) to some other user and used that user.</p> <p><img src="https://i.stack.imgur.com/LXXMd.jpg" alt="enter image description here"></p> <p>But then I get another error. As Kip says in Napolean Dynamite, "I love technology." </p> <p><img src="https://i.stack.imgur.com/cdJUv.jpg" alt="enter image description here"></p> <p><strong>Stack Trace in Details window:</strong></p> <pre><code>Could not start w3wp as the specified user. Win32 error code: 87 RedGate.Profiler.Engine.Startup.IIS.IISException stack trace: at ..StartProfilingIIS(String , String ) at RedGate.Profiler.Engine.Startup.IIS.IISStarter`1.StartProfilingIIS(String currentUserName, String subprocessVariableValue) at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs) at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext) rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at RedGate.Profiler.Engine.Startup.IIISActuator`1.StartProfilingIIS(String currentUserName, String subprocessVariableValue) </code></pre> <p><strong>After messing around with the error above for a bit, I tried unchecking this option, and it launched my default browser (which appears to be IE 9). Seems to be working now.</strong></p> <p><img src="https://i.stack.imgur.com/kft9N.jpg" alt="enter image description here"></p> |
25,448,170 | 0 | <p>You still only have about 16 significant decimal digits; this means that only the first 16 or so digits of the output are correct; and all of the remaining digits are likely wildly incorrect, and are not actually stored as part of the double-precision number. This is why adding 1 to the number doesn't do anything -- it's a change to one of the <em>insignificant</em> digits that isn't actually recorded.</p> |
18,104,603 | 0 | SA-MP (San Andreas Multiplayer) is a multiplayer mod for Grand Theft Auto San Andreas allowing users to play against each other over the internet or LAN. It makes use of the scripting language Pawn. |
32,599,071 | 0 | <p>Your response is likely being treated as HTML by the browser, which collapses line breaks (among plenty of other things). If you want your file to be displayed as-is, set the parameter <code>mimetype='text/plain'</code> on your flask <code>Response</code> object before returning it:</p> <pre><code>return Response(content, mimetype='text/plain') </code></pre> |
14,481,024 | 0 | <p>The values of the textbox is undefined - in PHP you are lookin for name_$i (with "_") and in javascript the names are without "_" (el.name = 'name' + i;)</p> <p>Also pay attention that in your javascript your loop starting from 1 (- in your php). The first client side row is comming from HTML but there you didn't put any index (name="name" instead of name="name_0"). It's better even not to fill the table with any row and just call the function (with i=0) when the page is loaded.</p> |
18,843,962 | 0 | <p>By definition, <code>SELECT</code> without <code>ORDER BY</code> is not deterministic, and implementation dependent. Server can decide to deliver your results in any order it thinks more performant.</p> <p>For example, if you delete some rows and later insert another set of rows, server may reuse that hole to put new data, and this data may be later delivered by SELECT in physical order on disk, not in order of insertion.</p> |
34,182,439 | 0 | <p>It may help to note that <code>comboPanel</code> is a <code>JPanel</code> having the default <code>FlowLayout</code>, which centers components based on the preferred sizes of the comboboxes. As a result, they "clump" together in the middle. Some alternatives:</p> <ul> <li><p>Specify a <code>GridLayout</code> having an extra column and use an empty component for the check column. The initial tableau will be aligned, although subsequent changes to the column widths will change that.</p> <pre><code>JPanel comboPanel = new JPanel(new GridLayout(0, annots.length + 1)); </code></pre></li> <li><p>Add a combobox to each relevant header using the approach shown <a href="http://stackoverflow.com/a/29963916/230513">here</a>, being mindful of the caveats adduced <a href="http://stackoverflow.com/a/7146216/230513">here</a>.</p></li> </ul> |
23,994,234 | 0 | How to terminate a server socket thread on timeout? <p>I'm using <code>Spring Integration</code> on the server side to offer a socket. The socket as a defined <code>soTimeout</code>, so that exceeding that timeout will close the current open socket connection to the client.</p> <pre><code>TcpConnectionFactoryFactoryBean fact = new TcpConnectionFactoryFactoryBean(); fact.setSoTimeout(timeout); </code></pre> <p>But the thread on the server side will continue. How can I force cancelation/termination of the server socket as well (maybe with an additional thread timeout, so that no thread can hang in the background by any issues)?</p> |
2,791,244 | 0 | <p>Try adding <code>filetype plugin on</code> before <code>syntax on</code> in your .vimrc.</p> |
14,325,496 | 0 | <p>Just tried it here, and I can't duplicate your experience. I'm guessing you have an unexpected or inconsistent view/controller hierarchy? Look at the controller of the table and scroll views' common superview. Anything fishy there? Remember: view controllers manage sets of <em>views</em>. Container view controllers manage other <em>view controllers</em> and have special rules (see: <a href="http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/Introduction/Introduction.html" rel="nofollow">The View Controller Programming Guide</a>, esp. <code>-addChildViewController:</code>, etc.).</p> <p>I'd suggest opening a blank project and trying to recreate the problem in its simplest possible form. If it's magically fixed, what's different? If it's still giving you trouble, send us a link so we can see the details of how you have things wired. </p> |
26,132,836 | 0 | <p>This is an issue with the simulator. On a device it'll work as expected.</p> |
28,954,043 | 0 | <p>Your <code>ready</code> event is incorrect.<br> The recommended way is:</p> <pre><code>$(document).ready(...); </code></pre> <p>Or this: (though <strong>not</strong> recommended by jQuery)</p> <pre><code>$().ready(...); </code></pre> <p>Or:</p> <pre><code>$(function() { ... }); </code></pre> <p><a href="http://api.jquery.com/ready/" rel="nofollow">http://api.jquery.com/ready/</a></p> |
2,512,704 | 0 | <p>Redis is not <em>usually</em> deployed as a "durable" datastore (in the sense of the "D" in ACID.), even with journaling. Most use cases intentionally sacrifice a little durability in return for speed.</p> <p>However, the "append only file" storage mode can optionally be configured to operate in a durable manner, at the cost of performance. It will have to pay for an <a href="http://en.wikipedia.org/wiki/Sync_%28Unix%29" rel="nofollow noreferrer">fsync()</a> on every modification. To configure this, set these two options in your .conf file:</p> <pre><code> appendonly yes appendfsync always </code></pre> <p>From the docs: <a href="http://code.google.com/p/redis/wiki/AppendOnlyFileHowto#How_durable_is_the_append_only_file?" rel="nofollow noreferrer">How durable is the append only file?</a></p> <blockquote> <p>Check redis.conf, you can configure how many times Redis will fsync() data on disk. There are three options:</p> <ul> <li>Fsync() every time a new command is appended to the append log file. Very very slow, very safe.</li> <li>Fsync() one time every second. Fast enough, and you can lose 1 second of data if there is a disaster. </li> <li>Never fsync(), just put your data in the hands of the Operating System. The faster and unsafer method.</li> </ul> </blockquote> <p><em>(Note that the default for appendfsync in the configuration file shipping with Redis post-2.0.0 is <code>everysec</code>, and not <code>always</code>.)</em></p> |
34,334,752 | 0 | <p>For stuff like that, regular expressions are your friend:</p> <pre><code>String text = "Hello world #computerScience"; text = text.replaceAll("(#\\w+)", "ANSI_YELLOW$1ANSI_RESET"); // Hello world ANSI_YELLOW#computerScienceANSI_RESET String text = "Hello world #java #color #hashtag"; text = text.replaceAll("(#\\w+)", "ANSI_YELLOW$1ANSI_RESET"); // Hello world ANSI_YELLOW#javaANSI_RESET ANSI_YELLOW#colorANSI_RESET ANSI_YELLOW#hashtagANSI_RESET </code></pre> |
14,410,056 | 0 | Should I call File.Exists before calling File.Delete? <p>I have a <code>File.Delete</code> in my finally clause like so:</p> <pre><code>finally { //remove the temporary file if(File.Exists(transformedFile)) File.Delete(transformedFile); } </code></pre> <p>According to the <a href="http://msdn.microsoft.com/en-us/library/system.io.file.delete.aspx">C# documentation</a>, calling File.Delete on a nonexistent file will not throw any exceptions. </p> <p>Is it okay to remove the <code>File.Exists</code> wrapped, or will that expose me to possible additional exceptions?</p> |
17,227,875 | 0 | How to put animate heading and image with wowslider <p>I'm trying to user Wow slider to create a carousel. Right now I'm only able to fadein/fadeout 3 images with it. What I want to do is also have a heading and a smaller image to animate on top of each of those 3 images. </p> <p>For example, when a user clicks 'next', the current image fades out and the next image fades in. At this point I want a heading to slide from the right and another smaller image to fade in; each in their own positions.</p> <p>Basically, I want something like this: <a href="http://cleancanvas.herokuapp.com/" rel="nofollow">http://cleancanvas.herokuapp.com/</a></p> <p>Can you please help me with this, as my experience with jquery or plugins is really limited.</p> <p>Thank you very much.</p> |
34,087,329 | 0 | Categorical and ordinal feature data representation in regression analysis? <p>I am trying to fully understand difference between categorical and ordinal data when doing regression analysis. For now, what is clear:</p> <p><strong>Categorical feature and data example:</strong><br> Color: red, white, black <br> Why categorical: <code>red < white < black</code> is logically <strong>incorrect</strong></p> <p><strong>Ordinal feature and data example:</strong><br> Condition: old, renovated, new <br> Why ordinal: <code>old < renovated < new</code> is logically <strong>correct</strong></p> <p><strong>Categorical-to-numeric and ordinal-to-numeric encoding methods: <br></strong> One-Hot encoding for categorical data <br> Arbitrary numbers for ordinal data</p> <p><strong>Categorical data to numeric:</strong></p> <pre><code>data = {'color': ['blue', 'green', 'green', 'red']} </code></pre> <p>Numeric format after One-Hot encoding:</p> <pre><code> color_blue color_green color_red 0 1 0 0 1 0 1 0 2 0 1 0 3 0 0 1 </code></pre> <p><strong>Ordinal data to numeric:</strong></p> <pre><code>data = {'con': ['old', 'new', 'new', 'renovated']} </code></pre> <p>Numeric format after using mapping: Old < renovated < new → 0, 1, 2</p> <pre><code>0 0 1 2 2 2 3 1 </code></pre> <p>In my data I have 'color' feature. As color changes from white to black price increases. From above mentioned rules I probably have to use one-hot encoding for categorical 'color' data. But why I cannot use ordinal representation. Below I provided my observations from where my question arised.</p> <p>Let me start with introducing formula for linear regression: <a href="https://i.stack.imgur.com/mbiK6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mbiK6.jpg" alt="enter image description here"></a> <br>Let have a look at data representations for color: <a href="https://i.stack.imgur.com/Veb54.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Veb54.jpg" alt="enter image description here"></a> Let's predict price for 1-st and 2-nd item using formula for both data representations:<br> <strong>One-hot encoding:</strong> In this case different thetas for different colors will exist. I assume that thetas already derived from regression (20, 50 and 100). Prediction will be: </p> <pre><code>Price (1 item) = 0 + 20*1 + 50*0 + 100*0 = 20$ (thetas are assumed for example) Price (2 item) = 0 + 20*0 + 50*1 + 100*0 = 50$ </code></pre> <p><strong>Ordinal encoding for color:</strong> In this case all colors will have 1 common theta but my assigned multipliers (10, 20, 30) differ:</p> <pre><code>Price (1 item) = 0 + 20*10 = 200$ (theta assumed for example) Price (2 item) = 0 + 20*20 = 400$ (theta assumed for example) </code></pre> <p>In my model White < Red < Black in prices. Seem to be that correlation works correctly and it is logical predictions in both cases. For ordinal and categorical representations. So I can use any encoding for my regression regardless of the data type (categorical or ordinal)? This division in data representations is just a matter of conventions and software-oriented representations rather than a matter of regression logic itself?</p> |
34,438,542 | 0 | <p>As alternative you can use <em>Retrofit</em>.</p> <p>You can specify a call like this:</p> <pre><code>@Multipart @POST("/user/photo") Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description); </code></pre> <p>then create it like this:</p> <pre><code>Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .build(); GitHubService service = retrofit.create(GitHubService.class); </code></pre> <p>and finally execute it like this:</p> <p><code>service.updateUser(Photo, description).enqueue()</code> --> <strong>asynchronous</strong></p> <p><code>service.updateUser(Photo, description).execute()</code> --> <strong>synchronous</strong></p> <p>See the documentation <a href="http://square.github.io/retrofit/" rel="nofollow">here</a></p> |
5,344,542 | 0 | <p>Use this html tag </p> <pre><code>align="center" </code></pre> <p>center can be substituted for left or right if you want not to position them on the center</p> <p>The proper way to do it is by linking your html to a CSS file and assign each div to a certain type of class in the CSS file, this helps you avoid redundancy. To do so create a css file and link it to the html by including this in your html code </p> <pre><code><head> <link rel="stylesheet" type="text/css" href="mystyle.css" /> </head> </code></pre> <p>And then in your mystyle.css file you would have to include something like this</p> <pre><code>DIV.Left{text-align:left;} DIV.Center{text-align:center;} DIV.Right{text-align:right;} </code></pre> <p>Then your html file divs would look like</p> <pre><code><div class="left"></div> <div class="center"></div> <div class="right"></div> </code></pre> |
14,482,392 | 0 | <p>wrap your two commands in function so you will have just one call ?</p> <pre><code>function add-log{ (param $txt) $DateTime = get-date | select -expand datetime Add-Content $LogFile -Value "$DateTime: $txt" } </code></pre> |
26,374,998 | 0 | <p>You may want to use a different event that satisfies your condition:</p> <p>SplitContainer Class: <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.splitcontainer(v=vs.110).aspx" rel="nofollow">MSDN</a> SplitContainer Event: <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.onmouseclick(v=vs.110).aspx" rel="nofollow">OnMouseClick</a></p> <p>try subscribing to that event if you want it to be fired on click only, also, if you want to unsubscribe to an event, use the <strong>-=</strong> tag.</p> |
37,436,717 | 0 | Binding data to grid view <p>Trying to bind a table to data grid. I dont see why the following code is not working. </p> <pre><code>private void Form1_Load(object sender, EventArgs e) { SqlConnection sqlConn = new SqlConnection("MyConnectionString"); string select = "SELECT CategoryId, CategoryName, Description FROM dbo.Categories"; SqlDataAdapter dataAdapter = new SqlDataAdapter(select, sqlConn); SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter); DataTable dt = new DataTable(); dt.Locale = System.Globalization.CultureInfo.InvariantCulture; dataAdapter.Fill(dt); dataGridView1.ReadOnly = true; //dataGridView1.DataSource = dt; dataGridView1.DataSource = northwindDataSetBindingSource; dataGridView1.AutoResizeColumns( DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); } </code></pre> |
18,786,295 | 0 | <p>It looks that you have just many php scripts without one cetral that manage the other scripts. So you have to start every script with </p> <pre><code><?php session_start(); ... </code></pre> <p>Or the session will not work properly.</p> |
31,256,206 | 0 | C++ memory alignment <p>So I read that when variables are declared in c++ if you want to get the optimum cache reads the memory should stick to its natural alignment. Example:</p> <pre><code>int a; // memory address should end in 0x0,0x4,0x8,0xC int b[2]; // 8 bytes 0x0,0x8 int b[4]; // 16 bytes 0x0 </code></pre> <p>But in practice these variables do not follow the "natural alignment" rules, a 16 byte variable was residing at a memory address that ended in 0xC. Why is this ?</p> |
28,668,365 | 0 | Initialize a class property <p>Is there a way to initialize a PHP class property from another class property? I have a series of properties I'd like to depend upon each other for easy modification of the root value:</p> <p></p> <pre><code>class Anon { private static $a = 5; private static $b = '+' . (2 * self::$a); } </code></pre> <p>However, this causes a syntax error. I've had trouble searching for this, but I haven't seen anybody trying to do this!</p> |
21,302,020 | 0 | using jquery minicolors in angular.js <p>I am trying to incorporate jquery minicolors in an angular directive.The directive is binded to a textbox with ngModel. When I type the color code,the changed value is detected by the watch,but when I select it using colorpicker,the value is not reflected in the scope variable.Can any one tell me what am I doing wrong?</p> <pre><code><input minicolors="colorPickerSettings" type="text" data-ng-model="category.ToBeConfirmedEventColor"> angular. module('myApp', []) .directive('minicolors', function () { return { require: 'ngModel', restrict: 'A', link: function (scope, element, attrs, ngModel) { //gets the settings object var getSettings = function () { return angular.extend({}, scope.$eval(attrs.minicolors)); }; //init method var initMinicolors = function () { // debugger if (!ngModel) { return; } var settings = getSettings(); //initialize the starting value, if there is one ngModel.$render = function () { if (!scope.$$phase) { //not currently in $digest or $apply scope.$apply(function () { var color = ngModel.$viewValue; element.minicolors('value', color); }); } }; // If we don't destroy the old one it doesn't update properly when the config changes element.minicolors('destroy'); // Create the new minicolors widget element.minicolors(settings); // Force a render to override whatever is in the input text box ngModel.$render(); }; // Watch model for changes and then call init method again if any change occurs scope.$watch(getSettings, initMinicolors, true); } }; }); </code></pre> |
2,065,439 | 0 | <pre><code>$sxe->addChild("date", $date); </code></pre> |
38,704,327 | 0 | <p>var questionID = $(this)[0].id </p> <p>This worked for me! </p> |
23,340,283 | 0 | <p>Are you meaning that you want the text values of all checked checkboxes, or the text value of every checkbox, or...?</p> <p>Either way, you want to iterate through the Page's Controls collection to find all controls that have a type of Checkbox and then use that to get their text values (and you can limit whether you want to include checked boxes or not in that iteration). And, yes, using a List might be easier than starting with an array, because you can easily add to a List<> and then transform it into an array with little pain.</p> |
10,722,948 | 0 | <p>You could use background subtraction. This would involve having the empty car park image as your background and then doing a comparison of the changes between that and any subsequent images. If you are looking at car parking spaces then you would want to split the image up into sectors(car park spaces) and do the background subtraction per sector. However due to constant changes in lighting of the carpark as the sun moves you are going to run into issues where the background image will change due to shadows, brightness,etc. An approach to handle this is to do frame by frame comparisons and if it changes by a certain threshold then it is most likely a car has parked rather than the sun has moved as the car will cause a much higher amount of change in a short space of time than the effects of lighting will.</p> |
12,721,334 | 0 | How to set all pages of a subdomain to redirect to a single page? <p>Let's say my domain name is <strong>website123.com</strong> and I have a subdomain of <strong>my.website123.com</strong></p> <p>I've deleted the "my" subdomain from the site and want to make sure that anyone that goes to any page with a my.website123.com URL is redirected to the main www.website123.com URL. The "my" subdomain has a ton of pages of it, so I need to make sure that regardless of which page a user goes to on the "my" subdomain, that they're redirected to the site's main index page.</p> <p>I was thinking to get this accomplished through .htaccess - is that the best way? If yes how?</p> |
21,862,704 | 0 | <p>It sounds like you want to use something like <a href="https://github.com/onevcat/VVDocumenter-Xcode" rel="nofollow">VVDocumenter</a>. </p> <p>From their Github page:</p> <blockquote> <p>Writing document is so important for developing, but it is really painful with Xcode. Think about how much time you are wasting in pressing '*' or '/', and typing the parameters again and again. Now, you can find the method (or any code) you want to document to, and type in ///, the document will be generated for you and all params and return will be extracted into a Javadoc style, which is compatible with appledoc, Doxygen and HeaderDoc. You can just fill the inline placeholder tokens to finish your document.</p> </blockquote> |
32,064,909 | 0 | <p>Add new <code>static</code> class and define your extension methods inside it. Check out <a href="https://msdn.microsoft.com/en-IN/library/bb383977.aspx">MSDN documentation</a> for Extension methods.</p> <pre><code> namespace TrendsTwitterati { public partial class Default: System.Web.UI.Page { } public static class MyExtensions { public static IEnumerable < TSource > DistinctBy < TSource, TKey > (this IEnumerable < TSource > source, Func < TSource, TKey > keySelector) { HashSet < TKey > seenKeys = new HashSet < TKey > (); foreach(TSource element in source) { if (seenKeys.Add(keySelector(element))) { yield return element; } } } } } </code></pre> |
39,736,461 | 0 | <p>The easiest way to compare json strings is using <code>JSONCompare</code> from <a href="https://github.com/skyscreamer/JSONassert" rel="nofollow">JSONAssert</a> library. The advantage is, it's not limited to structure only and can compare values if you wish:</p> <pre><code>JSONCompareResult result = JSONCompare.compareJSON(json1, json2, JSONCompareMode.STRICT); System.out.println(result.toString()); </code></pre> <p>which will output something like:</p> <pre><code>Expected: VALUE1 got: VALUE2 ; field1.field2 </code></pre> |
32,851,883 | 0 | How can I show items specific to a selected dropdown option? <p>I have a dropdown list of games, and depending on which game you select, it should show a list of things I need to do for that game. My problem is getting the list to show the steps for only the currently selected game. Can this be done with ng-model, will I need to use functions, or is there an even simpler way to do this? </p> <p>Also, is there any information I've included in my sample that would become redundant after utilizing provided suggestions?</p> <p><strong>HTML</strong></p> <pre><code><select> <option ng-repeat="game in things.toBeat">{{ game.title }}</option> </select> <ul> <li ng-repeat="step in things.toDo">{{ step.todo }}</li> </ul> </code></pre> <p><strong>JS</strong></p> <pre><code>var games = [ { "id" : "0", "title" : "Super Mario Bros." }, { "id" : "1", "title" : "Pac-man" } ]; var todos = [ { "gameID" : "0", "todo" : "Collect coins" }, { "gameID" : "0", "todo" : "Rescue princess" }, { "gameID" : "1", "todo" : "Eat dots" }, { "gameID" : "1", "todo" : "Eat fruit" } ]; $scope.things = { "toBeat" : games, "toDo" : todos }; </code></pre> |
19,250,774 | 0 | <p>Have you considered using the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.transfer%28v=vs.100%29.aspx" rel="nofollow">Server.Transfer</a> to redirect the query to the required url?</p> <p>Simply use</p> <pre><code>Server.Transfer("Page2.aspx", true); </code></pre> |
33,469,734 | 0 | <p>The format file is describing the source data not the destination. When you use <code>-c</code> or <code>datafiletype='char'</code> your input datatypes must be SQLCHAR. Native datatypes are only valid when using <code>-n</code> or <code>datafiletype='native'</code>. A source file in native format is always binary so bcp needs to know the data type of each field in order to read the correct amount of bytes and interpret them correctly.</p> |
33,282,395 | 0 | <p>It seems that what you want to do is to split that Comment column into it's on data stream?</p> <p>After the transpose, you can crosstab into a form that contains the products as headers and the dates and comments as individual rows. Then a filter can pull the comment row out. A sort on the Name field would also let you grab the last row in that dataset to know which one was the last date.</p> <p>For the crosstab:<br> - Grouping Fields: Name<br> - Header Field: Product<br> - Data Field: Value</p> <p>Methodologies: Concatenate</p> |
885,727 | 0 | <p>Be careful about assuming that int operations are always faster than float operations. In isolation they may be, but <a href="http://assemblyrequired.crashworks.org/2009/01/12/why-you-should-never-cast-floats-to-ints/" rel="nofollow noreferrer">moving data between a float register and an int register is shockingly slow on modern processors</a>. So once your data is on a float, you should keep it on a float for further computation.</p> |
11,836,093 | 0 | <p>I am going to take the lack of responses as an implicit 'no'. If anyone is interested, I am planning my own postgres spin off with dynamic multi-peer replication support within the next year.</p> |
21,894,655 | 0 | <p>To complement the answer from Seyyed, and assuming these files are not too big: </p> <p>You can have one kml file for each area, and then build a simple "global" file, referencing all these area files with a "NetworkLink" (look at to KML Reference if needed for the syntax). </p> |
12,528,369 | 0 | node.js return to client waiting for event <p>I'm playing around a bit with the concept of Comet on node.js, but I'm still a bit confused and I'm wondering if anyone here can point me in the right direction.</p> <p>Think on a game app where client code should ask for it's turn to make a move (for example on a chess app). What I'm thinking here is in use something like this:</p> <p>When match starts a method on the node server is called to create an element on a matches array with the id of the match and the initial player.</p> <p>When a player makes a move a method is called to update the current player on the array element referencing this match. This method should fire an event when the change occurs.</p> <p>Before being able to make any move, client code should call a method on the server that checks if it's the turn of the user and that waits for the changing player event if wasn't it's turn.</p> <p>I'm not sure if this is a good approach within the event loop, and if it is I don't see how can I make the method to wait until event to return.</p> <p>Any suggestions?</p> |
3,263,381 | 0 | Check if jQuery or mooTools are loaded <p>In my project I am using <code>jQuery</code> in client side and <code>mooTools</code> in admin side. I would like to be able to write some part of code (google maps functions, etc) which will be common for both of that libraries.</p> <p>Is it possible to check if <code>jQuery</code> or <code>mooTools</code> libraries are loaded and use proper behaviours ?</p> <p><code>$(document).ready(function() {});</code> or <code>window.addEvent('domready', function(){});</code></p> <p><code>$('#id');</code> or <code>$('id');</code></p> <p><code>$('googleMapLocalize').addEvent('click', function(){});</code> or <code>$('googleMapLocalize').bind('click', function(){});</code></p> <p>What is the best way ?</p> |
Subsets and Splits