pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
5,511,715
1
Python - Understanding error: IndexError: list index out of range <p>I'm fairly new to python. I have an error that I need to understand.</p> <p>The code:</p> <p>config.py:</p> <pre><code># Vou definir os feeds feeds_updates = [{"feedurl": "http://aaa1.com/rss/punch.rss", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa2.com/rss.xml", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa3.com/Heaven", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa4.com/feed.php", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa5.com/index.php?format=feed&amp;type=rss", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa6.com/rss.xml", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa7.com/?format=xml", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa8/site/component/rsssyndicator/?feed_id=1", "linktoourpage": "http://www.ha.com/fun.htm"}] </code></pre> <p>twitterC.py</p> <pre><code># -*- coding: utf-8 -*- import config # Ficheiro de configuracao import twitter import random import sqlite3 import time import bitly_api #https://github.com/bitly/bitly-api-python import feedparser ... # Vou escolher um feed ao acaso feed_a_enviar = random.choice(config.feeds_updates) # Vou apanhar o conteudo do feed d = feedparser.parse(feed_a_enviar["feedurl"]) # Vou definir quantos feeds quero ter no i i = range(8) print i # Vou meter para "updates" 10 entradas do feed updates = [] for i in range(8): updates.append([{"url": feed_a_enviar["linktoourpage"], "msg": d.entries[i].title + ", "}]) # Vou escolher ums entrada ao acaso print updates # p debug so update_to_send = random.choice(updates) print update_to_send # Para efeitos de debug </code></pre> <p>And the error that appears sometimes because of the nature of the random:</p> <pre><code>Traceback (most recent call last): File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 77, in &lt;module&gt; updates.append([{"url": feed_a_enviar["linktoourpage"], "msg": d.entries[i].title + ", "}]) IndexError: list index out of range </code></pre> <p>I'am not getting to the error, the list "feeds_updates" is a list with 8 elements, I think is well declareted and the RANDOM will choose one out of the 8...</p> <p>Can someone give me a clue on what is happenning here?</p> <p>PS: Sorry for my bad english.</p> <p>Best Regards,</p>
9,897,440
0
<p>As suggested, I have tried this and the fork is private</p>
37,353,452
0
<p>I'd like to help, but I'm not quite sure I understand your question. Given the information you have here, that code should work. The only unknown is the actual datatype of the value of the combo, but unless the <code>.Field(Of T)</code> is throwing an InvalidCastException, you should be good there. I wrote the following code and threw it into a unit test project, and everything came out good . . . at least with regard to the length of the resulting set of data.</p> <h2>Code</h2> <pre><code>&lt;TestCase(0, ExpectedResult:=4)&gt; &lt;TestCase(1, ExpectedResult:=4)&gt; &lt;TestCase(2, ExpectedResult:=3)&gt; &lt;TestCase(3, ExpectedResult:=2)&gt; &lt;TestCase(4, ExpectedResult:=1)&gt; &lt;TestCase(5, ExpectedResult:=0)&gt; Public Function tmptest(ByVal selected As Integer) As Integer Dim d As New DataTable d.Columns.Add(New DataColumn("id", GetType(Integer))) For j = 0 To 5 Dim r = d.NewRow() r("id") = j d.Rows.Add(r) Next If selected = 0 Then selected = 1 Dim query = From status In d.AsEnumerable() Where status.Field(Of Integer)("id") &gt; selected Select status Return query.Count End Function </code></pre> <h2>Results</h2> <p><a href="https://i.stack.imgur.com/alHkE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/alHkE.jpg" alt="Test Results"></a></p>
29,533,891
0
google-apps-script multiple criteria writing over headers <p>I have taken a bit of script from Serge which is great (original <a href="http://stackoverflow.com/questions/25038715/google-apps-script-copy-row-from-table-if-value-in-table-meets-condition">link here</a>. I have added in a second criteria to exclude certain rows and it works great except, if there is not header in the sheet being copied to, it will not work (error: "The coordinates or dimensions of the range are invalid.") and if I enter a header or some other data, it overwrites it. Can anyone assist please? I have also found that is there is no match to the criteria I get following message "TypeError: Cannot read property "length" from undefined."</p> <p>Also, what change would I need to make to change the cell 'dataSheetLog[i][12]' to the status variable, i.e. "COPIED" after I have copied it across. I have tried writing a setValue line but it is obviously the wrong instruction for that syntax.</p> <p>Code is:</p> <pre><code> { var Spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var sheetLog = Spreadsheet.getSheetByName("LOG"); var sheetMaint = Spreadsheet.getSheetByName("MAINTENANCE"); var Alast = sheetLog.getLastRow(); var criteria = "08 - Maintenance" var status = "COPIED" var dataSheetLog = sheetLog.getRange(2,1,Alast,sheetLog.getLastColumn()).getValues(); var outData = []; for (var i in dataSheetLog) { if (dataSheetLog[i][2]==criteria &amp;&amp; dataSheetLog[i][12]!=status){ outData.push(dataSheetLog[i]); } } sheetMaint.getRange(sheetMaint.getLastRow(),1,outData.length,outData[0].length).setValues(outData); } </code></pre>
20,022,466
0
<p>You need to initialise the <code>dwSize</code> member of <code>CONSOLE_CURSOR_INFO</code>:</p> <pre><code>CONSOLE_CURSOR_INFO CURSOR; CURSOR.dwSize = 1; CURSOR.bVisible = FALSE; </code></pre> <p>From the docs for <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms686019%28v=vs.85%29.aspx" rel="nofollow">SetConsoleCursorInfo</a>:</p> <blockquote> <p>The dwSize member of the CONSOLE_CURSOR_INFO structure specifies the percentage of a character cell that is filled by the cursor. If this member is less than 1 or greater than 100, SetConsoleCursorInfo fails.</p> </blockquote> <p>Note also from the same page</p> <blockquote> <p>Return value</p> <p>If the function succeeds, the return value is nonzero. <br>If the function fails, the return value is zero. To get extended error information, call GetLastError.</p> </blockquote> <p>Checking the return value would have helped you figure out what was going wrong.</p>
19,006,197
0
IIS NullReferenceException when deployed but not in Dev Server <p>I have developed an IIS Application using C# code behind ASPX pages with entity framework for database access. When I run it in the Visual Studio Development Server it works fine but if I either Publish it to IIS or run it on the Local IIS Web Server from Visual Studio (which is pretty much the same as Publishing I guess) I get</p> <pre><code>NullReferenceException: Object reference not set to an instance of an object.] System.Web.Hosting.RecyclableCharBuffer.Append(String s) +15 System.Web.Hosting.ISAPIWorkerRequest.SendUnknownResponseHeader(String name, String value) +93 System.Web.HttpResponse.WriteHeaders() +233 System.Web.HttpResponse.Flush(Boolean finalFlush) +219 System.Web.HttpRuntime.FinishRequest(HttpWorkerRequest wr, HttpContext context, Exception e) +127 </code></pre> <p>This Exception is thrown after my Home.aspx has finished it's Page Load. Some simple ASPX pages work ok. Setting a NullReferenceException break point just drops into disassembly.</p> <p>I am stuck for ideas about how to track this issue down. Any thoughts???</p>
465,726
0
<p>Here's a solution for php:</p> <pre><code>function make_uri($input, $max_length) { if (function_exists('iconv')) { $input = @iconv('UTF-8', 'ASCII//TRANSLIT', $input); } $lower = strtolower($input); $without_special = preg_replace_all('/[^a-z0-9 ]/', '', $input); $tokens = preg_split('/ +/', $without_special); $result = ''; for ($tokens as $token) { if (strlen($result.'-'.$token) &gt; $max_length+1) { break; } $result .= '-'.$token; } return substr($result, 1); } </code></pre> <p>usage:</p> <pre><code>echo make_uri('In C#: How do I add "Quotes" around string in a ...', 500); </code></pre> <p>Unless you need the uris to be typable, they don't need to be small. But you should specify a maximum so that the urls work well with proxies etc.</p>
16,343,319
0
<p>Thank you! I have an embedded TextEdit in the last row of ListView embedded in the alert dialog fragment. I used your solution of clearing the flags as a post runnable and now it works perfectly.</p> <pre><code> @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle("My Title"); m_adapter = new MyAdapter(getContext()); builder.setAdapter(m_adapter, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); final AlertDialog dialog = builder.create(); final ListView listView = dialog.getListView(); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { } }); listView.post(new Runnable() { @Override public void run() { dialog.getWindow().clearFlags( WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); } }); return dialog; } </code></pre>
3,860,789
0
<p>How about watching for if/when the <code>/usr/sbin/spindump</code> process starts up?</p>
11,861,168
0
<p><code>extern</code> declares a variable, but does not define it. It basically tells the compiler there is a definition for <code>x</code> somewhere else. To fix add the following to <code>header.c</code> (or some other <code>.c</code> file but <em>only</em> one <code>.c</code> file):</p> <pre><code>int x; </code></pre> <p>Note that in <code>main()</code> the local variable <code>x</code> will hide the global variable <code>x</code>.</p>
21,319,479
0
<p>I did something like this years ago in VB6. Copied below is the code. As you can see, the code just steps through the HTML character-by-character and removes everything between (and including) the &lt; and > tags. Hopefully you can do something similar in whatever tool you are using.</p> <pre><code>Function CleanTags(HTML As String) As String Dim result As String, b As Boolean, c As String, i As Long b = False For i = 1 To Len(HTML) c = Mid(HTML, i, 1) If c = "&lt;" Then b = True If b = False Then result = result &amp; c If c = "&gt;" Then b = False Next i CleanTags = result End Function </code></pre>
32,928,102
0
<ol> <li><p>This is <code>C</code> not <code>C++</code> (eventhough C++ brings enough <code>C</code> compatibility to make that code valid using a conforming C++ compiler with <code>#include &lt;stdio.h&gt;</code>).</p></li> <li><p>The specifier <code>%c</code> is for characters. You're reading and writing <code>int</code>. </p></li> </ol> <p>Thus, you should use <code>%i</code>.</p> <pre><code>int a; int b; printf("a"); scanf("%i", &amp;a); printf("b"); scanf("%i", &amp;b); a=a+b; printf("%i", a); </code></pre> <p>Output</p> <pre><code>a5 b7 12 </code></pre>
6,165,249
0
<p>You have to loop, or use a library call.</p> <p>One option would be <code>memcpy(kk, k, sizeof(k));</code>. For this you must <code>#include &lt;string.h&gt;</code>.</p>
17,955,241
0
<p>Because you are using strings rather than parameters, your example is vulnerable to SQL injection. It's best to avoid <code>pg_</code> functions. In your case there are two things you need to take into account:</p> <ul> <li>Learn the Drupal API (considering you are using Drupal this would be the best for code consistency</li> </ul> <p>or</p> <ul> <li>Use <a href="http://www.postgresql.org/docs/9.2/static/plpgsql.html">stored procedures</a></li> <li>Use a library like <a href="http://php.net/manual/en/ref.pdo-pgsql.php">PDO</a> or <a href="http://php.net/manual/en/function.pg-query-params.php">pg_query_params</a> which takes care of <a href="http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html#4.1">parameterized queries</a></li> </ul> <p>Normally you use stored procedures in addition to PDO, unfortunately sometimes this is not manageable because you have too much code. My advice is to use as much stored procedures as possible.</p>
20,735,476
0
Send a bean with html:link tag <p>I wanna send an object(bean) using the tag as follows:</p> <p>JSP:</p> <pre><code> &lt;logic:iterate id="demande" name="demandes"&gt; &lt;html:link page ="/show.do" paramId="demande" paramName="demande"&gt; &lt;bean:write name="demande" property="demandeId" /&gt;&lt;br&gt; &lt;/html:link&gt; &lt;/logic:iterate&gt; </code></pre> <p>What can I do to retrieve the bean (demande) in the controller side?</p>
36,856,137
0
where can Find sqlite databases in spip? <p>I would like to recover the SQLite database directories in the framework spip order after applying a script that will give me the equivalent mysql but I do not know the name of the file containing the data base sqlite Can you help me ?</p>
29,290,611
0
<p><code>ans += s;</code> create a new string and assigns it back to <code>ans</code> so it could be the garbage collector.</p>
15,043,393
0
Unexplained heroku timeouts <p>I have a rails 3.2.11 app deployed on Heroku that has been fairly stable over time. In the last 24 hours, pingdom has been reporting Timeouts which I can't find any "H1X" related errors in the logs at the same time.</p> <p>I am occassionally able to reproduce the timeouts in google chrome. where I would get this message after about 30 seconds of requesting any page:</p> <p>Chrome browser error No data received Unable to load the webpage because the server sent no data. Here are some suggestions: Reload this webpage later. Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.</p> <p>The app will then begin serving requests normally until it happens again. </p> <p>I know this is not enough info, but I can't find anything useful yet in newrelic or scanning the logs that correlates to when the error occured.</p> <p>In one instance, i was reproducing the error in the browser while viewing the heroku logs and when the timeout occurred, there was no evidence of the request showing up in the logs. Its like the failed requests never make it into the app.</p>
35,587,438
0
SSRS Render Multiple Pages from Report in C# <p>I have a service that renders a report from SSRS which works perfectly fine with one page, however when I tried to change the code to render multiple pages separately I can't seem to get it to work as expected.</p> <p>I used a guide on the MSDN blogs (<a href="http://blogs.msdn.com/b/bryanke/archive/2004/02/11/71491.aspx#code" rel="nofollow">http://blogs.msdn.com/b/bryanke/archive/2004/02/11/71491.aspx#code</a>) to try and achieve this, but my StreamIDs doesn't seem to be working as I expected.</p> <p>Here's my code from the Render() method onwards (the rest seems to be okay, but I can provide on request): </p> <pre class="lang-cs prettyprint-override"><code> var firstPage = rsExec.Render(format.ToString(), deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); var numberOfPages = streamIDs.Length + 1; results = new Byte[numberOfPages][]; results[0] = firstPage; if (numberOfPages &gt; 1) { for (int i = 1; i &lt; numberOfPages; i++) { deviceInfo = $@" &lt;DeviceInfo&gt; &lt;OutputFormat&gt;JPEG&lt;/OutputFormat&gt; &lt;StartPage&gt;{i + 1}&lt;/StartPage&gt; &lt;/DeviceInfo&gt;"; results[i] = rsExec.Render(format.ToString(), deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); } } </code></pre> <p>This generates the report okay, but I expected the streamIDs to become the number of extra pages required, but it always only has one entry in it. Am I doing something stupidly wrong here?</p> <p>I'm using SQL Server 2008 R2.</p>
26,924,153
0
MeasureString does not return exact width after rotation <p>I'm using <code>MeasureString</code> method to calculate the width of text but the returned value is not exact. I'm using the following code for calculating text width</p> <pre><code>Size sz = g.MeasureString(text, font); g.DrawString(text, font, brush, new Rectangle(0, 0, (int)sz.Width, (int)sz.Height), stringFormat); g.DrawRectangle(Pens.Red, new Rectangle(0, 0, (int)sz.Width, (int)sz.Height)); </code></pre> <p>This works fine without rotation. I'm using the following code to draw rotated text</p> <pre><code>g.RotateTransform(angle); Size sz = g.MeasureString(text, font); g.DrawString(text, font, brush, new Rectangle(0, 0, (int)sz.Width, (int)sz.Height), stringFormat); g.DrawRectangle(Pens.Red, new Rectangle(0, 0, (int)sz.Width, (int)sz.Height)); </code></pre> <p>The width value returned for second code snippet is different from first one and also it's not correct. See the following image</p> <p><img src="https://i.stack.imgur.com/ADUmJ.png" alt="Additional space"></p> <p>At the bottom of the rectangle there is some additional space after text. The rectangle was drawn based on the width and height of the string so I think this has something to do with <code>MeasureString</code> method. </p> <p>Please share your thoughts on avoiding this</p> <p>Edit:</p> <p>More space can be seen if text length is long (say 30 or more characters) .Rotation works fine for angles 0, 90, 180 and 270. Attached a screenshot</p> <p><img src="https://i.stack.imgur.com/ZNVcC.png" alt="At 90 degree"></p>
8,849,483
0
<p>That is not allowed operation. If you removed channel and you want to add it again you mustn't create a new instance. You must use the old one and only change its state. The main rule is that each entity with unique key must be declared only once. Your code results in two instances with the same key = error. </p>
25,674,559
0
<p>you could also add it directly in your page-template (this is called 'inline styling'):</p> <p>a couple of lines below your opening body tag you'll find </p> <pre><code>&lt;div&gt; &lt;a href="http://forum.banaisbul.com"&gt;&lt;img src="http://forum.banaisbul.com/wp-content/uploads/2014/09/banaisbulsiyah.jpg" border="0" alt="Link to this page"&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>and you need to change it to</p> <pre><code>&lt;div style="background-color:#404040"&gt; &lt;a href="http://forum.banaisbul.com"&gt;&lt;img src="http://forum.banaisbul.com/wp-content/uploads/2014/09/banaisbulsiyah.jpg" border="0" alt="Link to this page"&gt;&lt;/a&gt; &lt;/div&gt; </code></pre>
3,488,058
0
<p>&lt;Edit> Although one object can access private properties of all objects of the same class, you cannot access protected methods of an object from other class even if the protected method is defined in a common super class.</p> <p>So while this code compiles:</p> <pre><code>public class Test { private int x; private void change(Test test) { test.x = test.x + 1; } public static void main() { Test test1 = new Test(); Test test2 = new Test(); test1.change(test2); } } </code></pre> <p>The following code will not compile:</p> <pre><code>public class Test2 { public static void main() { Test1 test1 = new Test1(); test1.clone(); // The method clone() from the type Object is not visible } } </code></pre> <p>&lt;/Edit></p> <p>Being able to call <code>toString()</code>, <code>equals(Object)</code>, <code>hashCode()</code> and <code>getClass() on all objects makes things a lot easier.</p> <p><code>clone()</code> and <code>finalize()</code> are protected. So in order to be able to call them from the outside the subclass has to increase the visibility. And that is obviously a design decision.</p> <p>To be honest, i have no idea why Sun decided that all object are "locks" and have <code>notify()</code>, <code>notifyAll()</code>, <code>wait(long)</code>, wait(long, int)</code>. From my point of view those method should not be in Object at all but in a specialized Lock-class. But I guess there was a good reason to have them there in the very early days and it cannot be changed nowadays without breaking compatibility.</p>
34,849,535
0
<p>For these kind of errors, right click on the error word and say 'Resolve'. All the errors will be if defining assembly is referenced in your project.</p>
1,708,874
0
<p>Use <code>numpy.hstack()</code>:</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; desc = {'names': ('gender','age','weight'), 'formats': ('S1', 'f4', 'f4')} &gt;&gt;&gt; a = numpy.array([('M',64.0,75.0),('F',25.0,60.0)], dtype=desc) &gt;&gt;&gt; numpy.hstack((a,a)) array([('M', 64.0, 75.0), ('F', 25.0, 60.0), ('M', 64.0, 75.0), ('F', 25.0, 60.0)], dtype=[('gender', '|S1'), ('age', '&lt;f4'), ('weight', '&lt;f4')]) </code></pre>
27,521,919
0
How to convert dropdown value to array jquery <p>this way i was trying to convert dropdown value to array by jquery but routine is not working.</p> <pre><code>&lt;select name="DropDownList1" id="DropDownList1"&gt; &lt;option value="00"&gt;00&lt;/option&gt; &lt;option value="05"&gt;05&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;option value="15"&gt;15&lt;/option&gt; &lt;/select&gt; function cboValueToArray(targetid) { var $target = $("select[id*=" + targetid + "]"); var results = []; $($target).each(function () { var val = $(this).val(); if (val !== '') results.push(val); }); alert(results.toString()); return results; } alert(cboValueToArray('DropDownList1').toString()); </code></pre> <p>this line <code>$($target).each()</code> is causes problem. guide me how to fix this. thanks</p>
18,372,384
0
<p>Hide the Prelude's <code>(!!)</code> operator and you can define your own <code>(!!)</code> operator:</p> <pre><code>import Prelude hiding ((!!)) (!!) :: MyType1 -&gt; MyType2 -&gt; MyType3 x !! i = ... -- Go wild! </code></pre> <p>You can even make a type class for your new <code>(!!)</code> operator if you prefer.</p>
6,234,021
0
Reflection and Private Native Methods <p>I am using reflection to dynamically call some methods from extended class. Unfortunately one of these methods is declared as private native and as soon as I make the call... I receive the following exception:</p> <pre><code>java.lang.IllegalAccessException: Class com.something.somewhere.MyThing ca n not access a member of class com.something.somewhere.AnotherThing with modifier s "private native" </code></pre> <p>Is there a way around this?</p>
3,688,164
0
<p>I don't have any trouble getting a connection using</p> <pre><code>C:\Program Files\PuTTY&gt; putty -ssh -l &lt;username&gt; &lt;hostname or host ip&gt; </code></pre> <p>The only things that leap to mind are either 1) a problem with the script used as part of the <code>-m</code> argument, or 2) an incorrect use of capitals. Could the error message be generated by the script rather than the command? Could you possibly have used </p> <pre><code>C:\Program Files\PuTTY&gt; putty -ssh -L &lt;username&gt; &lt;hostname or host ip&gt; </code></pre> <p>A capital <code>L</code> is for a port-forwarding setup, while lowercase <code>l</code> is for specifying a login (username).</p> <p>A couple of notes:</p> <p><code>plink</code> does a similar job without opening a new window. Might be worth exploring, but the commands are pretty much identical.</p> <p>It's generally not a good idea to put plaintext passwords on the command line. You would be better off exploring keys, especially if this is for an automated process. A quick search will turn up a variety of links, but you'll need to check for the best way to handle your particular situation. If you want this to operate as part of an automated script, you'll do different things than if you want to run it as part of an interactive session where you already have Pageant running.</p> <p>If you do go with keys, then your command line becomes</p> <pre><code>putty -ssh &lt;username&gt;@&lt;host&gt; -m &lt;script on local machine&gt; </code></pre>
23,105,566
0
JQuery button click function not working <p>I'm new to JQuery and my problem is that I have a button in a modal such that when I click it, a JQuery script is run. Pieces of code so far:</p> <pre><code>&lt;a id="submitMe" class="btn btn-default btn-primary"&gt;Submit&lt;/a&gt; $(document).ready(function (){ $("#submitMe").click(function(){ alert("Something to alert"); }); }); </code></pre> <p>Thanks for all your help!</p>
30,132,971
0
<blockquote> <p>Is it possible to insert a character to the left of text</p> </blockquote> <p>You did so, in your code snippet in your question.</p> <blockquote> <p>I can change color/size of that character?</p> </blockquote> <p>You are welcome to wrap that character in <code>ForegroundColorSpan</code>, <code>RelativeSizeSpan</code>, etc., using a <code>SpannableString</code> instead of a regular string.</p> <p>Or, use a <code>BulletSpan</code> and skip the character, though I don't think you can control the size of the bullet.</p> <blockquote> <p>I can also create a custom drawable which is a "oval" shape of blue color but how can I insert that to the left of "my text" so that the effect is as below.</p> </blockquote> <p>Either use an <code>ImageSpan</code> or find a library that allows you to wrap text around an image in a <code>TextView</code> (I'm pretty sure there is one, though I'm not coming up with it on a quick search).</p>
858,207
0
<p>If you can modify the configuration file on the server here's what you can do to get the exception information through the service.</p> <p>You need to add a service behavior section to the server's config.</p> <pre><code>&lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="serviceNameBehavior"&gt; &lt;serviceDebug includeExceptionDetailInFaults="True" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; </code></pre> <p>Then associate the service with that behavior.</p> <pre><code>&lt;service name="serviceName" behaviorConfiguration="serviceNameBehavior" ... </code></pre>
9,824,833
0
<p>The problem is that you are loading the lang file from inside a function, which means that <code>$lang</code> does not get placed into the global scope but rather the local function scope.</p> <p><strong>Minimum required change to make it work (but not a good idea)</strong></p> <p>Assuming you <em>want</em> <code>$lang</code> to be placed inside the global scope, you could do so explicitly:</p> <pre><code>public function lang($file, $language){ require 'languages/'.$language.'/'. $file . '.php'; $GLOBALS['lang'] = $lang; // "export" to global scope } </code></pre> <p><strong>A much better idea</strong></p> <p>There are several things that can be improved:</p> <ol> <li>The function above writes the contents of the global variable <code>$lang</code> "behind the caller's back" -- that's not good design, and it makes the code harder to maintain</li> <li>As it stands, it loads the language file from scratch every time you call it</li> </ol> <p>You can kill both birds with one stone by storing the language file contents inside a <code>static</code> local variable and returning it from the function: there is no more writing to the global scope, and the variable keeps its contents so you don't have to reload the language file every time. It would look like this:</p> <pre><code>public function lang($file, $language){ static $cache = array(); if (empty($cache[$language][$file])) { // load language files on demand require 'languages/'.$language.'/'. $file . '.php'; $cache[$language][$file] = $lang; } return $lang; // return requested data, which is now definitely cached } </code></pre> <p>And to use it, you would do:</p> <pre><code>$lang = $this-&gt;lang('global', 'en'); </code></pre> <p>Dumping raw variables into the global scope like this is not always the best idea, but depending on the circumstances (small projects) it might be OK.</p>
26,229,122
0
<p>In Eclipse's do following steps </p> <p>Step 1. Project → Clean</p> <p>Step 2. Build and Run your Application. </p>
37,785,931
0
store array data retrieved from forms to database <p>I have a form. And there is add button to add more forms according to requirement. The Working demo is in JSFiddle. <a href="https://jsfiddle.net/szn0007/eanhpLkg/" rel="nofollow">https://jsfiddle.net/szn0007/eanhpLkg/</a></p> <p>My PHP code is :</p> <pre><code>$data['client_name'] = $_POST['client_name']; $data['address'] = $_POST['address']; $data['fiber_length'] = $_POST['fiber_length']; $data['phone_number'] = $_POST['phone_number']; $data['package'] = $_POST['package']; $data['result'] = $_POST['result']; $data['remarks'] = $_POST['remarks']; foreach($data['client_name'] as $c ) { $sql = "INSERT INTO ct_staff_activity_ftth(client_name) VALUE('$c') "; $this-&gt;db-&gt;query($sql); } </code></pre> <p>How can i insert all the dataas entered at once.</p>
14,191,644
0
Simple meteor insert not working <p>I am just getting started messing around with Meteor and can't get the following code for a simple Collection.insert to update the database when the event is triggered. I can even see the page update with the value of the text field for a split-second before disappearing (presumably once Meteor realized the value wasn't written to the server). Inserting via the console works just fine... Is there some basic concept that I am overlooking?</p> <p>file.js</p> <pre><code>var Tasks = new Meteor.Collection("Tasks"); if (Meteor.isClient) { Template.main.task = function() { return Tasks.find({}); }; Template.main.events = { 'click #submit' : function(event) { var task = document.getElementById("text").value; Tasks.insert({title: task}); } }; } </code></pre> <p>file.html</p> <pre><code>&lt;body&gt; {{&gt; main}} &lt;/body&gt; &lt;template name="main"&gt; &lt;form class="form-inline"&gt; &lt;input type="text" id="text" class="input-small" /&gt; &lt;input type="Submit" class="btn" id="submit" value="Submit"/&gt; &lt;/form&gt; {{#each task}} &lt;span id="output"&gt;{{title}}&lt;/span&gt; {{/each}} &lt;/template&gt; </code></pre>
36,876,055
0
CentOS 7, what happened to DNAT? <p>I am doing some firewall work on CentOS 7. My end goal is to essentially make the server's internal ip address is the same as the floating ip address assigned to it. I disabled firewalld and installed iptables-services.</p> <p>/etc/redhat-release</p> <pre><code>CentOS Linux release 7.2.1511 (Core) </code></pre> <p>iptables v1.4.21</p> <p>When running this script I get </p> <blockquote> <p>iptables v1.4.21: unknown option "SNAT" as well as unknown option "DNAT"</p> </blockquote> <p>My script is </p> <pre><code>#!/bin/bash PRIVIP="107.170.40.128" # e.g., assuming this is the private IP address FLOATIP="104.196.55.167" # e.g. assuming this is the floating IP address echo "iptables" echo "/sbin/iptables -t nat -A PREROUTING -d ${PRIVIP}/32 -j DNAT -–to-destination ${FLOATIP}" /sbin/iptables -t nat -A PREROUTING -d ${PRIVIP}/32 -j DNAT -–to-destination ${FLOATIP} echo "/sbin/iptables -t nat -A POSTROUTING -s ${FLOATIP}/32 -j SNAT -–to-source ${PRIVIP}" /sbin/iptables -t nat -A POSTROUTING -s ${FLOATIP}/32 -j SNAT -–to-source ${PRIVIP} echo "arp" /sbin/arp -i eth0 -Ds ${PRIVIP} eth0 netmask 255.255.255.255 pub /sbin/arp -an echo "sleep" sleep 10 systemctl restart network </code></pre> <p>What happened to the DNAT and SNAT options that are in Centos 6? </p>
38,532,122
0
<p>Maybe:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>alert(/^\{{2}[\w|\s]+\}{2}$/.test('{{FirstName}}'))</code></pre> </div> </div> </p> <p><code>^</code>: In the beginning.</p> <p><code>$</code>: In the end.</p> <p><code>\{{2}</code>: Character <code>{</code> 2 times.</p> <p><code>[\w|\s]+</code>: Alphabet characters or whitespace 1 or more times.</p> <p><code>\}{2}</code>: Character <code>}</code> 2 times.</p> <p><strong>UPDATE:</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>alert(/(^\{{2})?[\w|\s]+(\}{2})?$/.test('FirstName'))</code></pre> </div> </div> </p>
261,667
0
<p>You can find the error codes <a href="http://vista.intersystems.com/csp/docbook/DocBook.UI.Page.cls?KEY=RSQL_sqlerrors" rel="nofollow noreferrer">here</a></p>
13,669,241
0
<p>Will this work for you?</p> <pre><code>String.prototype.regexIndexOf = function(regex, startpos) { var indexOf = this.substring(startpos || 0).search(regex); return (indexOf &gt;= 0) ? (indexOf + (startpos || 0)) : indexOf; } </code></pre> <p>See <a href="http://jsfiddle.net/rCn3Q/2/" rel="nofollow">JSfiddle</a></p>
32,201,061
0
Google Pie Chart Using Array <p>I have tried to implement the following code using an array of two sets of values but the line graph does not show:</p> <pre><code>function drawChart() { var lineTotalDistance = &lt;?php echo json_encode($DistanceTotalArray) ?&gt;; var lineSpeed = &lt;?php echo json_encode($SpeedArray) ?&gt;; //alert(lineTotalDistance.length); //alert(lineSpeed.length); var data = new google.visualization.DataTable(); data.addColumn('number', 'Total Distance'); data.addColumn('number', 'Speed KM/H'); for(var i=0;i &lt; lineTotalDistance.length; i++) { data.addRows([ [lineTotalDistance, lineSpeed ] ]); } } </code></pre>
16,002,871
0
<p>I have been unable to get the <code>itemStyle</code> property of <code>credits</code> to work. </p> <p>Instead, taking inspiration from <a href="http://stackoverflow.com/questions/9732205/place-text-in-center-of-pie-chart-highcharts">Place text in center of pie chart - Highcharts</a>, I have come up with this little fiddle: <a href="http://jsfiddle.net/2P98N/22/" rel="nofollow">http://jsfiddle.net/2P98N/22/</a></p>
4,993,145
0
<pre><code>$sql = "SELECT * FROM my_table"; $ressource_sql = execute_sql($sql); while ($row = mysql_fetch_assoc($ressource_sql)) { $ligne_hve.=$row['id'] . ';'; $ligne_hve.= iconv(input charset, 'windows-1252//TRANSLIT', $row['name']) . ';'; $ligne_hve.= iconv(input charset, 'windows-1252//TRANSLIT', $row['products']) . ';'; $ligne_hve .= "\n"; } $file_hve = fopen($file_export_hve, "w+"); fwrite($file_hve, $ligne_hve); fclose($file_hve); </code></pre> <p>The input charset is iso-8859-1.</p>
14,491,532
0
<p>If you want to use Base still then you are going to have to do this to use those functions:</p> <pre><code>if (Button1) { dynamic_cast&lt;Client*&gt;(connection)-&gt;A(); } else { dynamic_cast&lt;Host*&gt;(connection)-&gt;B(); } </code></pre> <p>And you will need to make connection a pointer. <code>Base * connection</code>.</p> <p>This isn't really ideal though. You should investigate a different way to do it like in the other answers. </p>
26,321,084
0
<p>My <a href="http://stackoverflow.com/a/26320857/642706">other answer</a> correctly solves the direct problem raised in the Question. This answer is a bonus, an alternate avenue to accomplish the goal of calculating and applying elapsed time.</p> <p>Doing this kind of date-time work is much easier if using either of these libraries:</p> <ul> <li><a href="http://www.joda.org/joda-time/" rel="nofollow">Joda-Time</a></li> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html" rel="nofollow">java.time package</a><br/>(built into Java 8, inspired by Joda-Time, defined by <a href="https://jcp.org/en/jsr/detail?id=310" rel="nofollow">JSR 310</a>)</li> </ul> <p>The old date-time classes (java.util.Date, .Calendar, java.text.SimpleDateFormat) bundled with Java are notoriously troublesome, confusing, and flawed. Avoid them. If required you can convert to-and-fro with either library listed above.</p> <h1>Joda-Time</h1> <p>The code example below is using Joda-Time 2.5.</p> <h2>Elapsed Time</h2> <p>You can count elapsed time in either of two ways: </p> <ul> <li><strong>Calendar</strong> style<br/>Number of months, weeks, days, and such.</li> <li><strong>Stopwatch</strong> style<br/>Total number of milliseconds, as if measured with a running <a href="http://en.wikipedia.org/wiki/Stopwatch" rel="nofollow">stopwatch</a>.</li> </ul> <p>These two ways to measure elapsed time may give different results! This code example shows both.</p> <h2>Time Zone</h2> <p>Unlike j.u.Date, a <code>DateTime</code> object in Joda-Time actually knows its own assigned time zone. That is crucial if you count elapsed time by the calendar style (months, days, and so on). Note how this example uses Montréal, Québec time zone (arbitrarily chosen).</p> <h2>Example Code</h2> <pre><code>// Simulate inputs, a trio of java.util.Date objects. java.util.Date dateStart = new DateTime( 2014 , 1 , 2 , 0 , 0 , 0 , DateTimeZone.UTC ).toDate(); java.util.Date dateStop = new DateTime( 2014 , 3 , 2 , 0 , 0 , 0 , DateTimeZone.UTC ).toDate(); java.util.Date dateTarget = new DateTime( 2014 , 7 , 1 , 0 , 0 , 0 , DateTimeZone.UTC ).toDate(); // Convert inputs to Joda-Time DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" ); // Or DateTimeZone.UTC. DateTime start = new DateTime( dateStart , timeZone ); DateTime stop = new DateTime( dateStop , timeZone ); DateTime target = new DateTime( dateTarget , timeZone ); // Determine elapsed time in three fashions: (a) pair of points on timeline, (b) An amount of weeks, days, hours, and such, and (c) actual milliseconds. Interval interval = new Interval( start , stop ); Period period = interval.toPeriod(); Duration duration = interval.toDuration(); // Add elapsed time to target date-time. Show results of adding either period or duration. DateTime laterByPeriod = target.plus( period ); DateTime laterByDuration = target.plus( duration ); </code></pre> <p>Dump to console.</p> <pre><code>System.out.println( "dateStart: " + dateStart ); // BEWARE: j.u.Date objects are in UTC by definition, but "toString" method applies the JVM's current default time zone. Misleading! System.out.println( "dateStop: " + dateStop ); System.out.println( "dateTarget: " + dateTarget ); System.out.println( "start: " + start ); System.out.println( "stop: " + stop ); System.out.println( "target: " + target ); System.out.println( "interval: " + interval ); System.out.println( "period: " + period ); System.out.println( "duration: " + duration ); System.out.println( "laterByPeriod: " + laterByPeriod ); // Notice the change in offset because of DST (Daylight Saving Time) in Québec. System.out.println( "laterByDuration: " + laterByDuration ); </code></pre> <p>When run.</p> <pre class="lang-none prettyprint-override"><code>dateStart: Wed Jan 01 16:00:00 PST 2014 dateStop: Sat Mar 01 16:00:00 PST 2014 dateTarget: Mon Jun 30 17:00:00 PDT 2014 start: 2014-01-01T19:00:00.000-05:00 stop: 2014-03-01T19:00:00.000-05:00 target: 2014-06-30T20:00:00.000-04:00 interval: 2014-01-01T19:00:00.000-05:00/2014-03-01T19:00:00.000-05:00 period: P2M duration: PT5097600S laterByPeriod: 2014-08-30T20:00:00.000-04:00 laterByDuration: 2014-08-28T20:00:00.000-04:00 </code></pre>
23,333,081
0
<p>If the contents of the iframe is from the same domain you can access it by:</p> <pre><code>$('#edit-resp398__ifr').contents().find(selector)... </code></pre>
31,834,593
0
Target framework dnx451 or net451 in class library projects <p>From what I understand, the target frameworks <code>dnx451</code> and <code>net451</code> both use the desktop .NET Framework 4.5.1. <code>dnx451</code> is especially intended for DNX runtime application and supports ASP.NET 5.</p> <p>If we have a solution with a ASP.NET 5 project and multiple class libraries, should they all target <code>dnx451</code> or does only the web project need to target <code>dnx451</code>? Could the class libraries just target <code>net451</code>?</p>
28,548,533
0
Using JSON object using Angular and rest service <p>I have this service method</p> <pre><code>public object Get(EmployeeAccountsRequest request) { var list=userList.ToList(); var jsonSerialiser = new JavaScriptSerializer(); var json = jsonSerialiser.Serialize(list); return json; } </code></pre> <p>Definition of EmployeeAccountRequest request class</p> <pre><code>[Route("/employeeaccount", "GET")] public class AllUserAccountsRequest : IReturn&lt;object&gt; { public int projectNumber{ get; set; } public int class{ get; set; } } </code></pre> <p>which returns following JSON object.</p> <pre><code>[{"name": "Moroni", "allowance": 550, "paid": true}, {"name": "Tiancum", "allowance": 53, "paid": false}, {"name": "Jacob", "allowance": 27, "paid": false}] </code></pre> <p>Resource to get this data from service is as following:</p> <pre><code> angular.module('accService', ['ngResource']).factory('EmployeeAccount', function($resource) { return $resource('/api/employeeaccount/:id', {}, { get: { method: 'GET', }, query: { method: 'GET', }, update: { method: 'PUT' }, }); }); </code></pre> <p>And trying to receive this value in controller </p> <pre><code> var app = angular.module('EmployeeApp'); app.controller('EmployeeAccountsController', function($scope, $http, EmployeeAccount) { console.log(EmployeeAccount.query()) } </code></pre> <p>But i am not receiving the JSON object here. The above setup works fine if i return a list of array from my method.</p> <p>So the question becomes why would a list of array is received properly and not a simple JSON object. Please let me know, if more information is needed.</p>
17,429,964
0
<p>There is never a guarantee that you will not get stuck in a local optimum, sadly. Unless you can prove certain properties about the function you are trying to optimize, local optima exist and hill-climbing methods will fall prey to them. (And typically, if you can prove the things you need to prove, you can also select a better tool than a neural network.)</p> <p>One classic technique is to gradually reduce the learning rate, then increase it and slowly draw it down, again, several times. Raising the learning rate reduces the stability of the algorithm, but gives the algorithm the ability to jump out of a local optimum. This is closely related to simulated annealing.</p> <p>I am surprised that Google has not helped you, here, as this is a topic with many published papers: Try terms like, "local minima" and "local minima problem" in conjunction with neural networks and backpropagation. You should see many references to improved backprop methods. </p>
27,951,964
0
<p>In order to put the result from your <code>apply()</code> call into a data frame, you could do</p> <pre><code>df &lt;- data.frame(id=data$id, largest_value_var=apply(data[,-1], 1, function(x) names(x)[which.max(x)])) </code></pre> <p>Note that <code>c(names(x))</code> is the same as <code>names(x)</code>, so I omitted <code>c()</code>.</p>
18,634,136
1
Why do I get IndexError: list index out of range? <p>I keep getting the <code>IndexError</code> with a list. My code looks like this:</p> <pre><code>for x in range(len(MAIN_list[0])): print(x) print(MAIN_list[9][x]) print(MAIN_list[10][x]) print(MAIN_list[0][x] + "; " + MAIN_list[1][x] + \ "; " + MAIN_list[2][x] + "; " + MAIN_list[3][x] + \ "; " + MAIN_list[4][x] + "; " + MAIN_list[5][x] + \ "; " + MAIN_list[6][x] + "; " + MAIN_list[7][x] + \ "; " + MAIN_list[8][x] + "; " + MAIN_list[9][x] + \ "; " + MAIN_list[10][x]) </code></pre> <p>Now, the output is:</p> <pre><code>0 cross tick Traceback (most recent call last): File "C:\Users\Michele2\Desktop\Arcrate\MyCASH\Python Code\Scraping\Scraping1.3(clean)TEST.py", line 246, in &lt;module&gt; "; " + MAIN_list[10][x]) IndexError: list index out of range </code></pre> <p>I know that you'd usually get this error for variables outside the actual length of the list, but here I get the right output when I call it singularly (ie. row 3 of the output) but not when I try to print the list as a whole. Any though would be welcome.</p> <p>Thanks</p>
3,081,292
0
<p><strike>I'm assuming this doesn't happen the first run through, but after some time. Is this correct?</strike></p> <p><strong>edit</strong>: <em>removed incorrect assumption, but there's still an issue with <code>IDisposable</code></em></p> <hr> <p>You're not disposing of NewImage, and this will cause you issues in production.</p> <p>I'd normally say 'just use a using', but try/finally is the same thing. Refactor to us a using at your own discretion.</p> <pre><code>System.Drawing.Image NewImage = null; System.Drawing.Image FullsizeImage = null; try { FullsizeImage = System.Drawing.Image.FromFile(OriginalFile); [... snip ... ] NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero); // Clear handle to original file so that we can overwrite it if necessary FullsizeImage.Dispose(); // Save resized picture NewImage.Save(NewFile); } finally { if (FullsizeImage != null) FullsizeImage.Dispose(); if (NewImage != null) NewImage.Dispose(); } </code></pre>
39,181,025
0
<p>It looks like that xine is not working correctly because <code>Das Netzwerk ist nicht erreichbar</code>. This stops vdr:</p> <pre><code>[2461] [xine..put] cXinelibServer: bind error 192.168.2.51 port 37890: Die angeforderte Adresse kann nicht zugewiesen werden [2461] [xine..put] (ERROR (frontend_svr.c,860): Die angeforderte Adresse kann nicht zugewiesen werden) [2461] [discovery] UDP broadcast send failed (discovery) [2461] [discovery] (ERROR (tools/vdrdiscovery.c,97): Das Netzwerk ist nicht erreichbar) </code></pre> <p>The network seems to be ok:</p> <pre><code>Feb 18 00:53:57 glubschi vdr: [2302] [xine..put] Listening on address '192.168.2.51' port 37890 </code></pre>
39,829,468
0
What is Web API and why to use it in .net? <p>Why to choose Web API ? It supports convention-based CRUD Actions since it works with HTTP verbs GET,POST,PUT and DELETE. Responses have an Accept header and HTTP status code. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.</p>
11,585,253
0
<p><code>background-size: 100%</code> should do the trick.</p> <p>Here, <a href="http://jsfiddle.net/xGQtF/6/" rel="nofollow">http://jsfiddle.net/xGQtF/6/</a></p>
27,273,825
0
<p>Can you please share which upload type you require? It seems that this code has a mix of both signed and unsigned uploads. For example, you use the <code>unsigned_upload_tag</code> method while also passing the <code>timestamp</code>, <code>api_key</code> and <code>signature</code> which are required only for signed uploads.</p>
12,502,879
0
<p>I actually traced this back to an error in labeling the login button. The session was always open even when the button said 'log in'. I managed to correct this issue, but now I am discovering that indeed the app will not stay logged in across launches, but at least the login/logout button is always correct!</p>
10,531,745
0
<p>(1) I always add this as you suggested</p> <pre><code>config.assets.initialize_on_precompile = false </code></pre> <p>(2) But also, if using ActiveAdmin and/or Devise, exclude their routes when precompiling assets by coding routes.rb as follows</p> <pre><code> unless ARGV.join.include?('assets:precompile') ActiveAdmin.routes(self) devise_for :admin_users, ...etc.... devise_for :users, ...etc... devise_scope :user do get "/login", ..etc end </code></pre> <p>as per <a href="https://github.com/gregbell/active_admin/issues/474" rel="nofollow">here</a> and elsewhere</p>
36,841,914
0
How do I get the column count of a table when there are cells with rowspan/colspan? <p>How do I get the column count of a table when there are cells with rowspan/colspan?</p> <p><strong>UPDATE:</strong> In this question I mean the classical (as far as I know) use of tables, when it's necessary to use the <code>colspan</code>, though it's not required by the specification (and table will look ugly but it will be valid).</p> <p>I need JavaScript/jQuery to get <code>11</code> for the following table (as 11 is the maximum number of columns for this table):</p> <pre><code>&lt;table border="1"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th rowspan="3"&gt;Lorem&lt;/th&gt; &lt;th rowspan="3"&gt;ipsum&lt;/th&gt; &lt;th rowspan="3"&gt;dolor&lt;/th&gt; &lt;th colspan="4"&gt;sit&lt;/th&gt; &lt;th colspan="4"&gt;amet&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th colspan="3"&gt;consectetur&lt;/th&gt; &lt;th rowspan="2"&gt;adipisicing&lt;/th&gt; &lt;th rowspan="2"&gt;elit&lt;/th&gt; &lt;th rowspan="2"&gt;sed&lt;/th&gt; &lt;th rowspan="2"&gt;do&lt;/th&gt; &lt;th rowspan="2"&gt;eiusmod&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;tempor&lt;/th&gt; &lt;th&gt;incididunt&lt;/th&gt; &lt;th&gt;ut&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt;&lt;/tbody&gt; &lt;/table&gt; </code></pre> <p><a href="https://jsfiddle.net/toahb3a3/" rel="nofollow">https://jsfiddle.net/toahb3a3/</a></p> <p>My personal solution is:</p> <pre><code>$(function(){ var max = 0; $('tr').each(function(){ var current = 0; $(this).find('th').each(function(){ var colspan = $(this).attr('colspan'); current += Number(colspan ? colspan : 1); }); max = Math.max(current, max); }); console.log(max); }); </code></pre> <p><a href="https://jsfiddle.net/mt7qhbqd/" rel="nofollow">https://jsfiddle.net/mt7qhbqd/</a></p> <p><strong>UPDATE:</strong> To solve this problem we need the sum of <code>th</code> elements plus their <code>colspan</code> in the very first row of <code>thead</code>. Thanks to Andy for his code, it's really compact and it gave me the thought that I need only the first row. Also, thanks to Quentin who pointed me to the case when <code>colspan</code> is not necessarily used, so Andy's alogrithm won't work (but Quentin's will). Also thanks to Quentin for helping me with the title, as my English isn't good enough.</p> <p><em>Can anybody explain why my question is voted negatively? What's wrong with it</em></p>
18,587,889
0
<p>Try following:</p> <pre><code>import re lines = [ 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', 'Mozilla/5.0 (compatible; AhrefsBot/4.0; +http://ahrefs.com/robot/)', 'msnbot/2.0b (+http://search.msn.com/msnbot.htm)' ] botname = re.compile('\w+bot/[.\w]+', flags=re.IGNORECASE) for line in lines: matched = botname.search(line) if matched: print(matched.group()) </code></pre> <p>prints</p> <pre class="lang-none prettyprint-override"><code>Googlebot/2.1 AhrefsBot/4.0 msnbot/2.0b </code></pre> <p>assumed that bot agent names contain <code>bot/</code>.</p>
24,069,868
0
<p>The problem is that your test does a poor job to migrate some factors in the hardware that make benchmarking hard. To test this, i've made my own test case. Something like this:</p> <pre><code>for blah blah: sleep(500ms) std::copy sse axv </code></pre> <p>output:</p> <pre><code>SSE: 1.11753x faster than std::copy AVX: 1.81342x faster than std::copy </code></pre> <p>So in this case, AVX is a bunch faster than std::copy. What happens when i change to test case to..</p> <pre><code>for blah blah: sleep(500ms) sse axv std::copy </code></pre> <p>Notice that absolutely nothing changed, except the order of the tests.</p> <pre><code>SSE: 0.797673x faster than std::copy AVX: 0.809399x faster than std::copy </code></pre> <p>Woah! how is that possible? The CPU takes a while to ramp up to full speed, so tests that are run later have an advantage. This question has 3 answers now, including an 'accepted' answer. But only the one with the lowest amount of upvotes was on the right track.</p> <p>This is one of the reasons why benchmarking is hard and you should never trust anyone's micro-benchmarks unless they've included detailed information of their setup. It isn't just the code that can go wrong. Power saving features and weird drivers can completely mess up your benchmark. One time i've measured an factor 7 difference in performance by toggling a switch in the bios that less than 1% of notebooks offer.</p>
11,448,616
0
Netgem n5200 (or other) - How to get into linux operating system layer? <p>After logging by PuTTY to Netgem n5200 device I have open in terminal kind of shell with about 40 commends, but no information about way how to close it and work directly on Linux. </p> <p>Device has for 99% installed HardHat Linux distribution (MontaVista Linux). From level of mentioned shell I can use some simple linux command like "! pwd", "! ls -l", "! ps". Maybe it would be useful that I'm in tmp dir and I can not leave it at this moment.</p> <p>I've already study Netgem SDK looking for information and I found nothing, the same result after searching in google, so that's why I came looking for help here.</p>
26,489,068
0
<p>"Exception: The null object does not have a method 'querySelector'."</p> <p>Could that error possibly be because the <code>&lt;polymer-element&gt;</code> definition has no <code>&lt;template&gt;</code>? Perhaps a shadow DOM is never created in that instance, so <code>shadowRoot</code> is <code>null</code>. Just guessing here...</p> <p>I wonder, also, if <code>this..append()</code> attaches elements to the shadow DOM. Seems unlikely.</p>
16,638,560
0
<p>Consider the same functions in a module (lets not think of shell right now)</p> <pre><code>-module(fun_test). -export([test/0]). test() -&gt; F1 = fun() -&gt; timer:sleep(1000) end, F2 = fun() -&gt; io:format("hello world~n", []) end, {F1,F2}. </code></pre> <p>Output is as follows</p> <pre><code>1&gt; fun_test:test(). {#Fun&lt;fun_test.0.78536365&gt;,#Fun&lt;fun_test.1.78536365&gt;} </code></pre> <p>In the above example the anonymous function objects F1 and F2 names are constructed using the name of the module fun_test, unique identifier 0 and 1 (incremental for each function in the module), return addresses etc. as defined in the <a href="http://erlang.org/doc/apps/erts/crash_dump.html#id79001" rel="nofollow">ERTS Manual</a>. This explains the paragraph mentioned in the manual. Though not very useful, the function numbering is handy during debugging as <code>-test/0-fun-1-</code> in the trace will tell you that anonymous function 1 in test/0 function is the source of the error. </p> <p>For the functions defined in the shell use erl_eval module as explained by rvirding. The result of function object declaration is the return of erl_eval for that arity. So always the same value is returned for that arity.</p>
8,588,759
0
<p>There has been filebrowser demos out there written in Silverlight but they would run with elevated trust.</p> <p>That means that you would have to make the user immediately suspicious of your application when they first run it.</p> <p>It's probably a better user experience to just have a well worded error message for when the user runs out of space. </p> <p>Another option would be to try an increase the isolated storage quota by the size of the biggest video available.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile.increasequotato(v=vs.95).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile.increasequotato(v=vs.95).aspx</a></p> <p>Then when that fails just let the user know that no more space can be allocated for the app had that he may need to delete older videos.</p>
848,615
0
<p>Parameteric types ( the word 'generics' is usually used in ECMAScript for <a href="https://developer.mozilla.org/en/New_in_JavaScript_1.6#Array_and_String_generics" rel="nofollow noreferrer">generic methods</a>, rather than the combination of parametric types and runtime polymorphism used in Java ) were <a href="http://wiki.ecmascript.org/doku.php?id=proposals:type_parameters" rel="nofollow noreferrer">proposed</a> as part of ES4, but ES4 fractured and much of the type system proposed for ES ( including the parts implemented in ActionScript ) are not going into the next version. I can't say whether or not Adobe would want to go that way by themselves.</p>
5,505,662
0
<p>if in the plugin they do:</p> <pre><code>return this; //&lt;--jquery object </code></pre> <p>at the end then u can change it with other plugins :-)</p>
20,319,643
0
<p>The functionality available in <code>IOUtils</code> is all you need. This code (tested on my Nexus 7) populates a <code>TMemo</code> with the files in your folder (if there are any):</p> <pre><code>uses IOUtils; procedure THeaderFooterForm.SpeedButton1Click(Sender: TObject); var DirList: TStringDynArray; DirPath: string; s: string; begin DirPath := TPath.Combine(TPath.GetDocumentsPath, 'assets'); DirPath := TPath.Combine(DirPath, 'internal'); // Display where we're looking for the files Memo1.Lines.Add('Searching ' + DirPath); if TDirectory.Exists(DirPath, True) then begin // Get all files. Non-Windows systems don't typically care about // extensions, so we just use a single '*' as a mask. DirList := TDirectory.GetFiles(DirPath, '*'); // If none found, show that in memo if Length(DirList) = 0 then Memo1.Lines.Add('No files found in ' + DirPath) else // Files found. List them. begin for s in DirList do Memo1.Lines.Add(s); end; end else Memo1.Lines.Add('Directory ' + DirPath + ' does not exist.'); end; </code></pre>
31,126,964
0
<p>There's no "one way", but the common approach is to make your top-level repo your library - i.e. <code>github.com/you/somelib</code> and then have a <code>cmd</code> directory underneath that contains your CLI (package mains) - there may even be many.</p> <p>e.g.</p> <pre><code>yourlib/ api.go api_test.go handler.go handler_test.go cmd/ command-name/ main.go // Builds a "command-name" binary other-command/ main.go // Builds a "other-command" binary </code></pre> <p>Your CLI apps are just consumers of your library. Users can retrieve it via <code>go get github.com/you/yourlib/...</code> which will install the lib and the binaries onto their GOPATH.</p> <p>The Go <a href="https://github.com/golang/go/tree/master/src/cmd" rel="nofollow">source itself</a>, <a href="https://github.com/camlistore/camlistore" rel="nofollow">Camlistore</a> and <a href="https://github.com/boltdb/bolt" rel="nofollow">BoltDB</a> all use this approach (amongst many other libs).</p>
29,544,702
0
<p>Like this:</p> <pre><code>private let phoneLabels = [ kABPersonPhoneMobileLabel, kABPersonPhoneIPhoneLabel, kABWorkLabel, kABHomeLabel, kABPersonPhoneMainLabel, kABPersonPhoneHomeFAXLabel, kABPersonPhoneWorkFAXLabel, kABPersonPhonePagerLabel, kABOtherLabel ] as [AnyObject] as! [String] </code></pre>
30,763,362
0
Get list of process <p>I need to get the list of process with their PID. I know how to get the PID by its handle and viceversa, but the problem is that I'm not the one who create the process, so I don't have the handle nor the PID. I didn't find exactly information on how to do it on Internet.</p> <p>Is there some function that returns the list of process with their PID?</p> <p>I mean something like get all the PIDs of 'chrome.exe', for example.</p> <p>Both VCL and Firemonkey solutions are appreciated.</p>
38,630,923
0
<p>Use:</p> <pre><code>Ext.Date.format(timestampDate ,'Y-m-d H:i:s') </code></pre> <ul> <li><code>Y</code> - A full numeric representation of a year, 4 digits.</li> <li><code>m</code> - Numeric representation of a month, with leading zeros.</li> <li><code>H</code> - 24-hour format of an hour with leading zeros.</li> <li><code>i</code> - Minutes, with leading zeros</li> <li><code>s</code> - Seconds, with leading zeros</li> </ul> <p><a href="http://docs.sencha.com/extjs/6.0.2-classic/Ext.Date.html" rel="nofollow">http://docs.sencha.com/extjs/6.0.2-classic/Ext.Date.html</a></p>
22,833,197
0
<pre><code>&lt;?php $classreport = array( array( 'name' =&gt; 'Vick', 'std' =&gt; 'A', 'marks' =&gt; array(10, 20, 30, 40) ), array( 'name' =&gt; 'Josh', 'std' =&gt; 'B', 'marks' =&gt; array(20, 40) ), ); $csv = 'name, std, mark'."\r\n"; foreach($classreport as $student) { $markrows = 0; foreach ($student['marks'] as $marks) { if ($markrows == 0) { $csv .= sprintf('%s, %s, %d', $student['name'], $student['std'], $marks)."\r\n"; } else { $csv .= sprintf(', , %d', $marks)."\r\n"; $markrows++; } } } ?&gt; </code></pre> <p>Edit: Actually, I just realized it's easier to just add these things to arrays and then use the <code>csv</code> functions from PHP. Just consider this as pseudo-code to help you on your way.</p>
5,192,448
0
<p>As many as you want. After one commits the file and a second updates the changes the file gets merged. If the first user altered something that the second also altered, the update will result in a conflict and the user will have see what's different from the local file to the one the first user altered and has to manually choose how the file should end up <a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-conflicts.html" rel="nofollow">see solving conflicts in tortoise</a>.</p> <p>If the users modify different parts of the file then there's no issue to it and the file is merged on update.</p>
16,760,650
0
<p>Elements lose their <em>flex item</em> status if they are absolutely positioned. In order to do what you're suggesting, you need to absolutely position the flex container:</p> <p><a href="http://codepen.io/cimmanon/pen/prFdm" rel="nofollow">http://codepen.io/cimmanon/pen/prFdm</a></p> <pre><code>.foo { display: -webkit-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-box-pack: center; -webkit-box-align: center; position: absolute; top: 0; bottom: 0; left: 0; right: 0; } .bar { margin: auto; } &lt;div class="foo"&gt; &lt;div class="bar"&gt;Bar&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Note that I've omitted the moz 2009 Flexbox prefixes because absolute positioning breaks flex containers in Firefox. It should <em>just work</em> in Firefox versions with the standard Flexbox properties.</p>
13,839,187
0
<p>you forgot the 3th argument in your the IF function and other syntax stuff :-)</p> <p>why you make you script not with where? like this:</p> <pre><code>UPDATE saving s INNER JOIN time t ON t.ID = 'input' AND t.User = s.User SET s.balance = s.balance + t.balance * t.interest WHERE t.currency_TYPE = 'RMB'; </code></pre> <p>you will update just records with currency_type rmb!</p> <p>OR </p> <pre><code>UPDATE saving s INNER JOIN time t ON t.ID = 'input' AND t.User = s.User SET s.balance = (t.currency_TYPE = 'RMB', s.balance + t.balance * t.interest, 0); </code></pre>
39,857,165
0
F5 responsive tables: horizontal scroll is not visible <p>I used <a href="http://foundation.zurb.com/responsive-tables.html" rel="nofollow noreferrer">Foundation 5 Responsive Table</a>. But I have this:</p> <p><a href="https://i.stack.imgur.com/PIdBB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PIdBB.png" alt="enter image description here"></a></p> <p>If I understood examples, in the bottom of the 1st columns should be horizontal scroll (for mobile). But I can't move it. I can move content only in the right side.</p> <p>How to fix this problem?</p> <p>My code:</p> <pre><code>&lt;h3&gt;&lt;?php print t('Organization’s contact person'); ?&gt;&lt;/h3&gt; &lt;table class="responsive" summary="&lt;?php print t('Organization’s contact person'); ?&gt;"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th scope="column"&gt;&lt;?php print t('Contact person'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('Country'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('City'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('Street'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('Email'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('Phone'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('Other'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('Image'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('Body'); ?&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td scope="row"&gt; &lt;?php print render($content['field_dir_surname']); ?&gt; &lt;?php print render($content['field_dir_name']); ?&gt; &lt;?php print render($content['field_dir_second_name']); ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php isset($content['field_country_list']) ? print render($content['field_country_list']) : print '-'; ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php isset($content['field_city']) ? print render($content['field_city']) : print '-'; ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php print render($content['field_street']); ?&gt; &lt;?php print render($content['field_building_no']); ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php isset($content['field_email']) ? print render($content['field_email']) : print '-'; ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php isset($form['field_phone']) ? print render($form['field_phone']) : print '-'; ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php isset($form['field_other']) ? print render($form['field_other']) : print '-'; ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php isset($content['field_image']) ? print render($content['field_image']) : print '-'; ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php isset($content['body']) ? print render($content['body']) : print '-'; ?&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;div&gt;&lt;?php print render($content['field_share_content']); ?&gt;&lt;/div&gt; </code></pre>
10,347,265
0
HTML5 local storage JSON multiple objects <p>Does anyone know, if it's possible to make a local storage with multiple objects in it when I'm doing a loop in javascript?</p> <p>At the moment my code looks like this: </p> <pre><code>var albums = ''; var album_list = ''; $.each(data, function(i,item){ var name = item.name; albums += '&lt;li&gt;'+item.name+'&lt;/li&gt;'; var album_content = {name: item.name, uid: 1}; var album_content = album_content+','; album_list += album_content; }); var album_list = '['+album_list+']'; localStorage.setItem("albums", JSON.stringify(album_list)); var albums_l = JSON.parse(localStorage.getItem("albums")); $.each(albums_l, function(i,item){ console.log(item.name); }); </code></pre> <p>But that gives me an error. Anyone have a better solution for this, so I just have one localstorage and all the data in that?</p>
25,993,553
0
<p>You should use DateTime class method Subtract as:</p> <pre><code>var date2 = DateTime.Parse(DateTime.Now.ToShortDateString() + " 10:00"); System.TimeSpan diff1 = date2.Subtract(DateTime.Now); </code></pre>
24,332,673
0
<p>Try increasing the "outer_window" option in config/initializers/kaminari_config.rb. Example:</p> <pre><code>Kaminari.configure do |config| config.outer_window = 12 end </code></pre>
40,596,737
0
<p>If I understand your desired output correctly, you can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow noreferrer"><code>numpy.reshape</code></a></p> <pre><code>&gt;&gt;&gt; spp = np.asarray(splist, dt) &gt;&gt;&gt; spp array([(2002, 10.502535211267606), (2003, 10.214794520547946), (2004, 9.811578947368423), (2015, 9.093658536585366), (2016, 9.244272537935139)], dtype=[('f0', '&lt;i4'), ('f1', '&lt;f8')]) &gt;&gt;&gt; np.reshape(spp, (spp.size, 1)) array([[(2002, 10.502535211267606)], [(2003, 10.214794520547946)], [(2004, 9.811578947368423)], [(2015, 9.093658536585366)], [(2016, 9.244272537935139)]], dtype=[('f0', '&lt;i4'), ('f1', '&lt;f8')]) </code></pre>
11,695,710
0
How to copy namespace and attributes of root node with XSLT? <p>I'm new to XSL/XML and I need help with XSL transformation.</p> <p>I have XML which starts like this</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 ../ws/Invoice.xsd" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:sac="urn:oasis:names:specification:ubl:schema:xsd:SignatureAggregateComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2" xmlns:sig="urn:oasis:names:specification:ubl:schema:xsd:CommonSignatureComponents-2"&gt; &lt;ext:UBLExtensions&gt; &lt;ext:UBLExtension&gt; &lt;cbc:ID&gt;INVOICE1&lt;/cbc:ID&gt; &lt;cbc:Name&gt;InvoiceIssuePlaceData&lt;/cbc:Name&gt; &lt;ext:ExtensionAgencyURI&gt;urn:invoice:hr:issueplace&lt;/ext:ExtensionAgencyURI&gt; &lt;ext:ExtensionContent&gt; &lt;ext:InvoiceIssuePlace&gt;London&lt;/ext:InvoiceIssuePlace&gt; &lt;/ext:ExtensionContent&gt; &lt;/ext:UBLExtension&gt; &lt;/ext:UBLExtensions&gt; &lt;cbc:UBLVersionID&gt;2.1&lt;/cbc:UBLVersionID&gt; &lt;cbc:ID&gt;01 1206-2406-568&lt;/cbc:ID&gt; &lt;/Invoice&gt; </code></pre> <p>I want to create elements for all attributes, and to create element between &lt;_> tags for the value of node which has attribute.</p> <p>Here is the xsl...</p> <pre><code>&lt;?xml version='1.0' encoding='utf-8' ?&gt; &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2" xmlns:sig="urn:oasis:names:specification:ubl:schema:xsd:CommonSignatureComponents-2" xmlns:sac="urn:oasis:names:specification:ubl:schema:xsd:SignatureAggregateComponents-2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 ../ws/Invoice.xsd" version="1.0"&gt; &lt;xsl:output method="xml"/&gt; &lt;xsl:template match="/"&gt; &lt;xsl:apply-templates/&gt; &lt;/xsl:template&gt; &lt;xsl:template match="@*|*|text()"&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select="@*|*|text()"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match="*[@*]"&gt; &lt;xsl:element name="{name()}"&gt; &lt;xsl:if test="count(@*)&gt;=count(node())"&gt; &lt;_&gt; &lt;xsl:value-of select="."/&gt; &lt;/_&gt; &lt;/xsl:if&gt; &lt;xsl:for-each select="@*"&gt; &lt;xsl:element name="{name()}"&gt; &lt;xsl:value-of select="."/&gt; &lt;/xsl:element&gt; &lt;/xsl:for-each&gt; &lt;xsl:if test="count(node())&gt;count(@*)"&gt; &lt;xsl:apply-templates select="*|text()"/&gt; &lt;/xsl:if&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>The problem is that this transformation doesn't transforms root node (Invoice) as I would need. I'm getting:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"&gt; &lt;xsi:schemaLocation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 ../ws/Invoice.xsd&lt;/xsi:schemaLocation&gt; </code></pre> <p>No other attributes in Invoice and as new elements. Only xsi:schemaLocation, but with namespace defined on the level of that node.</p> <p>What I'm doing wrong?</p> <p>Thanks.</p>
37,307,891
0
<p>Just wanted to add, the fiddle, and code from the question worked almost perfectly for me, you have to make sure you take into account any padding though when resetting width/height.</p> <pre><code>el.css({ ... width: (el.width()+LEFT_PADDING+RIGHT_PADDING)/parent.width()*100+"%", height: (el.height()+TOP_PADDING+BOTTOM_PADDING)/parent.height()*100+"%" }); </code></pre>
1,828,093
0
<p>forget skype api, send the sms to directly to the sms email address of the phone, most/all carriars provide 2125551212@cingularme.com, or @vtext.com (those two domains are AT&amp;T and verizon)</p>
8,851,373
0
<p>Yes, I think your thoughts are wrong. Your method signature for an event handler includes arguments that you would not need in other contexts. Why not structure as follows:</p> <pre><code>private void ToggleSwitch_Unchecked(object sender, RoutedEventArgs e) { DoSomething() } private void DoSomething() { // ... } </code></pre> <p>You can then execute <code>DoSomething</code> whenever you like!</p>
26,381,925
0
<p>'12.10.13_file' as a filename, does have '13_file' as it's file extension. At least regarding the file system. </p> <p>But, instead of finding the last . yourself, use <a href="http://docs.python.org/library/os.path.html#os.path.splitext" rel="nofollow">os.path.splitext</a>:</p> <pre><code>import os fileName, fileExtension = os.path.splitext('/path/yourfile.ext') # Results in: # fileName = '/path/yourfile' # fileExtension = '.ext' </code></pre> <p>If you want to exclude certain extensions, you could blacklist those after you've used the above.</p>
39,247,334
0
<p>This is <strong>not</strong> officially supported but...</p> <p>What about using <code>aync</code>/<code>await</code> if you are feeling adventurous and happy to use babel.</p> <pre><code>async function foo() { const res1 = await Redis.getAsync("boo") const res2 = await Redis.getAsync(res1) } </code></pre>
11,377,776
0
<p>If you looking for some copy - paste solution, i foudn this code :</p> <pre><code> function countryCityFromIP($ipAddr) { //function to find country and city from IP address //Developed by Roshan Bhattarai http://roshanbh.com.np //verify the IP address for the ip2long($ipAddr)== -1 || ip2long($ipAddr) === false ? trigger_error("Invalid IP", E_USER_ERROR) : ""; $ipDetail=array(); //initialize a blank array //get the XML result from hostip.info $xml = file_get_contents("http://api.hostip.info/?ip=".$ipAddr); //get the city name inside the node &lt;gml:name&gt; and &lt;/gml:name&gt; preg_match("@&lt;Hostip&gt;(\s)*&lt;gml:name&gt;(.*?)&lt;/gml:name&gt;@si",$xml,$match); //assing the city name to the array $ipDetail['city']=$match[2]; //get the country name inside the node &lt;countryName&gt; and &lt;/countryName&gt; preg_match("@&lt;countryName&gt;(.*?)&lt;/countryName&gt;@si",$xml,$matches); //assign the country name to the $ipDetail array $ipDetail['country']=$matches[1]; //get the country name inside the node &lt;countryName&gt; and &lt;/countryName&gt; preg_match("@&lt;countryAbbrev&gt;(.*?)&lt;/countryAbbrev&gt;@si",$xml,$cc_match); $ipDetail['country_code']=$cc_match[1]; //assing the country code to array //return the array containing city, country and country code return $ipDetail; } </code></pre> <p>Hope this helps somebody.</p>
17,754,899
0
<p>Its been some time since I 've last worked with Hibernate and the problem is of a difficult nature so I will just describe various options:</p> <ul> <li><p>Since your <code>Trace</code> object has a <code>Cascade.All</code> option shouldn't it be enough to just add the <code>TraceEvent</code> on the set and call <code>session.save(trace)</code>? As it is now, my impression is that when the session closes it will try to save the <code>Trace</code> object. Alternatively avoid modifying the set. Just save the <code>TraceEvent</code>. You don't return <code>Trace</code> to be used anywere so there is no point in modifying it. Next time it will be used, it will probably be loaded from the database. All the above behaviour might depend on your configuration but it might worth taking a look.</p></li> <li><p>Do you use some sort of hibernate cache? Could it be that it happens that a <code>Trace</code> object might not be the most recent version? </p></li> <li><p>How <code>TraceEvent</code> is created? Could it be that this object is detached (loaded in a previous request and re-used now?) It seems rather unlikely but please check.</p></li> <li><p>This seems like a function that could be called from many places (i.e. to record a user's action). Is it possible that one of those other places are using the same session and possibly modifying it?</p></li> <li><p>Assuming that it is called from many places, were you able from your logs to link the error with some specific business functionality (e.g. when the user clicks that link/button etc)?</p></li> <li><p>If all else fail why don't you try to add an <code>EventListener</code> or an <code>Interceptor</code> on persist event next time you will update your production environment (I understand that you cannot replicate this error easily). It would be a simple one that would catch <code>NonUniqueObjectException</code> it could print additional log info, and then just re-throw</p></li> </ul>
10,675,573
0
Executing interactive shell commands in Java <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/10407308/redirect-stdin-and-stdout-in-java">Redirect stdin and stdout in Java</a> </p> </blockquote> <p>I know how to execute shell commands in Java but how to do it so my application can write to its input and read from its output. </p>
5,991,414
0
<pre><code>output = rs.getString("column");// if data is null `output` would be null, so there is no chance of NPE unless `rs` is `null` if(output == null){// if you fetched null value then initialize output with blank string output= ""; } </code></pre>
39,848,380
0
Composer won't run globally <p>Using macOS Sierra and trying to install Composer globally.</p> <p>I've followed all these instructions: <a href="http://stackoverflow.com/questions/11333230/how-to-run-composer-from-anywhere">How to run composer from anywhere?</a> and none of them work.</p> <p>Starting afresh I've done this:</p> <ol> <li><p>Terminal > In my home directory (<code>$ cd ~</code>) </p></li> <li><p><code>curl -sS <a href="https://getcomposer.org/installer" rel="nofollow">https://getcomposer.org/installer</a> | sudo php -- --install-dir=/usr/local/bin --filename=composer</code></p></li> <li><p>Reported as a successful installation. Message is: <b>Composer successfully installed to: /usr/local/bin/composer </b></p></li> <li><p><code>$ composer -v -bash: /usr/local/bin/composer/: Not a directory</code></p></li> </ol> <p>When I navigate to <code>/usr/local/bin</code> I can see composer, and it is indeed the executable rather than a directory:</p> <pre><code>$ cd /usr/local/bin $ ls -l -rwxr-xr-x 1 root wheel 1704783 4 Oct 10:07 composer </code></pre> <p>How can I get this to run globally? </p> <p>Checked my path and it looks ok?</p> <pre><code>$ echo $PATH /usr/local/php5/bin:/usr/local/php5/bin:/usr/local/bin: /usr/bin:/bin:/usr/sbin:/sbin </code></pre>
3,035,191
0
<p>One thing to note is that you can do <code>sizeof</code> on the type itself and not just on a variable:</p> <pre><code>// Check if the pointer size of a generic data pointer is different // than the pointer size of a function if (sizeof(void *) != sizeof(int (*)())) { ... } </code></pre>
16,933,647
0
Pausing CSS Slide with -webkit-animation-play-state:paused; not working <p>I have the following code:</p> <pre><code> .picTransition .item { position: absolute; left: 0; right: 0; opacity: 0; -webkit-animation: picTransition 56s linear infinite; -moz-animation: picTransition 56s linear infinite; -ms-animation: picTransition 56s linear infinite; animation: picTransition 56s linear infinite; } .picTransition.paused{ -webkit-animation-play-state:paused; -moz-animation-play-state:paused; -o-animation-play-state:paused; animation-play-state:paused; } .picTransition .item:nth-child(2) { -webkit-animation-delay: 14s; -moz-animation-delay: 14s; -ms-animation-delay: 14s; animation-delay: 14s; } .picTransition .item:nth-child(3) { -webkit-animation-delay: 28s; -moz-animation-delay: 28s; -ms-animation-delay: 28s; animation-delay: 28s; } .picTransition .item:nth-child(4) { -webkit-animation-delay: 42s; -moz-animation-delay: 42s; -ms-animation-delay: 42s; animation-delay: 42s; } </code></pre> <p>I am making a mistake on the how to pause the slides. I have used the animation-play-state: paused, but it does not work. I can use the jquery function, but I really want to try and get this to work in css only. Am I screwing up on the parent child relation? Or is this timing sequence not supported or messing with the pause issue? Perhaps I need to do a hover type pause and build a new div for that? I know I am making a simple mistake.</p>
26,935,923
0
<p>Merge the two insert into single insert like this</p> <pre><code>INSERT INTO @EventValueResultSet(....) SELECT .... .... FROM dbo.EventValue EV WITH (NOLOCK)) INNER JOIN dbo.DataRun_ DR WITH (NOLOCK) ON EV.dataRunId = DR.Id AND DR.PersonId = @PersonId WHERE PhysioCurrentDataTime BETWEEN @blockStartTime AND @endTime OR ( ( CurrentDataTime &lt; @blockStartTime ) AND ( EventEndTime = 0 OR EventEndTime &gt;= @blockStartTime ) ) </code></pre>
5,018,958
0
<p>I don't have a real answer myself, but your question reminded me of this post:</p> <blockquote> <p><a href="http://stackoverflow.com/questions/4964344/selenium-doesnt-work-with-cucumber-capybara-out-of-the-box-macosx">Selenium doesn't work with Cucumber/Capybara (out of the box) - MacOSX</a></p> </blockquote> <p>Where the questioner shows how he used ruby-debug to figure out why a missing dependency was helping selenium fail to open the browser. </p> <p>Hope this helps!</p>
22,771,957
1
python subprocess sends backslash before a quote <p>I have a string, which is a framed command that should be executed by in command line</p> <p>cmdToExecute = "TRAPTOOL -a STRING "ABC" -o STRING 'XYZ'"</p> <p>I am considering the string to have the entire command that should be triggered from command prompt. If you take a closer look at the string cmdToExecute, you can see the option o with value XYZ enclosed in SINGLE QUOTE. There is a reason that this needs to be given in single quote orelse my tool TRAPTOOL will not be able to process the command.</p> <p>I am using subprocess.Popen to execute the entire command. Before executing my command in a shell, I am printing the content</p> <pre><code>print "Cmd to be exectued: %r" % cmdToExecute myProcess = subprocess.Popen(cmdToExecute, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) (stdOut, stdErr) = myProcess.communicate() </code></pre> <p>The output of the above command is, Cmd to be executed: TRAPTOOL -a STRING "ABC" -o \'XYZ\'.</p> <p>You can see that the output shows a BACKWARD SLASH added automatically while printing. Actually, the \ is not there in the string, which I tested using a regex. But, when the script is run on my box, the TRAPTOOL truncates the part of the string XYZ on the receiving server. I manually copy pasted the print output and tried sending it, I saw the same error on the receiving server. However, when I removed the backward slash, it sent the trap without any truncation.</p> <ol> <li>Can anyone say why this happens?</li> <li>Is there anyway where we can see what command is actually executed in subprocess.Popen?</li> <li>Is there any other way I can execute my command other that subprocess.Popen that might solve this problem?</li> </ol>
1,328,739
0
<p>There are examples of usage Openlayers in Wicket. Did you try this: <a href="https://wicket-stuff.svn.sourceforge.net/svnroot/wicket-stuff/trunk/wicketstuff-core/openlayers-parent/openlayers-examples/src/main/java/org/wicketstuff/openlayers/MapUsingWFSGetFeaturePage.java" rel="nofollow noreferrer">https://wicket-stuff.svn.sourceforge.net/svnroot/wicket-stuff/trunk/wicketstuff-core/openlayers-parent/openlayers-examples/src/main/java/org/wicketstuff/openlayers/MapUsingWFSGetFeaturePage.java</a></p> <p>?</p>
14,548,106
0
Using the file name captured with the html browse button in javascript <p>I am trying to create a form where I can upload demographic information such as name, etc. as well as upload jpg image files. I cannot figure out how to catch the file the user chooses from the browse button. Where is the file name stored? How can I access it for the upload? How can I access it to assign it as a variable eg: </p> <pre><code>var theFileName; function() if (filename !=null) { //manipulate the variable }; else { //something else}; </code></pre> <p>I am new to JavaScript and trying to teach myself with web sources and books and cannot seem to find an answer. In addition to an answer to this question, can anyone suggest a good web source for further information on this subject? The ultimate goal is to be able to upload the info and files with PHP into a database so it can be recalled on another page but a different user. </p>
28,686,099
0
Why NOP/few extra lines of code/optimization of pointer aliasing helps? [Fujitsu MB90F543 MCU C code] <p>I am trying to fix an bug found in a mature program for Fujitsu MB90F543. The program works for nearly 10 years so far, but it was discovered, that under some special circumstances it fails to do two things at it's very beginning. One of them is crucial.</p> <p>After low and high level initialization (ports, pins, peripherials, IRQ handlers) configuration data is read over SPI from EEPROM and status LEDs are turned on for a moment (to turn them a data is send over SPI to a LED driver). When those special circumstances occur first and only first function invoking just a few EEPROM reads fails and additionally a few of the LEDs that should, don't turn on.</p> <p>The program is written in C and compiled using Softune v30L32. Surprisingly it is sufficient to add single __asm(" NOP ") in low level hardware init to make the program work as expected under mentioned circumstances. It is sufficient to turn off 'Control optimization of pointer aliasing' in Optimization settings. Adding just a few lines of code in various places helps too.</p> <p>I have compared (DIFFed) ASM listings of compiled program for a version with and without __asm(" NOP ") and with both aforementioned optimizer settings and they all look just fine.</p> <p>The only warning Softune compiler has been printing for years during compilation is as follows:</p> <blockquote> <p>*** W1372L: The section is placed outside the RAM area or the I/O area (IOXTND)</p> </blockquote> <p>I do realize it's rather general question, but maybe someone who has a bigger picture will be able to point out possible cause. </p> <p>Have you got an idea what may cause such a weird behaviour? How to locate the bug and fix it?</p> <p>During the initialization a few long (about 20ms) delay loops are used. They don't help although they were increased from about 2ms, yet single NOP in any line of the hardware initialization function and even before or after the function helps.</p> <p>Both the wait loops works. I have checked it using an oscilloscope. (I have added LED turn on before and off after).</p> <p>I have checked timming hypothesis by slowing down SPI clock from 1MHz to 500kHz. It does not change anything. Slowing down to 250kHz makes watchdog resets, as some parts of the code execute too long (>25ms).</p> <p>One more thing. I have observed that adding local variables in any source file sometimes makes the problem disappear or reappear. The same concerns initializing uninitialized local variables. Adding a few extra lines of a code in any of the files helps or reveals the problem.</p> <pre><code>void main(void) { watchdog_init(); // waiting for power supply to stabilize wait; // about 45ms hardware_init(); clear_watchdog(); application_init(); clear_watchdog(); wait; // about 20ms test_LED(); {...} } void hardware_init (void) { __asm("NOP"); // how it comes it helps? - it may be in any line of the function io_init(); // ports initialization clk_init(); timer_init(); adc_init(); spi_init(); LED_init(); spi_start(); key_driver_init(); can_init(); irq_init(); // set IRQ priorities and global IRQ enable } </code></pre>