title
stringlengths
10
150
body
stringlengths
17
64.2k
label
int64
0
3
Spark SQL UNION - ORDER BY column not in SELECT
<p>I'm doing a UNION of two temp tables and trying to order by column but spark complains that the column I am ordering by cannot be resolved. Is this a bug or I'm missing something?</p> <pre class="lang-scala prettyprint-override"><code>lazy val spark: SparkSession = SparkSession.builder.master(&quot;local[*]&quot;).getOrCreate() import org.apache.spark.sql.types.StringType val oldOrders = Seq( Seq(&quot;old_order_id1&quot;, &quot;old_order_name1&quot;, &quot;true&quot;), Seq(&quot;old_order_id2&quot;, &quot;old_order_name2&quot;, &quot;true&quot;) ) val newOrders = Seq( Seq(&quot;new_order_id1&quot;, &quot;new_order_name1&quot;, &quot;false&quot;), Seq(&quot;new_order_id2&quot;, &quot;new_order_name2&quot;, &quot;false&quot;) ) val schema = new StructType() .add(&quot;id&quot;, StringType) .add(&quot;name&quot;, StringType) .add(&quot;is_old&quot;, StringType) val oldOrdersDF = spark.createDataFrame(spark.sparkContext.makeRDD(oldOrders.map(x =&gt; Row(x:_*))), schema) val newOrdersDF = spark.createDataFrame(spark.sparkContext.makeRDD(newOrders.map(x =&gt; Row(x:_*))), schema) oldOrdersDF.createOrReplaceTempView(&quot;old_orders&quot;) newOrdersDF.createOrReplaceTempView(&quot;new_orders&quot;) //ordering by column not in select works if I'm not doing UNION spark.sql( &quot;&quot;&quot; |SELECT oo.id, oo.name FROM old_orders oo |ORDER BY oo.is_old &quot;&quot;&quot;.stripMargin).show() //ordering by column not in select doesn't work as I'm doing a UNION spark.sql( &quot;&quot;&quot; |SELECT oo.id, oo.name FROM old_orders oo |UNION |SELECT no.id, no.name FROM new_orders no |ORDER BY oo.is_old &quot;&quot;&quot;.stripMargin).show() The output of the above code is: +-------------+---------------+ | id| name| +-------------+---------------+ |old_order_id1|old_order_name1| |old_order_id2|old_order_name2| +-------------+---------------+ cannot resolve '`oo.is_old`' given input columns: [id, name]; line 5 pos 9; 'Sort ['oo.is_old ASC NULLS FIRST], true +- Distinct +- Union :- Project [id#121, name#122] : +- SubqueryAlias oo : +- SubqueryAlias old_orders : +- LogicalRDD [id#121, name#122, is_old#123] +- Project [id#131, name#132] +- SubqueryAlias no +- SubqueryAlias new_orders +- LogicalRDD [id#131, name#132, is_old#133] org.apache.spark.sql.AnalysisException: cannot resolve '`oo.is_old`' given input columns: [id, name]; line 5 pos 9; 'Sort ['oo.is_old ASC NULLS FIRST], true +- Distinct +- Union :- Project [id#121, name#122] : +- SubqueryAlias oo : +- SubqueryAlias old_orders : +- LogicalRDD [id#121, name#122, is_old#123] +- Project [id#131, name#132] +- SubqueryAlias no +- SubqueryAlias new_orders +- LogicalRDD [id#131, name#132, is_old#133] </code></pre> <p>So ordering by a column that's not in the SELECT clause works if I'm not doing a UNION and it fails if I'm doing a UNION of two tables.</p>
0
log4j.xml Rolling Appender based on size
<p>Please find below my log4.xml configuration for rolling file appender</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"&gt; &lt;log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'&gt; &lt;appender name="instrumentationAppender" class="org.apache.log4j.RollingFileAppender"&gt; &lt;param name="file" value="C:\\Users\\Test\\Downloads\\Testlogs\\instrumentation.log"/&gt; &lt;param name="Append" value="true" /&gt; &lt;param name="Encoding" value="UTF-8" /&gt; &lt;param name="MaxFileSize" value="100KB"/&gt; &lt;param name="MaxBackupIndex" value="10"/&gt; &lt;layout class="org.apache.log4j.PatternLayout"&gt; &lt;param name="ConversionPattern" value="%d %-5p [%t] (%C:%L) - %m%n"/&gt; &lt;/layout&gt; &lt;filter class="org.apache.log4j.varia.LevelRangeFilter"&gt; &lt;param name="LevelMin" value="INFO" /&gt; &lt;param name="LevelMax" value="INFO" /&gt; &lt;param name="AcceptOnMatch" value="true" /&gt; &lt;/filter&gt; &lt;/appender&gt; &lt;appender name="debugAppender" class="org.apache.log4j.RollingFileAppender"&gt; &lt;param name="file" value="C:\\Users\\Test\\Downloads\\Testlogs\\Test.log"/&gt; &lt;param name="Append" value="true" /&gt; &lt;param name="Encoding" value="UTF-8" /&gt; &lt;param name="MaxFileSize" value="100KB"/&gt; &lt;param name="MaxBackupIndex" value="10"/&gt; &lt;layout class="org.apache.log4j.PatternLayout"&gt; &lt;param name="ConversionPattern" value="%d %-5p [%t] (%C:%L) - %m%n"/&gt; &lt;/layout&gt; &lt;param name="ImmediateFlush" value="true" /&gt; &lt;filter class="org.apache.log4j.varia.LevelRangeFilter"&gt; &lt;param name="LevelMin" value="DEBUG" /&gt; &lt;param name="LevelMax" value="DEBUG" /&gt; &lt;param name="AcceptOnMatch" value="true" /&gt; &lt;/filter&gt; &lt;/appender&gt; &lt;appender name="errorAppender" class="org.apache.log4j.RollingFileAppender"&gt; &lt;param name="file" value="C:\\Users\\Test\\Downloads\\Testlogs\\Test.log"/&gt; &lt;param name="Append" value="true" /&gt; &lt;param name="Encoding" value="UTF-8" /&gt; &lt;param name="MaxFileSize" value="100KB"/&gt; &lt;param name="MaxBackupIndex" value="10"/&gt; &lt;layout class="org.apache.log4j.PatternLayout"&gt; &lt;param name="ConversionPattern" value="%d %-5p [%t] (%C:%L) - %m%n"/&gt; &lt;/layout&gt; &lt;filter class="org.apache.log4j.varia.LevelRangeFilter"&gt; &lt;param name="LevelMin" value="ERROR" /&gt; &lt;param name="LevelMax" value="FATAL" /&gt; &lt;param name="AcceptOnMatch" value="true" /&gt; &lt;/filter&gt; &lt;/appender&gt; &lt;category name="com.practice.Test" additivity="false"&gt; &lt;priority value="DEBUG"/&gt; &lt;appender-ref ref="instrumentationAppender" /&gt; &lt;appender-ref ref="debugAppender" /&gt; &lt;appender-ref ref="errorAppender" /&gt; &lt;/category&gt; </code></pre> <p></p> <p>The issue is instrumentationAppender,debugAppender and errorAppender are refered by com.practice pakaage as defined in above category. In all the appenders maxFileSize is 100kb and configured for Test.log file. The issue Test.log file does not get rollover after 100kb of size. All logs just get appended to same Test.log file. How do configure RollingAppender based on size?</p> <p>Thanks in advance for the help.</p>
0
set device time programmatically in android
<p>I need to set device time dynamically.if it possible please guide me </p> <p>So far as I tried</p> <p><strong>MainActivity.java</strong></p> <pre><code>Calendar c = Calendar.getInstance(); c.set(2010, 1, 1, 12, 00, 00); </code></pre> <p><strong>manifest.xml</strong></p> <pre><code>&lt;permission android:name="android.permission.SET_TIME" android:protectionLevel="signatureOrSystem" android:label="@string/app_name" /&gt; </code></pre> <p>Thanks in advance</p>
0
How to restart ADB manually from Android Studio
<p>I previously developped Android apps on Android Studio . Everything works fine.</p> <p>I work on real device, and Android Studio recognize it without issue.</p> <p>Suddenly when I exit android studio and disconnect and reconnect my device, it doesn't recognize my device anymore, I have to exit and restart Android Studio.</p> <p>I can't find a way to "Reset adb" like Android Studio.</p> <p>I follow the below instruction(Tools->Android->Enable ADB Integration) and enabled ADB,but still below error occurred.</p> <p>Error:-</p> <p><img src="https://i.stack.imgur.com/5ZBIE.jpg" alt="enter image description here"></p> <p>I using windows system.</p> <p>Any help great appreciation.</p>
0
Java client call to Windows Integated Authentication web service
<p>I am writing a Java 1.5+ client that needs to fetch data from an IIS-hosted web service. I created a new web service client in Eclipse and used the Java Proxy client type and Apache Axis2 web service runtime when generating the client proxy. The web service itself runs on Windows 2003 and security is set to use only Windows Integrated Authentication. I have found many articles online that show how to connect successfully from a Java client to this IIS service, but everything I have seen seems to require that I put the username and password in my Java client code somewhere.</p> <p>My Java client will run on a Windows machine that is on the same Active Directory network that the IIS service is on (i.e. the account I log in with each day can access the service). I want my Java client to run in the context of the logged-in user without me needing to put in my login credentials in the code. Here is my current code, which works, yet requires me to put a user name and password in the code:</p> <pre><code>final NTCredentials nt = new NTCredentials("my_username", "my_password", "", "my_domain"); final CredentialsProvider myCredentialsProvider = new CredentialsProvider() { public Credentials getCredentials(final AuthScheme scheme, final String host, int port, boolean proxy) throws CredentialsNotAvailableException { return nt; } }; DefaultHttpParams.getDefaultParams().setParameter("http.authentication.credential-provider", myCredentialsProvider); </code></pre> <p>But I really don't want to have to put the username and password in the code--I want it to run using the credentials of the logged-in Windows user that is running the Java client.</p> <p>What code should I use so it will connect with the logged-in user's credentials without needing to specify the user name and password? Is this possible?</p>
0
How to list class objects in listbox using C#?
<p>I have a custom class</p> <pre><code>class RouteStop { public int number; public string location; public string street; public string city; public string state; public string zip; public RouteStop(int INnumber, string INlocation, string INstreet, string INcity, string INstate, string INzip) { this.number = INnumber; this.location = INlocation; this.street = INstreet; this.city = INcity; this.state = INstate; this.zip = INzip; } } </code></pre> <p>Then I have a list where I store RouteStop items</p> <pre><code>private List&lt;RouteStop&gt; routeStops = new List&lt;RouteStop&gt;(); </code></pre> <p>What I am trying to archive is to load all objects from list into a listbox. So far it does it's job but instead of actual address it just writes object name into a list such like shown below <img src="https://i.stack.imgur.com/OTAaq.png" alt="enter image description here"></p> <p>How can I make it shows let's say number + location + street + city instead of object name?</p> <p>Also in future I will need to add OnSelect event to open a new window to edit each object's data. How would I pass information about which item is selected?</p> <p><strong>Added:</strong> Thank you very much everyone. Each answer helped. So what I did so far is changed data source to the list, overwrote ToString method to display full address in list, added new item to RouteStop with unique id and set the DisplayMember to the uniqe id so I can access selected item in future by id as well.</p> <p>Thank you very much once again</p>
0
Removing Previous Button on First Step jQuery Steps
<p>I'm using jQuery Steps for my site signup wizard, works awesome with the exception that on the first step I'm getting the previous button, which really makes no sense since there is no previous content.</p> <p>I looked at the <code>onInit()</code> function in the API but there is no setting for <code>enablePreviousButton</code>, only <code>enableFinishButton</code> and <code>enableCancelButton</code>.</p> <p>Is there a way I can remove the Previous button on the first step?</p> <p>Requested code:</p> <pre><code>$("#register-form").steps({ headerTag: "h3", bodyTag: "fieldset", autoFocus: true, onInit: function (event, current) { alert(current); }, labels: { finish: 'Sign Up &lt;i class="fa fa-chevron-right"&gt;&lt;/i&gt;', next: 'Next &lt;i class="fa fa-chevron-right"&gt;&lt;/i&gt;', previous: '&lt;i class="fa fa-chevron-left"&gt;&lt;/i&gt; Previous' } }); </code></pre> <p>HTML:</p> <pre><code>&lt;h3&gt;&lt;?= $lang_wizard_account; ?&gt;&lt;/h3&gt; &lt;fieldset&gt; &lt;legend&gt;&lt;?= $lang_text_your_details; ?&gt;&lt;/legend&gt; &lt;div class="form-group"&gt; &lt;label class="control-label col-sm-3" for="username"&gt;&lt;b class="required"&gt;*&lt;/b&gt; &lt;?= $lang_entry_username; ?&gt;&lt;/label&gt; &lt;div class="col-sm-8"&gt; &lt;input type="text" name="username" value="&lt;?= $username; ?&gt;" class="form-control" placeholder="&lt;?= $lang_entry_username; ?&gt;" autofocus id="username" required&gt; &lt;?php if ($error_username) { ?&gt; &lt;span class="help-block error"&gt;&lt;?= $error_username; ?&gt;&lt;/span&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label class="control-label col-sm-3" for="firstname"&gt;&lt;b class="required"&gt;*&lt;/b&gt; &lt;?= $lang_entry_firstname; ?&gt;&lt;/label&gt; &lt;div class="col-sm-8"&gt; &lt;input type="text" name="firstname" value="&lt;?= $firstname; ?&gt;" class="form-control" placeholder="&lt;?= $lang_entry_firstname; ?&gt;" id="firstname" required&gt; &lt;?php if ($error_firstname) { ?&gt; &lt;span class="help-block error"&gt;&lt;?= $error_firstname; ?&gt;&lt;/span&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; .... &lt;/fieldset&gt; </code></pre>
0
OpenXml Edit text in the header of a word file
<p>I'm using Open XML and I should change the text in the header of a word file. To change a specific paragraph in the document I have used the following code:</p> <pre><code>Dim body = wdDoc.MainDocumentPart.Document.Body Dim paras = body.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Paragraph)() Dim header = body.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Header)() For Each para In paras For Each run In para.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Run)() For Each testo In run.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Text)() If (testo.Text.Contains("&lt;$doc_description$&gt;")) Then testo.Text = testo.Text.Replace("&lt;$doc_description$&gt;", "replaced-text") End If Next Next Next </code></pre> <p>thanks in advance!</p>
0
In Vue.js how do I write custom filters in separate file and use them in various components by declaring in main.js?
<p>I tried doing this, but it does not work. </p> <pre class="lang-js prettyprint-override"><code>// filter.js export default { converTimestamp: function (seconds) { var date = new Date(seconds * 1000); return date.toDateString(); } }; // main.js import customFilters from './store/filters'; </code></pre>
0
How to set items spacing in a horizontal menu?
<p>Horizontal menu items: </p> <pre><code> &lt;asp:MenuItem Text="Registration" Value="Registration"&gt;&lt;/asp:MenuItem&gt; &lt;asp:MenuItem Text="Log In" Value="Log In"&gt;&lt;/asp:MenuItem&gt; &lt;asp:MenuItem Text="About Us" Value="About Us"&gt;&lt;/asp:MenuItem&gt; </code></pre> <p>Problem: space between items is the same as the space between words in an item (Log In, About Us).<br> I'm looking for a property named "itemspace" or something like that, but, it seems there is no such one. Or, maybe, there is?</p>
0
How to clear input buffer in C?
<p>I have the following program:</p> <pre><code>int main(int argc, char *argv[]) { char ch1, ch2; printf("Input the first character:"); // Line 1 scanf("%c", &amp;ch1); printf("Input the second character:"); // Line 2 ch2 = getchar(); printf("ch1=%c, ASCII code = %d\n", ch1, ch1); printf("ch2=%c, ASCII code = %d\n", ch2, ch2); system("PAUSE"); return 0; } </code></pre> <p>As the author of the above code have explained: The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: <code>Enter key (ASCII code 13)</code> and <code>\n (ASCII code 10)</code>. Therefore, at Line 2, it will read the <code>\n</code> and will not wait for the user to enter a character.</p> <p>OK, I got this. But my first question is: Why the second <code>getchar()</code> (<code>ch2 = getchar();</code>) does not read the <code>Enter key (13)</code>, rather than <code>\n</code> character?</p> <p>Next, the author proposed 2 ways to solve such probrems:</p> <ol> <li><p>use <code>fflush()</code></p></li> <li><p>write a function like this:</p> <pre><code>void clear (void) { while ( getchar() != '\n' ); } </code></pre></li> </ol> <p>This code worked actually. But I cannot explain myself how it works? Because in the while statement, we use <code>getchar() != '\n'</code>, that means read any single character except <code>'\n'</code>? if so, in the input buffer still remains the <code>'\n'</code> character?</p>
0
Convert into void*
<p>how can I convert any object of my own class convert into pointer to void?</p> <pre><code>MyClass obj; (void*)obj; // Fail </code></pre>
0
Why is std::unordered_map slow, and can I use it more effectively to alleviate that?
<p>I’ve recently found out an odd thing. It seems that calculating Collatz sequence lengths with <a href="http://melpon.org/wandbox/permlink/xpx3rSzV6thjfz1q" rel="noreferrer">no caching at all</a> is over 2 times <em>faster</em> than <a href="http://melpon.org/wandbox/permlink/Omhqamehs2P6y7Or" rel="noreferrer">using <code>std::unordered_map</code> to cache all elements</a>.</p> <p>Note I did take hints from question <a href="https://stackoverflow.com/questions/11614106/is-gcc-stdunordered-map-implementation-slow-if-so-why">Is gcc std::unordered_map implementation slow? If so - why?</a> and I tried to used that knowledge to make <code>std::unordered_map</code> perform as well as I could (I used g++ 4.6, it did perform better than recent versions of g++, and I tried to specify a sound initial bucket count, I made it exactly equal to the maximum number of elements the map must hold).</p> <p>In comparision, <a href="http://melpon.org/wandbox/permlink/9YayIIQmPm8I1Hmm" rel="noreferrer">using <code>std::vector</code> to cache a few elements</a> was almost 17 times faster than no caching at all and almost 40 times faster than using <code>std::unordered_map</code>.</p> <p>Am I doing something wrong or is this container THAT slow and why? Can it be made performing faster? Or maybe hashmaps are inherently ineffective and should be avoided whenever possible in high-performance code?</p> <p>The problematic benchmark is:</p> <pre><code>#include &lt;iostream&gt; #include &lt;unordered_map&gt; #include &lt;cstdint&gt; #include &lt;ctime&gt; std::uint_fast16_t getCollatzLength(std::uint_fast64_t val) { static std::unordered_map &lt;std::uint_fast64_t, std::uint_fast16_t&gt; cache ({{1,1}}, 2168611); if(cache.count(val) == 0) { if(val%2 == 0) cache[val] = getCollatzLength(val/2) + 1; else cache[val] = getCollatzLength(3*val+1) + 1; } return cache[val]; } int main() { std::clock_t tStart = std::clock(); std::uint_fast16_t largest = 0; for(int i = 1; i &lt;= 999999; ++i) { auto cmax = getCollatzLength(i); if(cmax &gt; largest) largest = cmax; } std::cout &lt;&lt; largest &lt;&lt; '\n'; std::cout &lt;&lt; "Time taken: " &lt;&lt; (double)(std::clock() - tStart)/CLOCKS_PER_SEC &lt;&lt; '\n'; } </code></pre> <p>It outputs: <code>Time taken: 0.761717</code></p> <p>Whereas a benchmark with no caching at all:</p> <pre><code>#include &lt;iostream&gt; #include &lt;unordered_map&gt; #include &lt;cstdint&gt; #include &lt;ctime&gt; std::uint_fast16_t getCollatzLength(std::uint_fast64_t val) { std::uint_fast16_t length = 1; while(val != 1) { if(val%2 == 0) val /= 2; else val = 3*val + 1; ++length; } return length; } int main() { std::clock_t tStart = std::clock(); std::uint_fast16_t largest = 0; for(int i = 1; i &lt;= 999999; ++i) { auto cmax = getCollatzLength(i); if(cmax &gt; largest) largest = cmax; } std::cout &lt;&lt; largest &lt;&lt; '\n'; std::cout &lt;&lt; "Time taken: " &lt;&lt; (double)(std::clock() - tStart)/CLOCKS_PER_SEC &lt;&lt; '\n'; } </code></pre> <p>Outputs <code>Time taken: 0.324586</code></p>
0
How to rename a column and change its type by migration same time
<p>In my <code>general_exams</code> table, I have a column named <code>semester</code>, type is <code>string</code>. Now I want to change its name to <code>semester_id</code>, type is <code>integer</code>. I have read about migration and it has available transformations:</p> <ul> <li>rename_column(table_name, column_name, new_column_name): Renames a column but keeps the type and content.</li> <li>change_column(table_name, column_name, type, options): Changes the column to a different type using the same parameters as add_column.</li> </ul> <p>So, I create my migration file like this:</p> <pre><code>class RenameSemesterFromGeneralExams &lt; ActiveRecord::Migration def change rename_column :general_exams, :semester, :semester_id change_column :general_exams, :semester_id, :integer end end </code></pre> <p>But, when I run <code>rake db:migrate</code>, it has error:</p> <pre><code>== RenameSemesterFromGeneralExams: migrating ================================= -- rename_column(:general_exams, :semester, :semester_id) -&gt; 0.0572s -- change_column(:general_exams, :semester_id, :integer) rake aborted! An error has occurred, this and all later migrations canceled: PG::Error: ERROR: column "semester_id" cannot be cast to type integer : ALTER TABLE "general_exams" ALTER COLUMN "semester_id" TYPE integer </code></pre> <p>In my table GeneralExam, I destroyed all data. So, anyone can tell me how can I do that? Or I must create two migration files?</p>
0
Changing the background color of the selected options in a select box
<p><img src="https://i.stack.imgur.com/8Bdta.png" alt="enter image description here"></p> <p>I have to create a select box like this. I have been able to get this tree structure using optgroup but I am facing problems in changing the default background color of the selected option from default color to this orange color. I am aware of js solutions but I am more interested in pure HTML/CSS solution. It would be better if it will work in every browser, but no pressure ;)</p> <p>Thanks in advance.</p>
0
header/footer/nav tags - what happens to these in IE7, IE8 and browsers than don't support HTML5?
<p>I am eager to start using Html5 in particular the <code>&lt;header&gt;/&lt;footer&gt;/&lt;article&gt;/&lt;nav&gt;</code> tags.</p> <p>What happens if the browser doesn't support these?</p> <p>Also I need to style these so: For Example: The <code>nav</code> has borders and margins etc. You know standard CSS stuff.</p> <p>So if I style them using the <code>nav</code> tag then IE7 &amp; IE8 etc are going to ignore this?</p>
0
Can Spring Boot test classes reuse application context for faster test run?
<p><code>@ContextConfiguration</code> location attribute does not make sense for Spring Boot integration testing. Is there any other way for reusing application context across multiple test classes annotated with <code>@SpringBootTest</code> ? </p>
0
How to use Fonts in iText PDF
<p>I have a java application where i have to use "Bodoni MT Black" font using FontFactory in itextPdf how should i modify my code? This is my code,</p> <pre><code>Font base = FontFactory.getFont(FontFactory.TIMES_ROMAN, 6); </code></pre> <p>how to change font to "Bodoni MT Black" (Not supported in FontFactory) instead of TIMES_ROMAN? please help.</p>
0
How to catch the event of clicking the app window's close button in Electron app
<p>I wish to catch the event of clicking the app window's close button in Electron app.</p> <p>I'm trying to develope Electron app for Mac OSX. I want to hide the app window, not to terminate the app when a user clicks the window's close button like other Mac apps.</p> <p>However, I can not detect wether the system should be terminated or it should be hidden, because in any case, a <code>close</code> event of <code>browser-window</code> is called when a close button is clicked, the OS is shut down or the app is terminated with quit command, <code>Cmd+Q</code>.</p> <p>Is there any way to catch the event of clicking the app window's close button in Electron app?</p> <p>Thank you for your help.</p> <hr> <h3>Postscript</h3> <p>To detect the event of clicking a close button, I tried this code </p> <pre><code>var app = require('app'); var BrowserWindow = require('browser-window'); var Menu = require('menu'); var force_quit = false; var menu = Menu.buildFromTemplate([ { label: 'Sample', submenu: [ {label: 'About App', selector: 'orderFrontStandardAboutPanel:'}, {label: 'Quit', accelerator: 'CmdOrCtrl+Q', click: function() {force_quit=true; app.quit();}} ] }]); app.on('window-all-closed', function(){ if(process.platform != 'darwin') app.quit(); }); app.on('ready', function(){ Menu.setApplicationMenu(menu); mainWindow = new BrowserWindow({width:800, height:600}); mainWindow.on('close', function(e){ if(!force_quit){ e.preventDefault(); mainWindow.hide(); } }); mainWindow.on('closed', function(){ console.log("closed"); mainWindow = null; app.quit(); }); app.on('activate-with-no-open-windows', function(){ mainWindow.show(); }); }); </code></pre> <p>With this code, the app is hidden when a close button of the app window is clicked, and the app is terminated when <code>Cmd+Q</code> is typed. However, when I try to shut down the OS, the shutdown event is prevented. </p>
0
Add ReportViewer to Toolbox VB.NET 2013
<p>I installed Report Viewer 2012 in VS 2013 (VB.NET), but it's not listed as an component in toolbox. Where is the location to reference the ReportViewer via browse, or how do I add the ReportViewer to toolbox?</p> <p>I wasted all day trying to create a simple report.</p> <p>Any help greatly appreciated.</p>
0
How to give System property to my test via Gradle and -D
<p>I have a a Java program which reads a System property</p> <pre><code>System.getProperty("cassandra.ip"); </code></pre> <p>and I have a Gradle build file that I start with </p> <pre><code>gradle test -Pcassandra.ip=192.168.33.13 </code></pre> <p>or </p> <pre><code>gradle test -Dcassandra.ip=192.168.33.13 </code></pre> <p>however <strong>System.getProperty</strong> will always return <strong>null</strong>.</p> <p>The only way I found was to add that in my Gradle build file via</p> <pre><code>test { systemProperty "cassandra.ip", "192.168.33.13" } </code></pre> <p>How Do I do it via -D</p>
0
Project not Built in Active Configuration - Xamarin/Xamarin.Form
<p>I have downloaded Xamarin.Form sample projects from github <a href="https://github.com/xamarin/xamarin-forms-samples" rel="noreferrer">https://github.com/xamarin/xamarin-forms-samples</a></p> <p>Once I open any sample projects, it does not allow me to run on iOS Simulator.</p> <p>Does any one know how to handle this problem. I am using Xamarin Studio on Mac Operating System. </p> <p><img src="https://i.stack.imgur.com/jtfND.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/eusGc.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/ELLFN.png" alt="enter image description here"></p> <p><strong>UPDATE-1:</strong></p> <p>I have also found the following useful article regarding my issue <a href="http://crossplatform.io/2013/12/02/setting-the-active-configuration-in-xamarin-studio/" rel="noreferrer">http://crossplatform.io/2013/12/02/setting-the-active-configuration-in-xamarin-studio/</a></p> <p>I chose <code>TabbedPageDemo.iOS--&gt; iOS|Debug</code> then I could able to see iOS part, however it still does not give me an option of <strong>Set As Start Project</strong></p> <p><img src="https://i.stack.imgur.com/gho0I.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/p5Jhi.png" alt="enter image description here"></p>
0
Dynamically add controls to a silveright StackPanel to Create a menu
<p>hello community any one can please say how to add controls dynamically into a Stack Panel </p> <p>note: what i need is i have to create a menu which get data from database and creates menu items accordingly can any one say how can i create such menus i am new to silver light </p> <p>I am using silverlight 3 beta and expression blend3 + sketch flow please help me to know how to design those </p>
0
Can I instantiate a PHP class inside another class?
<p>I was wondering if it is allowed to create an instance of a class inside another class.</p> <p>Or, do I have to create it outside and then pass it in through the constructor? But then I would have created it without knowing if I would need it.</p> <p>Example (a database class):</p> <pre><code>class some{ if(.....){ include SITE_ROOT . 'applicatie/' . 'db.class.php'; $db=new db </code></pre>
0
Reading from a cryptostream to the end of the stream
<p>I'm having some trouble with the code below. I have a file in a temporary location which is in need of encryption, this function encrypts that data which is then stored at the "pathToSave" location.</p> <p>On inspection is does not seem to be handling the whole file properly - There are bits missing from my output and I suspect it has something to do with the while loop not running through the whole stream.</p> <p>As an aside, if I try and call CryptStrm.Close() after the while loop I receive an exception. This means that if I attempt to decrypt the file, I get a file already in use error! </p> <p>Tried all the usual and Ive looked on here at similar issues, any help would be great.</p> <p>Thanks</p> <pre><code>public void EncryptFile(String tempPath, String pathToSave) { try { FileStream InputFile = new FileStream(tempPath, FileMode.Open, FileAccess.Read); FileStream OutputFile = new FileStream(pathToSave, FileMode.Create, FileAccess.Write); RijndaelManaged RijCrypto = new RijndaelManaged(); //Key byte[] Key = new byte[32] { ... }; //Initialisation Vector byte[] IV = new byte[32] { ... }; RijCrypto.Padding = PaddingMode.None; RijCrypto.KeySize = 256; RijCrypto.BlockSize = 256; RijCrypto.Key = Key; RijCrypto.IV = IV; ICryptoTransform Encryptor = RijCrypto.CreateEncryptor(Key, IV); CryptoStream CryptStrm = new CryptoStream(OutputFile, Encryptor, CryptoStreamMode.Write); int data; while (-1 != (data = InputFile.ReadByte())) { CryptStrm.WriteByte((byte)data); } } catch (Exception EncEx) { throw new Exception("Encoding Error: " + EncEx.Message); } } </code></pre> <p>EDIT:</p> <p>I've made the assumption that my problem is with Encryption. My Decrypt might be the culprit </p> <pre><code> public String DecryptFile(String encryptedFilePath) { FileStream InputFile = new FileStream(encryptedFilePath, FileMode.Open, FileAccess.Read); RijndaelManaged RijCrypto = new RijndaelManaged(); //Key byte[] Key = new byte[32] { ... }; //Initialisation Vector byte[] IV = new byte[32] { ... }; RijCrypto.Padding = PaddingMode.None; RijCrypto.KeySize = 256; RijCrypto.BlockSize = 256; RijCrypto.Key = Key; RijCrypto.IV = IV; ICryptoTransform Decryptor = RijCrypto.CreateDecryptor(Key, IV); CryptoStream CryptStrm = new CryptoStream(InputFile, Decryptor, CryptoStreamMode.Read); String OutputFilePath = Path.GetTempPath() + "myfile.name"; StreamWriter OutputFile = new StreamWriter(OutputFilePath); OutputFile.Write(new StreamReader(CryptStrm).ReadToEnd()); CryptStrm.Close(); OutputFile.Close(); return OutputFilePath; } </code></pre>
0
Merging cv::Mat horizontally
<p>I want to merge a few <code>cv::Mat</code>, when I use <code>mat1.push_back(mat2)</code> it add <code>mat2</code> to the end of <code>mat1</code> vertically , is there a way to do this horizontally? The only other option I can think of is making every <code>cv::Mat</code> into a <code>cv::RotatedRect</code>, rotate it, creating a new <code>Mat</code>, merging, rotating everything in the end in the same way, but it sound pointlessly long if there is another way</p>
0
Generate random int in 3D array
<p>l would like to generate a random 3d array containing random integers (coordinates) in the intervalle [0,100].</p> <p>so, <code>coordinates=dim(30,10,2)</code></p> <p>What l have tried ?</p> <pre><code>coordinates = [[random.randint(0,100), random.randint(0,100)] for _i in range(30)] </code></pre> <p>which returns</p> <pre><code>array([[97, 68], [11, 23], [47, 99], [52, 58], [95, 60], [89, 29], [71, 47], [80, 52], [ 7, 83], [30, 87], [53, 96], [70, 33], [36, 12], [15, 52], [30, 76], [61, 52], [87, 99], [19, 74], [37, 63], [40, 2], [ 8, 84], [70, 32], [63, 8], [98, 89], [27, 12], [75, 59], [76, 17], [27, 12], [48, 61], [39, 98]]) </code></pre> <p>of shape <code>(30,10)</code></p> <p>What l'm supposed to get ?</p> <p>dim=(30,10,2) rather than (30,10)</p>
0
How to force FormRequest return json in Laravel 5.1?
<p>I'm using <a href="http://laravel.com/docs/5.1/validation#form-request-validation">FormRequest</a> to validate from which is sent in an API call from my smartphone app. So, I want FormRequest alway return json when validation fail.</p> <p>I saw the following source code of Laravel framework, the default behaviour of FormRequest is return json if reqeust is Ajax or wantJson.</p> <pre><code>//Illuminate\Foundation\Http\FormRequest class /** * Get the proper failed validation response for the request. * * @param array $errors * @return \Symfony\Component\HttpFoundation\Response */ public function response(array $errors) { if ($this-&gt;ajax() || $this-&gt;wantsJson()) { return new JsonResponse($errors, 422); } return $this-&gt;redirector-&gt;to($this-&gt;getRedirectUrl()) -&gt;withInput($this-&gt;except($this-&gt;dontFlash)) -&gt;withErrors($errors, $this-&gt;errorBag); } </code></pre> <p>I knew that I can add <code>Accept= application/json</code> in request header. FormRequest will return json. But I want to provide an easier way to request my API by support json in default without setting any header. So, I tried to find some options to force FormRequest response json in <code>Illuminate\Foundation\Http\FormRequest</code> class. But I didn't find any options which are supported in default. </p> <h2>Solution 1 : Overwrite Request Abstract Class</h2> <p>I tried to overwrite my application request abstract class like followings:</p> <pre><code>&lt;?php namespace Laravel5Cg\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\JsonResponse; abstract class Request extends FormRequest { /** * Force response json type when validation fails * @var bool */ protected $forceJsonResponse = false; /** * Get the proper failed validation response for the request. * * @param array $errors * @return \Symfony\Component\HttpFoundation\Response */ public function response(array $errors) { if ($this-&gt;forceJsonResponse || $this-&gt;ajax() || $this-&gt;wantsJson()) { return new JsonResponse($errors, 422); } return $this-&gt;redirector-&gt;to($this-&gt;getRedirectUrl()) -&gt;withInput($this-&gt;except($this-&gt;dontFlash)) -&gt;withErrors($errors, $this-&gt;errorBag); } } </code></pre> <p>I added <code>protected $forceJsonResponse = false;</code> to setting if we need to force response json or not. And, in each FormRequest which is extends from Request abstract class. I set that option. </p> <p>Eg: I made an StoreBlogPostRequest and set <code>$forceJsoResponse=true</code> for this FormRequest and make it response json.</p> <pre><code>&lt;?php namespace Laravel5Cg\Http\Requests; use Laravel5Cg\Http\Requests\Request; class StoreBlogPostRequest extends Request { /** * Force response json type when validation fails * @var bool */ protected $forceJsonResponse = true; /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'title' =&gt; 'required|unique:posts|max:255', 'body' =&gt; 'required', ]; } } </code></pre> <h2>Solution 2: Add an Middleware and force change request header</h2> <p>I build a middleware like followings: <pre><code>namespace Laravel5Cg\Http\Middleware; use Closure; use Symfony\Component\HttpFoundation\HeaderBag; class AddJsonAcceptHeader { /** * Add Json HTTP_ACCEPT header for an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $request-&gt;server-&gt;set('HTTP_ACCEPT', 'application/json'); $request-&gt;headers = new HeaderBag($request-&gt;server-&gt;getHeaders()); return $next($request); } } </code></pre> <p>It 's work. But I wonder is this solutions good? And are there any Laravel Way to help me in this situation ? </p>
0
resolve a java.util.ArrayList$SubList notSerializable Exception
<p>I am using SubList function on an object of type List. The problem is that I am using RMI and because the java.util.ArrayList$SubList is implemented by a non-serializable class I got the Exception described above when I try to pass the resulting object to a remote function taking as an argument a List as well. I've seen that I should copy the resulting List to a new LinkedList or ArrayList and pass that.</p> <p>Does anyone know a function that helps as to easily do that for this for example ?</p> <pre><code>List&lt;String&gt; list = originalList.subList(0, 10); </code></pre>
0
Remove milliseconds in a datetime field
<p>I converted a database from MS SQL to MySql using workbench. There is a table that has a column called <code>ActivityDate</code> (<code>datetime(6)</code>) . For some reason, when that column got converted it has a dot in the date like (<code>2013-05-03 11:20:20.420000</code>) .</p> <p>I want to remove the .420000 or whatever number is after the dot. I tried doing <code>SUBSTRING_INDEX(ActivityDate,'.',1)</code> but that didn't work, the last digits would just be <code>.000000</code> </p> <p>I also tried <code>UPDATE</code>alerts<code>.</code>activitylog<code>SET</code>ActivityDate<code>= date_format(ActivityDate, '%Y-%m-%d %H:%i') WHERE</code>activitylog<code>.</code>ActivityLogID<code>= 5;</code></p> <p>And same issue... I get <code>.000000</code> at the end</p> <p>How can I do this?</p>
0
Sorting an array of Objective-c objects
<p>So I have a custom class <code>Foo</code> that has a number of members:</p> <pre><code>@interface Foo : NSObject { NSString *title; BOOL taken; NSDate *dateCreated; } </code></pre> <p>And in another class I have an <code>NSMutableArray</code> containing a list of these objects. I would very much like to sort this array based on the <code>dateCreated</code> property; I understand I could write my own sorter for this (iterate the array and rearrange based on the date) but I was wondering if there was a proper Objective-C way of achieving this? </p> <p>Some sort of sorting mechanism where I can provide the member variable to sort by would be great. </p> <p>In C++ I used to overload the &lt; = > operators and this allowed me to sort by object, but I have a funny feeling Objective-C might offer a nicer alternative?</p> <p>Many thanks</p>
0
attempting to reference a deleted function
<p>I'm trying to learn about the fstream class and I'm having some trouble. I created a couple of txt files, one with a joke and the other with a punchline (joke.txt) and (punchline.txt) just for the sake of reading in and displaying content. I ask the user for the file name and if found it should open it up, clear the flags then read the content in. but I cant even test what it reads in because I'm currently getting errors regarding a deleted function but I don't know what that means</p> <p>error 1:</p> <pre><code>"IntelliSense: function "std::basic_ifstream&lt;_Elem, _Traits&gt;::basic_ifstream(const std::basic_ifstream&lt;_Elem, _Traits&gt;::_Myt &amp;) [with _Elem=char, _Traits=std::char_traits&lt;char&gt;]" (declared at line 818 of "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\fstream") cannot be referenced -- it is a deleted function </code></pre> <p>the second error is the exact same but for the 2nd function (displayLastLine())</p> <p>and error 3:</p> <pre><code>Error 1 error C2280: 'std::basic_ifstream&lt;char,std::char_traits&lt;char&gt;&gt;::basic_ifstream(const std::basic_ifstream&lt;char,std::char_traits&lt;char&gt;&gt; &amp;)' : attempting to reference a deleted function </code></pre> <p>and here's my code:</p> <pre><code>#include "stdafx.h" #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; using namespace std; void displayAllLines(ifstream joke); void displayLastLine(ifstream punchline); int main() { string fileName1, fileName2; ifstream jokeFile, punchlineFile; // Desribe the assigned project to the User cout &lt;&lt; "This program will print a joke and its punch line.\n\n"; cout &lt;&lt; "Enter the name of the joke file (ex. joke.txt): "; cin &gt;&gt; fileName1; jokeFile.open(fileName1.data()); if (!jokeFile) { cout &lt;&lt; " The file " &lt;&lt; fileName1 &lt;&lt; " could not be opened." &lt;&lt; endl; } else { cout &lt;&lt; "Enter name of punch line file (ex. punchline.txt): "; cin &gt;&gt; fileName2; punchlineFile.open(fileName2.data()); if (!punchlineFile) { cout &lt;&lt; " The file " &lt;&lt; fileName2 &lt;&lt; " could not be opened." &lt;&lt; endl; jokeFile.close(); } else { cout &lt;&lt; endl &lt;&lt; endl; displayAllLines(jokeFile); displayLastLine(punchlineFile); cout &lt;&lt; endl; jokeFile.close(); punchlineFile.close(); } } // This prevents the Console Window from closing during debug mode cin.ignore(cin.rdbuf()-&gt;in_avail()); cout &lt;&lt; "\nPress only the 'Enter' key to exit program: "; cin.get(); return 0; } void displayAllLines(ifstream joke) { joke.clear(); joke.seekg(0L, ios::beg); string jokeString; getline(joke, jokeString); while (!joke.fail()) { cout &lt;&lt; jokeString &lt;&lt; endl; } } void displayLastLine(ifstream punchline) { punchline.clear(); punchline.seekg(0L, ios::end); string punchString; getline(punchline, punchString); while (!punchline.fail()) { cout &lt;&lt; punchString &lt;&lt; endl; } } </code></pre>
0
Tracking model changes in SQLAlchemy
<p>I want to log every action what will be done with some SQLAlchemy-Models.</p> <p>So, I have a after_insert, after_delete and before_update hooks, where I will save previous and current representation of model,</p> <pre><code>def keep_logs(cls): @event.listens_for(cls, 'after_delete') def after_delete_trigger(mapper, connection, target): pass @event.listens_for(cls, 'after_insert') def after_insert_trigger(mapper, connection, target): pass @event.listens_for(cls, 'before_update') def before_update_trigger(mapper, connection, target): prev = cls.query.filter_by(id=target.id).one() # comparing previous and current model MODELS_TO_LOGGING = ( User, ) for cls in MODELS_TO_LOGGING: keep_logs(cls) </code></pre> <p>But there is one problem: when I'm trying to find model in before_update hook, SQLA returns modified (dirty) version. How can I get previous version of model before updating it? Is there a different way to keep model changes?</p> <p>Thanks!</p>
0
Calculate days to go until a particular date with momentjs
<p>I want to count down the days until a particular event using momentjs but I'm getting an unexpected result.</p> <p>With today's date being 17th April, and the event date being 14th May, I want the resulting number of days to be 27, however my code gives me a result of 57. What's wrong?</p> <pre><code>function daysRemaining() { var eventdate = moment([2015, 5, 14]); var todaysdate = moment(); return eventdate.diff(todaysdate, 'days'); } alert(daysRemaining()); </code></pre>
0
java 101, how do I count the number of arguments passed into main?
<p>For example</p> <pre><code>public static void main(String[] args) { int count = 0; for (String s: args) { System.out.println(s); count++; } } </code></pre> <p>is there some way of doing something like</p> <p>int count = args.length()? or args.size()?</p>
0
Export DataTable to Excel with Open Xml SDK in c#
<p>My program have ability to export some data and DataTable to Excel file (template) In the template I insert the data to some placeholders. It's works very good, but I need to insert a DataTable too... My sample code:</p> <pre><code>using (Stream OutStream = new MemoryStream()) { // read teamplate using (var fileStream = File.OpenRead(templatePath)) fileStream.CopyTo(OutStream); // exporting Exporting(OutStream); // to start OutStream.Seek(0L, SeekOrigin.Begin); // out using (var resultFile = File.Create(resultPath)) OutStream.CopyTo(resultFile); </code></pre> <p>Next method to exporting</p> <pre><code>private void Exporting(Stream template) { using (var workbook = SpreadsheetDocument.Open(template, true, new OpenSettings { AutoSave = true })) { // Replace shared strings SharedStringTablePart sharedStringsPart = workbook.WorkbookPart.SharedStringTablePart; IEnumerable&lt;Text&gt; sharedStringTextElements = sharedStringsPart.SharedStringTable.Descendants&lt;Text&gt;(); DoReplace(sharedStringTextElements); // Replace inline strings IEnumerable&lt;WorksheetPart&gt; worksheetParts = workbook.GetPartsOfType&lt;WorksheetPart&gt;(); foreach (var worksheet in worksheetParts) { DoReplace(worksheet.Worksheet.Descendants&lt;Text&gt;()); } int z = 40; foreach (System.Data.DataRow row in ExcelWorkXLSX.ToOut.Rows) { for (int i = 0; i &lt; row.ItemArray.Count(); i++) { ExcelWorkXLSX.InsertText(workbook, row.ItemArray.ElementAt(i).ToString(), getColumnName(i), Convert.ToUInt32(z)); } z++; } } } } </code></pre> <p>But this fragment to output DataTable slooooooooooooooooooooooowwwwwww...</p> <p>How can I export DataTable to Excel fast and truly?</p>
0
Connecting Crystal Reports to an SQL Server
<p>So I've gone into the 'database expert', but I can't seem to figure out how to add the db to the report.</p> <p>Any ideas?</p> <p>P.S. I'm using CR 13 and SQL Server 2012</p>
0
Show untracked files as git diff
<p>When using <code>git diff</code> it only shows files which are already been tracked. Is there a way to show the untracked files as well for a diff? The goal is to get a git patch that also contains this, namely I have a script which starts with <code>git diff</code> and eventually pipes it to <code>git apply</code></p>
0
NodeJS /Electron Confusion about client/server code
<p>This is a beginner kind of question. I haven't used NodeJS before, so it's a bit confusing to me. I don't see a clear separation between server modules and client modules. It seems like I can use "npm" (Node's package manager) to install both client modules and server modules.</p> <p>My question is specifically related to this page: <a href="http://electron.atom.io/docs/v0.36.8/api/synopsis/" rel="noreferrer">http://electron.atom.io/docs/v0.36.8/api/synopsis/</a></p> <p>It says that I can use Node modules on client side:</p> <blockquote> <p>The renderer process is no different than a normal web page, except for the extra ability to use node modules:</p> </blockquote> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;script&gt; const remote = require('electron').remote; console.log(remote.app.getVersion()); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>How does this make any sense? Node is running on the server side, how is the browser ("renderer" process as they call it) able to use Node's packages?</p>
0
How to set and trigger an css transition from JavaScript
<p>I'm new to html5, css and javascript, And mostly I've just been playing around. What I want to do is to set and trigger a transition of a div. After the page is loaded, I manage to do that by setting a transition. But that doesn't feel very dynamic and doesn't seem the right way to go. I am thankful for any help</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; body{ text-align: center; } #dialPointer { position:relative; margin-left: auto; margin-right: auto; width:23px; height:281px; background:url(pointer.png); background-size:100% 100%; background-repeat:no-repeat; transform: rotate(-150deg); transition-duration: 2s; transition-delay: 2s; -webkit-transform: rotate(-150deg); -webkit-transition-duration:2s; -webkit-transition-delay: 2s; } /* I want to call this once */ .didLoad { width:23px; height:281px; transform:rotate(110deg); -moz-transform:rotate(110deg); /* Firefox 4 */ -webkit-transform:rotate(110deg); /* Safari and Chrome */ -o-transform:rotate(110deg); /* Opera */ } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="dialPointer"&gt;&lt;/div&gt; &lt;script language="javascript" type="text/javascript"&gt; window.onload=function () { //But instead of using rotate(110deg), I would like to call "didLoad" document.getElementById("dialPointer").style.webkitTransform = "rotate(110deg)"; }; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
0
Scrolling a Scroll Area in Qt
<p>I just have a Scroll Area widget that consists of several Qlabels .</p> <p>take a look at the situation:</p> <p><img src="https://i.stack.imgur.com/oifPV.png" alt="Widgets Inside Scroll Area" /></p> <p>I tried to to do the following but it didn't work out, its doesn't scroll ...</p> <pre><code>#include &quot;form1.h&quot; #include &quot;form.h&quot; #include &quot;ui_form.h&quot; #include &quot;ui_form1.h&quot; #include&lt;QScrollArea&gt; #include&lt;QScrollBar&gt; Form::Form(QWidget *parent) : QWidget(parent), ui(new Ui::Form) { ui-&gt;setupUi(this); ui-&gt;scrollAreaWidgetContents-&gt;setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); ui-&gt;scrollAreaWidgetContents-&gt;resize(ui-&gt;scrollArea-&gt;size().width() ,ui-&gt;scrollArea-&gt;size().height()); ui-&gt;scrollArea-&gt;setWidgetResizable(true); ui-&gt;scrollArea-&gt;setWidget(ui-&gt;scrollAreaWidgetContents); ui-&gt;scrollAreaWidgetContents-&gt;adjustSize(); } </code></pre> <p>Please Can you tell me what am doing wrong or what am not understanding ?? please be specific , I would appreciate it...</p>
0
How to populate the value of a Text Box based on the value in a Combo Box in MS Access 2007?
<p>I have a combo box which is of a lookup type, i.e., I've selected the source to be a column from a table and am storing the selected value in another table. The table which I am looking up has another column and I need the value in this column to be displayed in a text box and each time I change the value in the combo box, I need the corresponding value to be displayed in the text box. How can I do this? What I have done so far is to write a <code>Select</code> query that selects the appropriate column based on the combo box's value. Is there a more decent way of doing this? Please help me!</p>
0
UNION ALL query: "Too Many Fields Defined"
<p>I'm trying to get a UNION of 3 tables, each of which have 97 fields. I've tried the following:</p> <pre><code>select * from table1 union all select * from table2 union all select * from table3 </code></pre> <p>This gives me an error message:</p> <pre><code>Too many fields defined. </code></pre> <p>I also tried explicitly selecting all the field names from the first table (ellipses added for brevity):</p> <pre><code>select [field1],[field2]...[field97] from table1 union all select * from table2 union all select * from table3 </code></pre> <p>It works fine when I only UNION two tables like this:</p> <pre><code>select * from table1 union all select * from table2 </code></pre> <p>I shouldn't end up with more than 97 fields as a result of this query; the two-table UNION only has 97. So why am I getting <code>Too many fields</code> with 3 tables?</p> <p>EDIT: As RichardTheKiwi notes below, Access is summing up the field count of each SELECT query in the UNION chain, which means that my 3 tables exceed the 255 field maximum. So instead, I need to write the query like this:</p> <pre><code>select * from table1 union all select * from (select * from table2 union all select * from table3) </code></pre> <p>which works fine.</p>
0
Android Custom Shape Button
<p>How can i make a custom shaped clickable view or button in Android? </p> <p>When I click , I want to avoid touching on an empty area .</p> <p><img src="https://i.stack.imgur.com/PpkBo.png" alt="enter image description here"></p> <p>please help. Thank you. </p>
0
Inserting blocks into custom places in Magento2
<p>In Magento 1</p> <p>I can edit <code>local.xml</code> like so:</p> <pre><code>&lt;default&gt; &lt;reference name="root"&gt; &lt;block type="core/template" name="above_main" template="page/html/banner.phtml" /&gt; &lt;/reference&gt; &lt;/default&gt; </code></pre> <p>I can edit a template file like so:</p> <pre><code>&lt;body&lt;?php echo $this-&gt;getBodyClass()?' class="'.$this-&gt;getBodyClass().'"':'' ?&gt;&gt; &lt;?php echo $this-&gt;getChildHtml('after_body_start') ?&gt; &lt;div class="wrapper"&gt; &lt;?php echo $this-&gt;getChildHtml('global_notices') ?&gt; &lt;div class="page"&gt; &lt;?php echo $this-&gt;getChildHtml('header') ?&gt; &lt;?php // MY EDIT: ?&gt; &lt;?php echo $this-&gt;getChildHtml('above_main'); &lt;div class="main-container col2-left-layout"&gt; &lt;div class="main"&gt; &lt;?php echo $this-&gt;getChildHtml('breadcrumbs') ?&gt; &lt;!-- rest of page... --&gt; </code></pre> <p>This will end up with the file at <code>page/html/banner.phtml</code> being inserted into the template at my own custom position, <code>above_main</code>.</p> <p>OK, so my question is:</p> <p>How do I do this in Magento 2?</p>
0
Oracle ManagedDataAccess - Connection Request Timed out - Pooling
<p>I'm finally admitting defeat and asking for help. I've done everything I can think of to solve this problem, but it seems I'm incapable of doing it.</p> <p>I'm working with: VS2010 C# Oracle 12c ODP.Net Managed121012</p> <p>I have inherited an app that uses both the managed and unmanaged dataaccess dll. It was working until I de-installed oracle. I then re-installed the 11g client for a 64bit machine. Right away I noticed that there was only dataaccess dll for framework 2 installed, but I continued anyway. I then copied all the oci and ora dlls from the client_1 folder into the bin directory of my app as well as the Oracle.DataAccess.dll into my bin directory too. I also copied Oracle.ManagedDataAccess.dll into this folder.</p> <p>My application ran successfully as long as I didn't change anything on my datasets. I would have happily carried on like this, except I have to create more datasets. When I tried to add a new dataset, my data source connection wizard drop down list was blank. Then I tried to re-create the connections, but could only see the .Net Framework DProviders. I could not see the managed provider. At some point I also got this error "no data provider is currently selected".</p> <p>Thinking it's because the managed provider wasn't installed I uninstalled the 11g client and installed the 64bit 12c client and copied all the relevant files into the bin of my app. I added the following lines to my app.config file:</p> <pre><code> &lt;configSections&gt; &lt;section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess" /&gt; </code></pre> <p></p> <pre><code> &lt;system.data&gt; &lt;DbProviderFactories&gt; &lt;remove invariant="Oracle.DataAccess.Client" /&gt; &lt;remove invariant="Oracle.ManagedDataAccess.Client" /&gt; &lt;add name="ODP.NET, Managed Driver" invariant="Oracle.DataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" /&gt; &lt;/DbProviderFactories&gt; </code></pre> <p></p> <p>After this I can now see some of the old data sources, but I can't connect to my database because I get a "Connection Request Timed out". When I manually creating a new connection, I can connect fine with the unmanaged provider, but get a connection request timed out error. </p> <p>I'm really at the end of my rope and would really appreciate fresh eyes before I use the rope.</p> <p>Thanks in advance.</p>
0
Convert multiple lines to single line using text editor
<p>I have the following words each in a line in a text editor</p> <pre><code> 'about', 'above', 'across', 'after', 'afterwards', 'again', 'against', 'all', 'almost', 'alone', </code></pre> <p>Can some help me to convert the above content into a single line using a text editor</p> <pre><code>'about', 'above', 'across', 'after', 'afterwards', 'again', 'against', 'all', 'almost', 'alone', </code></pre>
0
Live reload for thymeleaf template
<p>When I change a thymeleaf .html file residing inside /templates , I expect the browser to automatically reload the page. I have the live reload plugin installed and its able to do a handshake with the spring boot server. However , upon chaning a thymeleaf template file , I have to manually reload the browser. Any suggestions what I might be missing. Obviously I have <code>spring-boot-devtools</code> enabled and have also manually updated the property <code>devtools.livereload.enabled = true</code>. And spring devtools is correctly relecting changes to any template or controller in build target , and with a manual reload of browser , I see the changes.</p> <p>As per spring docs.</p> <blockquote> <p>Certain resources do not necessarily need to trigger a restart when they are changed. For example, Thymeleaf templates can be edited in-place. By default, changing resources in /META-INF/maven, /META-INF/resources, /resources, /static, /public, or /templates does not trigger a restart but does trigger a <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-devtools.html#using-boot-devtools-livereload" rel="noreferrer">live reload</a>.</p> </blockquote> <p>I have my local running over a broken https. ( Some certificate issue , which causes a <code>not secure</code> message in chrome address bar. Could this be the reason live reload is not working. </p>
0
modifying arrays in java
<p>So I'm trying to figure out how to take user input thru the Scanner object, place it in each slot of an array, then read those numbers back to the user plus one. Problem is I have to use a a loop for the read back statement.Heres what I have so far. I figured out the first loop fine with the scanner, but I don't know how to modify each element in the array using a loop. </p> <pre><code>import java.util.Scanner; public class Lab7 { public static void main(String [] Args) { Scanner console = new Scanner(System.in); System.out.println("Enter your 5 integers: "); int index =0; final int SIZE = 5; int[] arrayOfSize = new int[SIZE]; while(index&lt;arrayOfSize.length ) { arrayOfSize[index]=console.nextInt(); index++; } System.out.println("Processing each array element..."); </code></pre>
0
gettimeofday() not declared in this scope - Cygwin
<p>Can cygwin make use of gettimeofday()? I'm getting the error:</p> <pre><code>lab8.cpp: In function ‘int main()’: lab8.cpp:62:30: error: ‘gettimeofday’ was not declared in this scope gettimeofday(&amp;start, NULL); ^ makefile:14: recipe for target 'lab8.o' failed make: *** [lab8.o] Error 1 </code></pre> <p>I definitely included <code>&lt;sys/time.h&gt;</code>. Is there a package that I have to install or does it just not work on Windows?</p> <p>EDIT: Here's a simple test that yields the same error:</p> <pre><code>#include &lt;sys/time.h&gt; int main() { struct timeval start; gettimeofday(&amp;start, NULL); } </code></pre> <p>With the error:</p> <pre><code>$ g++ -c -Wall -g -std=c++11 test.cpp -o test.o test.cpp: In function ‘int main()’: test.cpp:6:30: error: ‘gettimeofday’ was not declared in this scope gettimeofday(&amp;start, NULL); </code></pre>
0
UIView doesn't resize to full screen when hiding the nav bar & tab bar
<p>I have an app that has a tab bar &amp; nav bar for normal interaction. One of my screens is a large portion of text, so I allow the user to tap to go full screen (sort of like Photos.app).</p> <p>The nav bar &amp; tab bar are hidden, and I set the the text view's frame to be full screen. The problem is, there is about 50px of white space where the tab bar used to be. You can see if from this screen shot:</p> <p><em>removed dead ImageShack link</em></p> <p>I'm not sure what's causing this. The whitespace is definitely not the view behind the text view, as I set it's background color to red just to be sure. What could be causing this?</p> <p>** UPDATE **</p> <p>I did some hit testing in a UIWindow subclass and found out that the whitespace is actually the undocumented/unpublished UILayoutContainerView. This is the parent view of the tabBar. I don't think it's recommended to directly manipulate this view, so how can I hide the tab bar?</p> <p>** UPDATE # 2 **</p> <p>I checked self.view's frame before &amp; after animation, and it looks like the parent view is not resizing enough.</p> <p>after going fullscreen, the view's frame is only 411 pixels tall. I've tried messing with the frame manually and also setting autoResizeMask with no luck.</p> <p>**** UPDATE: Here's the end result ****</p> <pre><code>- (void)toggleFullscreen { isFullScreen = !isFullScreen; //ivar //hide status bar &amp; navigation bar [[UIApplication sharedApplication] setStatusBarHidden:isFullScreen animated:YES]; [self.navigationController setNavigationBarHidden:isFullScreen animated:YES]; [UIView beginAnimations:@&quot;fullscreen&quot; context:nil]; [UIView setAnimationBeginsFromCurrentState:YES]; [UIView setAnimationDuration:.3]; //move tab bar up/down CGRect tabBarFrame = self.tabBarController.tabBar.frame; int tabBarHeight = tabBarFrame.size.height; int offset = isFullScreen ? tabBarHeight : -1 * tabBarHeight; int tabBarY = tabBarFrame.origin.y + offset; tabBarFrame.origin.y = tabBarY; self.tabBarController.tabBar.frame = tabBarFrame; //fade it in/out self.tabBarController.tabBar.alpha = isFullScreen ? 0 : 1; //resize webview to be full screen / normal [webView removeFromSuperview]; if(isFullScreen) { //previousTabBarView is an ivar to hang on to the original view... previousTabBarView = self.tabBarController.view; [self.tabBarController.view addSubview:webView]; webView.frame = [self getOrientationRect]; //checks orientation to provide the correct rect } else { [self.view addSubview:webView]; self.tabBarController.view = previousTabBarView; } [UIView commitAnimations]; } </code></pre> <p>(note that I switched textview to webview, but the same works for the original text view)</p>
0
Python and Intellisense
<p>Is there an equivalent to 'intellisense' for Python?</p> <p>Perhaps i shouldn't admit it but I find having intellisense really speeds up the 'discovery phase' of learning a new language. For instance switching from VB.net to C# was a breeze due to snippets and intellisense helping me along.</p>
0
Taking multiple integers on the same line as input from the user in python
<p>I know how to take a single input from user in <code>python 2.5</code>:</p> <pre><code>raw_input("enter 1st number") </code></pre> <p>This opens up one input screen and takes in the first number. If I want to take a second input I need to repeat the same command and that opens up in another dialogue box. How can I take two or more inputs together in the same dialogue box that opens such that:</p> <pre><code>Enter 1st number:................ enter second number:............. </code></pre>
0
Running an angular 2 application built locally on Chrome using angular-cli without a node server
<p>I will make my <strong>Angular 2</strong> question very precise.</p> <p><strong>1. I am using:</strong> </p> <p>Angular 2, angular-cli: 1.0.0-beta.15, ( webpack building ) node: 6.4.0, os: linux x64</p> <p><strong>2. What I want to achieve:</strong></p> <p>I want to build my project in a way that after the build <strong>( ng build project-name )</strong> I get static files of my Angular 2 application, which I can run directly from chrome without using <strong>ng serve</strong> or the node server. <strong>I just want to double click index.html and run the app locally.</strong></p> <p><strong>3. Meanwhile, what I get in the chrome browser console output when I double click the generated index.html is:</strong></p> <blockquote> <p>file:///inline.js Failed to load resource: net::ERR_FILE_NOT_FOUND file:///styles.b52d2076048963e7cbfd.bundle.js Failed to load resource: net::ERR_FILE_NOT_FOUND file:///main.c45bb457f14bdc0f5b96.bundle.js Failed to load resource: net::ERR_FILE_NOT_FOUND file:///favicon.ico Failed to load resource: net::ERR_FILE_NOT_FOUND</p> </blockquote> <ol start="4"> <li><p>As I understand this is related to paths. The built and bundled application cannot find the right paths. So my question is <strong>where</strong> and <strong>how</strong> I should change <strong>the paths</strong> in my app or in any <strong>build configuration files</strong> in order for my app to work like I would like it to work in the way I have described in <strong>point number 2</strong> </p></li> <li><p>Thank you in advance for a direct and full answer on that topic, because other topics are not explaining the full scope on that subject. </p></li> </ol>
0
np arrays being immutable - "assignment destination is read-only"
<p>FD** - I am a Python newb as well as a stack overflow newb as you can tell. I have edited the question based on comments.</p> <p>My goal is to read a set of PNG files, create Image(s) with Image.open('filename') and convert them to simple 2D arrays with only 1s and 0s. The PNG is of the format RGBA with mostly only 255 and 0 as values. Quite often in the images, the edges are grey scale values, which I would like to avoid in the 2D array. </p> <p>I created the 2D array from image using np.asarray(Image) getting only the 'Red' channel. In each of the 2d image array, I would like to set the cell value = 1 if the current value is non zero.</p> <p>So, I loop into the 2d array and I check the cell value and try to set it to 1.</p> <p>It gives me an error indicating that the array is read-only. I read through several stack overflow threads discussing that np arrays are immutable and it is a still bit unclear. I use PIL and numpy</p> <p>Thanks @user2314737. I will attempt to set that flag. @Eric, thanks for your comments as well. </p> <pre><code>from PIL import Image import numpy as np </code></pre> <p>The relevant code:</p> <pre><code>prArray = [np.asarray(img)[:, :, 0] for img in problem_images] for img in prArray: for x in range(184): for y in range(184): if img[x][y] != 0: img[x][y] = 1 </code></pre> <p>The error "assignment destination is read-only" is in the last line.</p> <p>Thank you everyone for help. </p>
0
SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' - Gulp
<p>Consider the following two files:</p> <p><code>app.js</code></p> <pre><code>import Game from './game/game'; import React from 'react'; import ReactDOM from 'react-dom'; export default (absPath) =&gt; { let gameElement = document.getElementById("container"); if (gameElement !== null) { ReactDOM.render( &lt;Game mainPath={absPath} /&gt;, gameElement ); } } </code></pre> <p><code>index.js</code></p> <pre><code>import App from './src/app'; </code></pre> <p>The <code>gulpfile.js</code></p> <pre><code>var gulp = require('gulp'); var source = require('vinyl-source-stream'); var browserify = require('browserify'); var babelify = require("babelify"); var watch = require('gulp-watch'); gulp.task('make:game', function(){ return browserify({ entries: [ 'index.js' ] }) .transform('babelify') .bundle() .pipe(source('index.js')) .pipe(gulp.dest('app/')); }); </code></pre> <p>The error:</p> <pre><code>gulp make:game [13:09:48] Using gulpfile ~/Documents/ice-cream/gulpfile.js [13:09:48] Starting 'make:game'... events.js:154 throw er; // Unhandled 'error' event ^ SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' </code></pre> <p><strong>What is this error? What am I doing wrong?</strong></p>
0
keras error on predict
<p>I am trying to use a keras neural network to recognize canvas images of drawn digits and output the digit. I have saved the neural network and use django to run the web interface. But whenever I run it, I get an internal server error and an error on the server side code. The error says <strong>Exception: Error when checking : expected dense_input_1 to have shape (None, 784) but got array with shape (784, 1)</strong>. My only main view is </p> <pre><code>from django.shortcuts import render from django.http import HttpResponse import StringIO from PIL import Image import numpy as np import re from keras.models import model_from_json def home(request): if request.method=="POST": vari=request.POST.get("imgBase64","") imgstr=re.search(r'base64,(.*)', vari).group(1) tempimg = StringIO.StringIO(imgstr.decode('base64')) im=Image.open(tempimg).convert("L") im.thumbnail((28,28), Image.ANTIALIAS) img_np= np.asarray(im) img_np=img_np.flatten() img_np.astype("float32") img_np=img_np/255 json_file = open('model.json', 'r') loaded_model_json = json_file.read() json_file.close() loaded_model = model_from_json(loaded_model_json) # load weights into new model loaded_model.load_weights("model.h5") # evaluate loaded model on test data loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) output=loaded_model.predict(img_np) score=output.tolist() return HttpResponse(score) else: return render(request, "digit/index.html") </code></pre> <p>The links I have checked out are:</p> <ul> <li><a href="https://stackoverflow.com/questions/37901698/error-error-when-checking-model-input-expected-dense-input-6-to-have-shape-no">Here</a></li> <li><a href="https://github.com/fchollet/keras/issues/3109" rel="noreferrer"> Here </a></li> <li><a href="http://machinelearningmastery.com/handwritten-digit-recognition-using-convolutional-neural-networks-python-keras/" rel="noreferrer">and Here</a></li> </ul> <p><strong>Edit</strong> Complying with Rohan's suggestion, this is my stack trace</p> <pre><code>Internal Server Error: /home/ Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vivek/keras/neural/digit/views.py", line 27, in home output=loaded_model.predict(img_np) File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 671, in predict return self.model.predict(x, batch_size=batch_size, verbose=verbose) File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1161, in predict check_batch_dim=False) File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 108, in standardize_input_data str(array.shape)) Exception: Error when checking : expected dense_input_1 to have shape (None, 784) but got array with shape (784, 1) </code></pre> <p>Also, I have my model that I used to train the network initially.</p> <pre><code>import numpy from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.utils import np_utils # fix random seed for reproducibility seed = 7 numpy.random.seed(seed) (X_train, y_train), (X_test, y_test) = mnist.load_data() for item in y_train.shape: print item num_pixels = X_train.shape[1] * X_train.shape[2] X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32') X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32') # normalize inputs from 0-255 to 0-1 X_train = X_train / 255 X_test = X_test / 255 print X_train.shape # one hot encode outputs y_train = np_utils.to_categorical(y_train) y_test = np_utils.to_categorical(y_test) num_classes = y_test.shape[1] # define baseline model def baseline_model(): # create model model = Sequential() model.add(Dense(num_pixels, input_dim=num_pixels, init='normal', activation='relu')) model.add(Dense(num_classes, init='normal', activation='softmax')) # Compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) return model # build the model model = baseline_model() # Fit the model model.fit(X_train, y_train, validation_data=(X_test, y_test), nb_epoch=20, batch_size=200, verbose=1) # Final evaluation of the model scores = model.evaluate(X_test, y_test, verbose=0) print("Baseline Error: %.2f%%" % (100-scores[1]*100)) # serialize model to JSON model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights("model.h5") print("Saved model to disk") </code></pre> <p><strong>Edit</strong> I tried reshaping the img to (1,784) and it also failed, giving the same error as the title of this question</p> <p>Thanks for the help, and leave comments on how I should add to the question.</p>
0
How to setup conditionals for BPMN2 Exclusive Gateway
<p>I'm using Camunda BPMN2 for the first time in my spring project and trying to get my head around a couple of things ...</p> <p>In my applicationContext, I have the following block to setup Camunda:</p> <pre><code> &lt;!-- Setup BPMN Process Engine --&gt; &lt;bean id="processEngineConfiguration" class="org.camunda.bpm.engine.spring.SpringProcessEngineConfiguration"&gt; &lt;property name="processEngineName" value="engine" /&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="transactionManager" ref="transactionManager" /&gt; &lt;property name="databaseSchemaUpdate" value="true" /&gt; &lt;property name="jobExecutorActivate" value="false" /&gt; &lt;property name="deploymentResources" value="classpath*:*.bpmn" /&gt; &lt;/bean&gt; &lt;bean id="processEngine" class="org.camunda.bpm.engine.spring.ProcessEngineFactoryBean"&gt; &lt;property name="processEngineConfiguration" ref="processEngineConfiguration" /&gt; &lt;/bean&gt; &lt;bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService" /&gt; &lt;bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService" /&gt; &lt;bean id="taskService" factory-bean="processEngine" factory-method="getTaskService" /&gt; &lt;bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService" /&gt; &lt;bean id="managementService" factory-bean="processEngine" factory-method="getManagementService" /&gt; &lt;context:annotation-config /&gt; </code></pre> <p>I've setup two services:</p> <pre><code>@Component(value="service1") public class Service1 implements JavaDelegate { @Override public void execute(DelegateExecution execution) throws Exception { System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;"); System.out.println("SERVICE1"); System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;"); } } </code></pre> <p>and </p> <pre><code>@Component(value="service2") public class Service2 implements JavaDelegate { @Override public void execute(DelegateExecution execution) throws Exception { System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;"); System.out.println("SERVICE2"); System.out.println("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;"); } } </code></pre> <p>In scenario 1 I have a parallel gateway that calls both Service1 and Service2 (I've built these diagrams using BPMN2 editor in eclipse):</p> <p><img src="https://i.stack.imgur.com/7707I.png" alt="scenario 1"></p> <p><img src="https://i.stack.imgur.com/gLiJB.png" alt="scenario 1 - service 1"></p> <p><img src="https://i.stack.imgur.com/eWYDP.png" alt="scenario 1 - service 2"></p> <p>Running this line of code:</p> <pre><code>runtimeService.startProcessInstanceByKey("ConnectorSwitch"); </code></pre> <p>Prints out </p> <pre><code>&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; SERVICE1 &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; SERVICE2 &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; </code></pre> <p>as expected.</p> <p>Now I'm trying to put in an Exclusive Gateway:</p> <p><img src="https://i.stack.imgur.com/fbVoF.png" alt="enter image description here"></p> <p>Running it gives me the following exception:</p> <pre><code>SEVERE: Error while closing command context org.camunda.bpm.engine.ProcessEngineException: Exclusive Gateway 'ExclusiveGateway_3' has outgoing sequence flow 'SequenceFlow_39' without condition which is not the default flow. | ..../ConnectorSwitch.bpmn | line 0 | column 0 Exclusive Gateway 'ExclusiveGateway_3' has outgoing sequence flow 'SequenceFlow_40' without condition which is not the default flow. | ..../ConnectorSwitch.bpmn | line 0 | column 0 at org.camunda.bpm.engine.impl.util.xml.Parse.throwExceptionForErrors(Parse.java:183) at org.camunda.bpm.engine.impl.bpmn.parser.BpmnParse.execute(BpmnParse.java:177) at org.camunda.bpm.engine.impl.bpmn.deployer.BpmnDeployer.deploy(BpmnDeployer.java:106) at org.camunda.bpm.engine.impl.persistence.deploy.DeploymentCache.deploy(DeploymentCache.java:50) at org.camunda.bpm.engine.impl.persistence.entity.DeploymentManager.insertDeployment(DeploymentManager.java:42) at org.camunda.bpm.engine.impl.cmd.DeployCmd.execute(DeployCmd.java:81) at org.camunda.bpm.engine.impl.cmd.DeployCmd.execute(DeployCmd.java:50) at org.camunda.bpm.engine.impl.interceptor.CommandExecutorImpl.execute(CommandExecutorImpl.java:24) at org.camunda.bpm.engine.impl.interceptor.CommandContextInterceptor.execute(CommandContextInterceptor.java:90) at org.camunda.bpm.engine.spring.SpringTransactionInterceptor$1.doInTransaction(SpringTransactionInterceptor.java:42) at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:130) ...... </code></pre> <p>The exception is pretty clear, I'm missing a condition on the Exclusive Gateway. So my question is, how do I assign a condition to the exclusive gateway, how do I call a method in a certain class and evaluate the true / false and if I want to call something else that is not a JavaDelegate for service1 / service2 (in other words, MyClass.doSomethingWithParams(someparam)), how would I go about that?</p> <p>Answers in XML is fine as well, would prefer to learn how to use BPMN2 in XML instead of relying on the BPMN2 visuals.</p>
0
How do I add a manifest to an executable using mt.exe?
<p>I'm trying to use mt.exe from the Windows SDK to add a manifest to an executable file that doesn't have one, using the following command line:</p> <pre><code>C:\winsdk61&gt;mt.exe -nologo -manifest "r:\shared\hl.exe.manifest" -updateresource:"r:\shared\hl33m.exe;#1" </code></pre> <p>Unfortunately, when I do, I get this error:</p> <pre><code>mt.exe : general error c101008c: Failed to read the manifest from the resource of file "r:\shared\hl33m.exe". The specified resource type cannot be found in the image file. </code></pre> <p>Of course the resource wasn't found in the file - the file doesn't have a manifest, that's why I want to add one.</p> <p>How can I append a manifest to an executable file? Shouldn't this be simple?</p>
0
Easy way to determine leap year in ruby?
<p>Is there an easy way to determine if a year is a leap year?</p>
0
intellij-idea The system cannot find the file specified,
<p>can someone help me? i'm pretty new to programming, I decided to give IDEA a try comming from eclipse and I have run into a problem I have imported a project from eclipse that works but in IDEA I cant referance my res folder like I do in eclipse like I cant use res/image.png I can only do c:\ect. anyone know why? I have set the res folder as a resource root.</p>
0
How to create an iOS Time Picker programmatically?
<p>I have a tiny little problem. </p> <p>I'd like to implement the time picker like:</p> <p><img src="https://i.stack.imgur.com/G7ja3.png" alt="http://i.stack.imgur.com/G7ja3.png"></p> <p>This screen grab is from iOS 6's day notifications of DO NOT DISTURB</p> <p>My question is how to do it ?</p> <p>Any ideas ????</p> <p>Are there any tutorials/resources online that you folks could suggest as how to do this ?</p> <p>[edited] I should have mentioned that this for an iPhone not an iPad....</p> <p>Thanks.</p>
0
ActionBarCompat - how to use it
<p>I'm trying to use ActionBarCompat on my own project. I've already opened the sample project (http://developer.android.com/resources/samples/ActionBarCompat/index.html), But I don't know how to implement it on my own.</p> <p>I can't find any tutorial of some kind. Should I make this project as a library? Can someone give me some directions, please.</p>
0
Ruby Activerecord IN clause
<p>I was wondering if anyone knew how to do an "IN" clause in activerecord. Unfortunately, the "IN" clause is pretty much un-googleable so I have to post here. Basically I want to answer a question like this "Give me all the college students that are in these dormitories where the dormitory id is in this array [id array]". I know how to write the query given a single dormitory id, but I don't know how to do it given an array of ids.</p> <p>Any help is greatly appreciated. I'm sure this is a repost of a question somewhere, so I'll delete this once an answer/better search term is found.</p>
0
Server returned HTTP response code: 401 for URL: https
<p>I'm using Java to access a HTTPS site which returns the display in an XML format. I pass the login credentials in the URL itself. Here is the code snippet:</p> <pre><code>DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); requestURL = "https://Administrator:Password@localhost:8443/abcd"; try { InputStream is = null; URL url = new URL(requestURL); InputStream xmlInputStream =new URL(requestURL).openConnection().getInputStream(); byte[] testByteArr = new byte[xmlInputStream.available()]; xmlInputStream.read(testByteArr); System.out.println(new String(testByteArr)); Document doc = db.parse(xmlInputStream); System.out.println("DOC="+doc); } catch (MalformedURLException e) { } </code></pre> <p>I'm creating a trust manager in the program which does not validate signed/unsigned certificates. But, on running the above program, I get the error Server returned HTTP response code: 401 for URL: <a href="https://Administrator:Password@localhost:8443/abcd" rel="nofollow noreferrer">https://Administrator:Password@localhost:8443/abcd</a></p> <p>I can use the same url on my browser and it displays the xml correctly. Kindly let me know how to make this work within the Java program.</p>
0
Symfony2 : accessing entity fields in Twig with an entity field type
<p>Here is my FormType :</p> <pre><code>public function buildForm(FormBuilder $builder, array $options) { $builder -&gt;add('user', 'entity', array( 'class' =&gt; 'UserBundle:User', 'expanded' =&gt; true, 'property' =&gt; 'name', )); } </code></pre> <p>Is there a way to access user's fields in the view (Twig) ?</p> <p>I'd like to do something like this :</p> <pre><code>{% for u in form.user %} {{ form_widget(u) }} {{ form_label(u) }} {% if u.moneyLeft &gt; 0 %} &lt;span&gt;{{ u.name }} : {{ u.moneyLeft }} €&lt;/span&gt; {% endif %} {% endfor %} </code></pre> <p>... where <em>moneyLeft</em> and <em>name</em> are fields from User entity.</p>
0
MVC Razor Radio Button
<p><strong>In partial view</strong> I work with textboxes like this.</p> <pre><code>@model Dictionary&lt;string, string&gt; @Html.TextBox("XYZ", @Model["XYZ"]) </code></pre> <p>How can i generate radiobuttons, and get the desired value in the form collection as YES/NO True/False) ? Currently i am getting null for "ABC" if i select any value for the below.</p> <pre><code> &lt;label&gt;@Html.RadioButton("ABC", @Model["ABC"])Yes&lt;/label&gt; &lt;label&gt;@Html.RadioButton("ABC", @Model["ABC"])No&lt;/label&gt; </code></pre> <p><strong>Controller</strong></p> <pre><code> public int Create(int Id, Dictionary&lt;string, string&gt; formValues) { //Something Something } </code></pre>
0
Rock-paper-scissors game c++
<p>Rock-paper-scissors game c++ doesn't display the cout to tell who win the game, i dont know what wrong and why is the program doesn't show the cout. Please let me know whats wrong and how to fix it and why it happened and i think the cstdlib is doing nothing there.</p> <blockquote> <p>Objective: To score the rock-paper-scissors game. If the user enters invalid input, your program should say so, otherwise it will output one of the above results.</p> </blockquote> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; using namespace std; int main() { string pone; string ptwo; string r; string p; string s; cout &lt;&lt; "Rock, Paper, Scissors Game\n"; cout &lt;&lt; "\nPlayer One, please enter your move: ('p' for Paper, 'r' for Rock, 's' for Scissor)"; cin &gt;&gt; pone; cout &lt;&lt; "\nPlayer Two, please enter your move: ('p' for Paper, 'r' for Rock, 's' for Scissor)"; cin &gt;&gt; ptwo; if (pone == ptwo) { cout &lt;&lt;"\nThere is a tie"&lt;&lt;endl; } if ( pone == r &amp;&amp; ptwo == p) { cout &lt;&lt; "\nPaper wraps rock, Player 1 win"; } else if (pone == r &amp;&amp; ptwo == s) { cout &lt;&lt; "\nRock smashes scissors, player 1 win"; } if (pone == p &amp;&amp; ptwo == r) { cout &lt;&lt;"\nPaper wraps rock, player 1 win"; } else if ( pone == p &amp;&amp; ptwo == s) { cout &lt;&lt;"\nScissors cut paper, player 2 win"; } if ( pone == r &amp;&amp; ptwo == p) { cout &lt;&lt; "\nPaper wraps rock, Player 1 win"; } else if (pone == r &amp;&amp; ptwo == s) { cout &lt;&lt; "\nRock smashes scissors, player 1 win"; } if (pone == p &amp;&amp; ptwo == r) { cout &lt;&lt;"\nPaper wraps rock, player 1 win"; } else if ( pone == p &amp;&amp; ptwo == s) { cout &lt;&lt;"\nScissors cut paper, player 2 win"; } if ( ptwo == s &amp;&amp; pone == r) { cout &lt;&lt;"\nScissors cut paper, player 1 win"; } else if (ptwo == s &amp;&amp; pone == p) { cout &lt;&lt;"\nRock smashes scissors, player 2 win "; } return 0; } </code></pre>
0
How to add data in charsequence [] dynamically in Java?
<p>One way to initialize a <code>charsequence[]</code> is</p> <pre><code>charsequence[] item = {&quot;abc&quot;, &quot;def&quot;}; </code></pre> <p>but I don't want to initialize it this way. Can someone please suggest some other way like the way we initialize <code>string[]</code> arrays?</p>
0
Why shouldn't Java enum literals be able to have generic type parameters?
<p>Java enums are great. So are generics. Of course we all know the limitations of the latter because of type erasure. But there is one thing I don't understand, Why can't I create an enum like this:</p> <pre><code>public enum MyEnum&lt;T&gt; { LITERAL1&lt;String&gt;, LITERAL2&lt;Integer&gt;, LITERAL3&lt;Object&gt;; } </code></pre> <p>This generic type parameter <code>&lt;T&gt;</code> in turn could then be useful in various places. Imagine a generic type parameter to a method:</p> <pre><code>public &lt;T&gt; T getValue(MyEnum&lt;T&gt; param); </code></pre> <p>Or even in the enum class itself:</p> <pre><code>public T convert(Object o); </code></pre> <h3>More concrete example #1</h3> <p>Since the above example might seem too abstract for some, here's a more real-life example of why I want to do this. In this example I want to use</p> <ul> <li>Enums, because then I can enumerate a finite set of property keys</li> <li>Generics, because then I can have method-level type-safety for storing properties</li> </ul> <pre><code>public interface MyProperties { public &lt;T&gt; void put(MyEnum&lt;T&gt; key, T value); public &lt;T&gt; T get(MyEnum&lt;T&gt; key); } </code></pre> <h3>More concrete example #2</h3> <p>I have an enumeration of data types:</p> <pre><code>public interface DataType&lt;T&gt; {} public enum SQLDataType&lt;T&gt; implements DataType&lt;T&gt; { TINYINT&lt;Byte&gt;, SMALLINT&lt;Short&gt;, INT&lt;Integer&gt;, BIGINT&lt;Long&gt;, CLOB&lt;String&gt;, VARCHAR&lt;String&gt;, ... } </code></pre> <p>Each enum literal would obviously have additional properties based on the generic type <code>&lt;T&gt;</code>, while at the same time, being an enum (immutable, singleton, enumerable, etc. etc.)</p> <h3>Question:</h3> <p>Did no one think of this? Is this a compiler-related limitation? Considering the fact, that the keyword "<strong>enum</strong>" is implemented as syntactic sugar, representing generated code to the JVM, I don't understand this limitation.</p> <p>Who can explain this to me? Before you answer, consider this:</p> <ul> <li>I know generic types are erased :-)</li> <li>I know there are workarounds using Class objects. They're workarounds.</li> <li>Generic types result in compiler-generated type casts wherever applicable (e.g. when calling the convert() method</li> <li>The generic type &lt;T&gt; would be on the enum. Hence it is bound by each of the enum's literals. Hence the compiler would know, which type to apply when writing something like <code>String string = LITERAL1.convert(myObject); Integer integer = LITERAL2.convert(myObject);</code></li> <li>The same applies to the generic type parameter in the <code>T getvalue()</code> method. The compiler can apply type casting when calling <code>String string = someClass.getValue(LITERAL1)</code></li> </ul>
0
Why does String.valueOf(null) throw a NullPointerException?
<p>according to the documentation, the method <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#valueOf(java.lang.Object)" rel="noreferrer"><code>String.valueOf(Object obj)</code></a> returns:</p> <blockquote> <p>if the argument is <code>null</code>, then a string equal to <code>"null"</code>; otherwise, the value of <code>obj.toString()</code> is returned.</p> </blockquote> <p>But how come when I try do this:</p> <pre><code>System.out.println("String.valueOf(null) = " + String.valueOf(null)); </code></pre> <p>it throws NPE instead? (try it yourself if you don't believe!)</p> <pre> Exception in thread "main" java.lang.NullPointerException at java.lang.String.(Unknown Source) at java.lang.String.valueOf(Unknown Source) </pre> <p>How come this is happening? Is the documentation lying to me? Is this a major bug in Java?</p>
0
Is Catching a Null Pointer Exception a Code Smell?
<p>Recently a co-worker of mine wrote in some code to catch a null pointer exception around an entire method, and return a single result. I pointed out how there could've been any number of reasons for the null pointer, so we changed it to a defensive check for the one result.</p> <p>However, catching NullPointerException just seemed wrong to me. In my mind, Null pointer exceptions are the result of bad code and not to be an expected exception in the system.</p> <p>Are there any cases where it makes sense to catch a null pointer exception? </p>
0
Ruby RVM apt-get update error
<p>I get following error when trying to install anything with RVM:</p> <pre><code>Searching for binary rubies, this might take some time. Found remote file https://rvm.io/binaries/ubuntu/13.04/x86_64/ruby-2.1.1.tar.bz2 Checking requirements for ubuntu. Installing requirements for ubuntu. Updating system..kshitiz password required for 'apt-get --quiet --yes update': ............................ Error running 'requirements_debian_update_system ruby-2.1.1', showing last 15 lines of /home/kshitiz/.rvm/log/1400047196_ruby-2.1.1/update_system.log ++ /scripts/functions/logging : rvm_pretty_print() 78 &gt; case "${TERM:-dumb}" in ++ /scripts/functions/logging : rvm_pretty_print() 81 &gt; case "$1" in ++ /scripts/functions/logging : rvm_pretty_print() 83 &gt; [[ -t 2 ]] ++ /scripts/functions/logging : rvm_pretty_print() 83 &gt; return 1 ++ /scripts/functions/logging : rvm_error() 117 &gt; printf %b 'There has been error while updating '\''apt-get'\'', please give it some time and try again later. For 404 errors check your sources configured in: /etc/apt/sources.list /etc/apt/sources.list.d/*.list \n' There has been error while updating 'apt-get', please give it some time and try again later. For 404 errors check your sources configured in: /etc/apt/sources.list /etc/apt/sources.list.d/*.list ++ /scripts/functions/requirements/ubuntu : requirements_debian_update_system() 53 &gt; return 100 Requirements installation failed with status: 100. </code></pre> <p>How can I fix this?</p>
0
How to find a specific cell and make it the ActiveCell
<p>I am writing a VBA code that will open a specific worksheet in my workbook in Excel, and then find the cell in Column A that has the value "TOTAL". This then must be set as the ActiveCell, so that the rest of my macro can perform actions on the row containing this cell.</p> <p>I want it so that when the user runs the macro, this cell is specifically chosen right off the bat. The position of this cell will change after the macro is run, so I need it to work no matter what cell this value is in. Everytime the macro runs, a new row is added above the row containing "TOTAL" and therefore the position of this cell is ever-changing.</p> <p>So far I have come up with this, just from readin through forums. It still doesn't work, but I'm new to this language and I can't determine where the error is.</p> <pre><code>Sub Macro2() Dim C As Range Worksheets("Project Total").Select With Selection C = .Find("TOTAL", After:=Range("A2"), MatchCase:=True) End With End Sub </code></pre>
0
`fatal: Not a valid object name: 'master'` when creating a new branch in git
<p>I followed <a href="https://www.atlassian.com/git/tutorial/git-basics#!add" rel="noreferrer">this tutorial</a> but I'm having trouble creating a new branch in a new repository. This is the error I'm getting:</p> <p><img src="https://i.stack.imgur.com/mySA5.jpg" alt="enter image description here"></p> <p>What am I doing wrong?</p>
0
How to discard local changes and pull latest from GitHub repository
<p>I have a directory on my machine where I store all projects from GitHub. I opened one of them and made changes locally on my machine. Project got messed up and now I want to discard all the changes I made and pull the latest version from the repository. I am relatively new to GitHub, using Git Shell. </p> <p>Would <code>git pull</code> command be sufficient? Do I need to do anything extra to discard the changes made locally? Can anyone help?</p>
0
Passing data from one page to another in angular js
<p>How do I pass data from one page to another in angular js? I have heard about using something as services but I am not sure how to use it! Given below is the functionality I want to execute! On page 1:</p> <pre><code>&lt;div class="container" ng-controller="mycontrl"&gt; &lt;label for="singleSelect"&gt; Select Date &lt;/label&gt;&lt;br&gt; &lt;select nAMe="singleSelect" ng-model="dateSelect"&gt; &lt;option value="2/01/2015"&gt;2nd Jan&lt;/option&gt; &lt;option value="3/01/2015"&gt;3rd Jan&lt;/option&gt; &lt;/select&gt; &lt;br&gt; Selected date = {{dateSelect}} &lt;br/&gt;&lt;br/&gt;&lt;br/&gt; &lt;label for="singleSelect"&gt; Select time &lt;/label&gt;&lt;br&gt; &lt;select nAMe="singleSelect" ng-model="timeSelect"&gt; &lt;option value="9/10"&gt;9AM-10AM&lt;/option&gt; &lt;option value="10/11"&gt;10AM-11AM&lt;/option&gt; &lt;option value="11/12"&gt;11AM-12PM&lt;/option&gt; &lt;option value="12/13"&gt;12PM-1PM&lt;/option&gt; &lt;option value="13/14"&gt;1PM-2PM&lt;/option&gt; &lt;/select&gt; &lt;button ng-click="check()"&gt;Check!&lt;/button&gt; &lt;br&gt; Selected Time = {{timeSelect}} &lt;br/&gt;&lt;br/&gt; </code></pre> <p>User selects time and date and that is used to make call to the db and results are stored in a variable array! Page 1 controller:</p> <pre><code>var config= { params: { time: times, date:dates } }; $http.get('/era',config).success(function(response) { console.log("I got the data I requested"); $scope.therapist_list = response; }); </code></pre> <p>Now how do I send this variable <code>$scope.therapist_list</code> which is an array to next page which will be having a different controller and also if services is use how do define it in my application.js file</p> <p>application.js: </p> <pre><code>var firstpage=angular.module('firstpage', []); var secondpage=angular.module('secondpage', []); </code></pre>
0
Sending an e-mail through java application with excel file attached - not working
<p>I am trying to send a mail through Java application with excel file as attachment without actually creating the file.The data in the excel file comes from the database. I am able to send the mail with attachment but the file is in Text(Tab Delimited) format. But I want the file to be in Excel format only.</p> <p>Please help....</p> <p>Following is the code:</p> <pre><code> //Here goes my DBConnection and Query code while(rs.next()) { for(int i=1;i&lt;13;i++) { //tab for each column exceldata = exceldata+""+"\t"; } // new line for end of eachrow exceldata = exceldata+"\n"; } String data = exceldata; String filename="example"; MimeMessage msg = new MimeMessage(session); //TO,From and all the mail details goes here DataSource fds = new ByteArrayDataSource(data,"application/vnd.ms-excel"); MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText("Hi"); MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(filename); Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); msg.saveChanges(); // Set the Date: header msg.setSentDate(new java.util.Date()); Transport.send(msg); </code></pre>
0
Validating Google ID tokens in C#
<p>I need to validate a Google ID token passed from a mobile device at my ASP.NET web api.</p> <p>Google have some sample code <a href="https://github.com/googleplus/gplus-verifytoken-csharp">here</a> but it relies on a JWT NuGet package which is .Net 4.5 only (I am using C#/.Net 4.0). Is anyone aware of any samples which do this without these packages or has achieved this themselves? The use of the package makes it very difficult to work out what I need to do without it.</p>
0
selenium.common.exceptions.WebDriverException: Message: 'Geckodriver' executable may have wrong permissions using GeckoDriver Firefox Selenium Python
<p>I get this error when I try to execute my first Selenium/python code.</p> <blockquote> <p>selenium.common.exceptions.WebDriverException: Message: 'Geckodriver' executable may have wrong permissions.</p> </blockquote> <p>My code : </p> <pre><code>from selenium import webdriver from selenium.webdriver.firefox.firefox_binary import FirefoxBinary if __name__ == '__main__': binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\firefox.exe') driver = webdriver.Firefox(firefox_binary=binary, executable_path="C:\\Users\\mohammed.asif\\Geckodriver") driver=webdriver.Firefox() driver.get("www.google.com"); </code></pre>
0
SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)
<p>I am seeing this in several situations and it is intermittent in our web based application connecting to SQL 2008 R2 serve back end. Users are coming across a point 2 point connection and seeing this on and off. Thought it was bandwidth issues until I started seeing it on terminal servers that are on the same core switch as this SQL server. I have checked remote connection enabled, Port 1433 is set correctly in Configuration for TCP/IP and the only thing I see that could be a cause is the timeout setting is set to 100000 in the remote connections rather than unlimited. </p> <p>The error is </p> <blockquote> <p><code>System.Data.SqlClient.SqlException</code> (<code>0x80131904</code>): <em>A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)</em> <code>---&gt;</code></p> <p><code>System.ComponentModel.Win32Exception</code> (<code>0x80004005</code>): <em>The network path was not found</em> <code>at</code></p> <pre class="lang-none prettyprint-override"><code>System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal&amp; connection) at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal&amp; connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal&amp; connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) at System.Data.SqlClient.SqlConnection.Open() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.&lt;&gt;c__DisplayClass1.b__0() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation) at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation) at System.Data.Entity.Core.EntityClient.EntityConnection.Open() ClientConnectionId:00000000-0000-0000-0000-000000000000 </code></pre> </blockquote>
0
Placeholder Color Change in Bootstrap
<p>How can I change the Placeholder Color in Bootstrap?</p> <p>The following code, which I tried, doesn't work.</p> <pre><code>input::-webkit-input-placeholder { color: red; } input:-moz-placeholder { color: red; } </code></pre>
0
How can i clone an image in javascript
<p><br> I'm trying to clone an image in javascript, bud without loading a new one.<br> Normally new browsers will load an image once and there are several ways to use that image again. The problem is that when I test it in IE 6 the image will request a new image from the server. <br> Anyone how has some info on how to do this in older browsers?<br> <br> 3 methods that not work: <br></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;My Image Cloning&lt;/title&gt; &lt;script type="text/javascript"&gt; sourceImage = new Image(); sourceImage.src = "myImage.png"; function cloneImageA () { imageA = new Image(); imageA.src = sourceImage.src; document.getElementById("content").appendChild(imageA); } function cloneImageB () { imageB = sourceImage.cloneNode(true); document.getElementById("content").appendChild(imageB); } function cloneImageC() { var HTML = '&lt;img src="' + sourceImage.src + '" alt="" /&gt;'; document.getElementById("content").innerHTML += HTML; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="controle"&gt; &lt;button onclick="cloneImageA();"&gt;Clone method A&lt;/button&gt; &lt;button onclick="cloneImageB();"&gt;Clone method B&lt;/button&gt; &lt;button onclick="cloneImageC();"&gt;Clone method C&lt;/button&gt; &lt;/div&gt; &lt;div id="content"&gt; Images:&lt;br&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p></p> <h2>Solution</h2> <p>Added cache-headers server-side with a simple .htaccess file in the directory of the image(s):<br> /img/.htaccess</p> <pre><code>Header unset Pragma Header set Cache-Control "public, max-age=3600, must-revalidate" </code></pre> <p><strong>All of the above javascript method's will use the image loaded if the cache-headers are set.</strong></p>
0
Where to write python code in anaconda
<p>I have downloaded the anaconda distribution for the python but now I didn't find that where to write python programs like I was writing python code using python IDLE. Please help me to get rid of this problem</p> <p>Thanks in Advance :)</p> <p>P.S:- I only have anaconda and I have not downloaded python from its website or I don't have any previous versions of python installed on my system.</p>
0
is google maps api-key necessary for practice?
<p>(Starting June 11, 2018: All Google Maps Platform API requests must include an API key; we no longer support keyless access.) I heard that the google maps api-key is not free. Does anyone know if it is possible to start a project that is not for release and includes google maps api-key without getting billed?</p>
0
how to use string builder to append double quotes and 'OR' between elements
<p>This is my code where I will get set of values in a list array.</p> <p>how to use string builder to append double quotes and OR between all those elements and save to a string?</p> <p>Also is it possible to get the elements in a split? For example I will get:</p> <pre><code>a,b,c,d,e,f,g,h,i,j </code></pre> <p>in an array I want the output as </p> <pre><code>"a" OR "b" OR "c" OR "d" </code></pre> <p>and remaining elements in another iteration. As there are 10 elements I want 5 elements at at time in above format. Is it possible in string builder. Here in my example I have mentioned total as 10 elements but I actually get more than 1000 elements. Here is my code.</p> <pre><code>List&lt;String&gt; test = new ArrayList&lt;String&gt;(); while (rs.next()) { String url = rs.getString("rssUrl"); test.add(url); } </code></pre>
0
str.isdecimal() and str.isdigit() difference example
<p>Reading python docs I have come to .isdecimal() and .isdigit() string functions and i'm not finding literature too clear on their usable distinction. Could someone supply me with code examples of where these two functions differentiate please.</p> <p>Similar behaviour:</p> <pre><code>&gt;&gt;&gt; str.isdecimal('1') True &gt;&gt;&gt; str.isdigit('1') True &gt;&gt;&gt; str.isdecimal('1.0') False &gt;&gt;&gt; str.isdigit('1.0') False &gt;&gt;&gt; str.isdecimal('1/2') False &gt;&gt;&gt; str.isdigit('1/2') False </code></pre>
0
How would I catch and deal with "undefined" from parsed json object
<p>I'm trying to populate a spreadsheet from a RESTful service and sometimes there's no such property so I get an "undefined" in my spreadsheet and the script stops and gives an error. I have no clue as to how to go about dealing with it, or skipping over the "undefined" part.</p> <p>Here's a sample query in json</p> <p>{</p> <pre><code>"rel": "self", "url": "https://www.sciencebase.gov/catalog/items?max=2&amp;s=Search&amp;q=project+ 2009+WLCI&amp;format=json&amp;fields=title%2Csummary%2Cspatial%2Cfacets", "total": 65, "nextlink": { "rel": "next", "url": "https://www.sciencebase.gov/catalog/items?max=2&amp;s= Search&amp;q=project+2009+WLCI&amp;format=json&amp;fields=title%2Csummary%2 Cspatial%2Cfacets&amp;offset=2" }, "items": [ { "link": { "rel": "self", "url": "https://www.sciencebase.gov/catalog/item/ 4f4e4ac3e4b07f02db67875f" }, "id": "4f4e4ac3e4b07f02db67875f", "title": "Decision-Making and Evaluation - Social and Economic Evaluation Supporting Adaptive Management for WLCI", "summary": "Provide information on the social and economic environment for the WLCI area and provide context for the biological and physical aspects of this project.", "spatial": { "representationalPoint": [ -108.585, 42.141 ] }, "facets": [ { "startDate": "2007-10-01 00:00:00", "projectStatus": "Active", "facetName": "Project", "_class": "ProjectFacet", "active": true, "className": "gov.sciencebase.catalog.item.facet.ProjectFacet", "endDate": null, "projectType": "Science", "_embeddedClassName": "gov.sciencebase.catalog.item.facet. ProjectFacet" } ] }, { "link": { "rel": "self", "url": "https://www.sciencebase.gov/catalog/item /4f4e4ac0e4b07f02db676d57" }, "id": "4f4e4ac0e4b07f02db676d57", "title": "Data and Information Management Products for the Wyoming Landscape Conservation Initiative" } ] </code></pre> <p>}</p> <p>Since the second item has only a title and nothing more after that I get "undefined" if I try to get a summary or facet etc. for items using a loop. I've thought of and tried using if statements like </p> <pre><code>if (parsedResponse.items[i].summary === "undefined") { Do something here; } </code></pre> <p>but this doesn't seem to work. Any suggestions I could try are appreciated. Thanks</p>
0
How feof() works in C
<p>Does feof() checks for eof for the current position of filepointer or checks for the position next to current filepointer?</p> <p>Thanks for your help !</p>
0
What is the best way to learn android quickly
<p>actually I am on 6 months internship program in a company and I am told to make an application in android with no help provided by the company and I have never done android before , so can you suggest me any faster way of learning android . Please let me know if there is .</p>
0
How to change Foreground Color of each letter in a string in C# Console?
<p>I want to ask if how can I change a color of a specific letter in a string with a specific color i want.</p> <p>For example:</p> <pre><code>string letters = "Hello World"; //The string inputted. </code></pre> <p>I want to change "o" in the "Hello" to red. How do i do that? I know that</p> <pre><code>Console.Foreground = ConsoleColor.Red; </code></pre> <p>will change the whole string to red. What would be the best code to change a specific letter with a specific color? Thanks in advance!</p>
0
PHP - if dropdown selection = something
<p>How would I go about creating a conditional statement based on a dropdown list selection?</p> <p>Lets say we have a dropdown list with entries:</p> <pre><code>Alpha Bravo Charlie Other </code></pre> <p>I want to create a conditional statement where if <code>Other</code> is the currently selected entry from the dropdown, I want to echo a newline stating <code>If Other, Please Specify</code>. But if it isn't the currently selected entry, I don't want that string to populate.</p>
0
Android AlertDialog Builder
<p>I have an alertdialog that I show but no matter what I do the alertdialog shows with a blank Title and Message. The Icon, the Positive button and negative buttons show ok with correct descriptions. Here is the snippets of code that I use: In the Manifest file:</p> <pre><code>&lt;uses-sdk android:minSdkVersion="5" android:targetSdkVersion="16" /&gt; </code></pre> <p>In my code I declare:</p> <pre><code>import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; </code></pre> <p>I also declare context:</p> <pre><code>final Context context = this; </code></pre> <p>I place my alert in :</p> <pre><code>public void confirm() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); // set title alertDialogBuilder.setTitle("This is title"); alertDialogBuilder.setIcon(R.drawable.ic_delete); // set dialog message alertDialogBuilder .setMessage("This is the message") .setCancelable(false) .setPositiveButton(R.string.yes,new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // if this button is clicked, close // current activity MainActivity.this.finish(); } }) .setNegativeButton(R.string.no,new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // if this button is clicked, just close // the dialog box and do nothing dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } </code></pre> <p>I then call confirm from where I need it, like so:</p> <pre><code>confirm(); </code></pre> <p>The alert shows up ok. The icon is set The setPositiveButton is good and contains correct description The setNegativeButton is good and contains correct description</p> <p>The Title is blank The Message is blank</p> <p>Any ideas?</p>
0
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
<h2>Original Question</h2> <p>For the following small code I'm getting the error...</p> <pre><code>import java.io.*; class test { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i; System.out.println("Enter no of processes "); int no_of_process=Integer.parseInt(br.readLine()); int process[]=new int[no_of_process]; System.out.println("Enter the values"); for(i=0;i&lt;no_of_process;i++) process[i]=Integer.parseInt(br.readLine()); for(i=0;i&lt;no_of_process;i++) System.out.println(process[i]); } } </code></pre> <p>Input:</p> <pre><code>Enter no of processes 5 Enter the values 1 2 Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:470) at java.lang.Integer.parseInt(Integer.java:499) at test.main(test.java:17) Process completed. </code></pre> <p>I think I have written the code properly and proper integer input is also given. How do I get rid of the above error without using any explicit exception handling statements? </p> <h2>Further Question:</h2> <p>Thanks guys for your answers...it is working. But there is one new question in my mind.</p> <p>I tried the following modification in the code and executed it. To my surprise, input was accepted properly without any run time error.</p> <pre><code>for(i=0;i&lt;no_of_process;i++) { System.out.println(Write anything or even keep it blank); process[i]=Integer.parseInt(br.readLine()); } </code></pre> <p>By adding just one Print statement before (or even after) the input statement in the for loop, my program worked correctly and no exception was thrown while giving input.</p> <p>Can you guys explain the reason behind this?</p> <p>Again if I remove the Print statement from there, the same error gets repeated. I am really confused about the reason behind this. Please help.</p>
0
Reading httprequest content from spring exception handler
<p>I Am using Spring's <code>@ExceptionHandler</code> annotation to catch exceptions in my controllers.</p> <p>Some requests hold POST data as plain XML string written to the request body, I want to read that data in order to log the exception. The problem is that when i request the inputstream in the exception handler and try to read from it the stream returns -1 (empty).</p> <p>The exception handler signature is:</p> <pre><code>@ExceptionHandler(Throwable.class) public ModelAndView exception(HttpServletRequest request, HttpServletResponse response, HttpSession session, Throwable arff) </code></pre> <p>Any thoughts? Is there a way to access the request body?</p> <p>My controller: </p> <pre><code>@Controller @RequestMapping("/user/**") public class UserController { static final Logger LOG = LoggerFactory.getLogger(UserController.class); @Autowired IUserService userService; @RequestMapping("/user") public ModelAndView getCurrent() { return new ModelAndView("user","response", userService.getCurrent()); } @RequestMapping("/user/firstLogin") public ModelAndView firstLogin(HttpSession session) { userService.logUser(session.getId()); userService.setOriginalAuthority(); return new ModelAndView("user","response", userService.getCurrent()); } @RequestMapping("/user/login/failure") public ModelAndView loginFailed() { LOG.debug("loginFailed()"); Status status = new Status(-1,"Bad login"); return new ModelAndView("/user/login/failure", "response",status); } @RequestMapping("/user/login/unauthorized") public ModelAndView unauthorized() { LOG.debug("unauthorized()"); Status status = new Status(-1,"Unauthorized.Please login first."); return new ModelAndView("/user/login/unauthorized","response",status); } @RequestMapping("/user/logout/success") public ModelAndView logoutSuccess() { LOG.debug("logout()"); Status status = new Status(0,"Successful logout"); return new ModelAndView("/user/logout/success", "response",status); } @RequestMapping(value = "/user/{id}", method = RequestMethod.POST) public ModelAndView create(@RequestBody UserDTO userDTO, @PathVariable("id") Long id) { return new ModelAndView("user", "response", userService.create(userDTO, id)); } @RequestMapping(value = "/user/{id}", method = RequestMethod.GET) public ModelAndView getUserById(@PathVariable("id") Long id) { return new ModelAndView("user", "response", userService.getUserById(id)); } @RequestMapping(value = "/user/update/{id}", method = RequestMethod.POST) public ModelAndView update(@RequestBody UserDTO userDTO, @PathVariable("id") Long id) { return new ModelAndView("user", "response", userService.update(userDTO, id)); } @RequestMapping(value = "/user/all", method = RequestMethod.GET) public ModelAndView list() { return new ModelAndView("user", "response", userService.list()); } @RequestMapping(value = "/user/allowedAccounts", method = RequestMethod.GET) public ModelAndView getAllowedAccounts() { return new ModelAndView("user", "response", userService.getAllowedAccounts()); } @RequestMapping(value = "/user/changeAccount/{accountId}", method = RequestMethod.GET) public ModelAndView changeAccount(@PathVariable("accountId") Long accountId) { Status st = userService.changeAccount(accountId); if (st.code != -1) { return getCurrent(); } else { return new ModelAndView("user", "response", st); } } /* @RequestMapping(value = "/user/logout", method = RequestMethod.GET) public void perLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { userService.setOriginalAuthority(); response.sendRedirect("/marketplace/user/logout/spring"); } */ @ExceptionHandler(Throwable.class) public ModelAndView exception(HttpServletRequest request, HttpServletResponse response, HttpSession session, Throwable arff) { Status st = new Status(); try { Writer writer = new StringWriter(); byte[] buffer = new byte[1024]; //Reader reader2 = new BufferedReader(new InputStreamReader(request.getInputStream())); InputStream reader = request.getInputStream(); int n; while ((n = reader.read(buffer)) != -1) { writer.toString(); } String retval = writer.toString(); retval = ""; } catch (IOException e) { e.printStackTrace(); } return new ModelAndView("profile", "response", st); } } </code></pre> <p>Thank you</p>
0
Iterate through rows from Sqlite-query
<p>I have a table layout that I want to populate with the result from a database query. I use a select all and the query returns four rows of data. </p> <p>I use this code to populate the TextViews inside the table rows.</p> <pre class="lang-java prettyprint-override"><code>Cursor c = null; c = dh.getAlternative2(); startManagingCursor(c); // the desired columns to be bound String[] columns = new String[] {DataHelper.KEY_ALT}; // the XML defined views which the data will be bound to int[] to = new int[] { R.id.name_entry}; SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.list_example_entry, c, columns, to); this.setListAdapter(mAdapter); </code></pre> <p>I want to be able to separate the four different values of KEY_ALT, and choose where they go. I want them to populate four different TextViews instead of one in my example above.</p> <p>How can I iterate through the resulting cursor?</p>
0
Excel VBA Macros to copy and paste cell value to certain cells based on text in column
<p>I am attempting to copy and paste text values to a certain amount of cells in excel based on a text comparison. </p> <p>Please see below for explanation:</p> <p>I have 2 column A(blank) and B(with values)</p> <p><img src="https://i.stack.imgur.com/WqQvm.jpg" alt="enter image description here"></p> <p>After the macros, this will be the end results:</p> <p><img src="https://i.stack.imgur.com/CKxkl.jpg" alt="enter image description here"></p> <p>It is basically taking the bottom cell after it detect the fruits column and pasting the cell value into row A. Note that after it reaches the next cell fruits it take the next (bottom) cell value. F123,F124 etc..</p> <p>Can someone please provide me with the excel vba codes to do? Thanks.</p>
0
Default file transfer mode in SCP
<p>I want to know what is the default mode used (ASCII or binary like FTP) while transferring files using SCP.</p> <p>Is there any file mode concept in SCP ? How does it work ?</p>
0
Delete a very, very deep tree of subdirectories on windows?
<p>I was testing a file management program today and while looking to solve something else my program ended up not checking for moving a directory to the same directory.</p> <p>The result is a possibly endless recursion of dir1s. I need to commit the changes so I'm desperate to get these out of my repository.</p> <p>Any ideas?</p> <p>Basically.. what I got is:</p> <p>dir/dir/dir/dir........./dir/dir/dir It's probably on the thousands.</p>
0
React - Call props function inside of a components function
<p>Trying to do something like this:</p> <p>// Component one</p> <pre><code>toggleDropdown() { setState({open: !open} } render () { return ( ChildComponent toggle={this.toggleDropdown} /&gt; ) } </code></pre> <p>Then in my child component I'd like to call that toggleDropdown function in another function like this:</p> <pre><code>// This gets triggered on click. removeItem() { // remove scripts then: this.props.toggleDropdown() } </code></pre> <p>I thought you'd be able to do something like this but it appears that you can only call prop functions on the element?</p>
0