input
stringlengths
51
42.3k
output
stringlengths
18
55k
Programatically set app setting / env variable during Azure (Kudu) deployment <h1>Summary</h1> <p>I'm trying to deploy an MVC5 web app to Azure. I need to set WEBSITE_NODE_DEFAULT_VERSION programatically to ensure all configuration is atomically contained in the repo. When I try to set that app setting / env variable in <code>.deployment</code> or <code>deploy.cmd</code>, it gets ignored by the deployment. Why?</p> <h1>Background</h1> <p>My web app uses bower for client-side libraries, and a simple gulp script to place the minimized libs in a target folder. My cshtml files then consume them from said target folder.</p> <p>Per <a href="http://stackoverflow.com/a/28591913/1876622">this comment</a>, I've brought down the deployment script (<code>.deployment</code> and <code>deploy.cmd</code>) from Azure and tweaked it to install bower.</p> <blockquote> <p>Then download your custom deployment script. if you go to https://.scm.azurewebsites.net then click on Tools -> Download custom deployment script or just download it from D:\home\deployment\tools</p> </blockquote> <p>My research then showed that npm is available by default in Azure web app deployments, and the bower package is pre-installed, but gulp isn't. So I need to add 3 custom commands to the deployment scripts:</p> <ol> <li>npm install (required to make gulp available)</li> <li>bower install (pulls down the client-side libs)</li> <li>gulp (pipelines the client-side libs)</li> </ol> <p>Per <a href="http://stackoverflow.com/questions/35412935/npm-3-x-install-fails-on-rename-long-paths-in-windows-azure">this question</a>, The problem I'm facing is that node (and therefore npm) being used are an old version. The <code>npm install</code> command is resulting in filenames that are too long, which is a known issue in older versions of npm.</p> <p>Per <a href="https://github.com/projectkudu/kudu/wiki/Configurable-settings#runtime-settings" rel="nofollow">this set of Kudu runtime settings</a>, I'm trying to set the <code>WEBSITE_NODE_DEFAULT_VERSION</code> to <strong>6.7.0</strong> (the latest at the time of this question), because that would ensure that the latest npm also runs.</p> <p><strong>Here's where my problem occurs.</strong> In <code>deploy.cmd</code>, before running <code>npm install</code>, I add a line <code>set WEBSITE_NODE_DEFAULT_VERSION = 6.7.0</code> (I've tried variations, including with quotes, without spaces around the equal sign, with <code>setlocal</code>, etc.) I <code>echo %WEBSITE_NODE_DEFAULT_VERSION%</code> on either side of setting the variable. The output before and after is always <strong>4.4.7</strong>.</p> <p>I tried it in <code>.deployment</code> as well, to no avail. I even tried changing the position (sometimes before <code>command = deploy.cmd</code> and sometimes after).</p> <p>From what I can decipher off the net, at least <em>one</em> of my methods above should work... <strong>Why can't I set this app setting / env variable in the deployment script?</strong></p> <h1>Update</h1> <p>According to <a href="http://stackoverflow.com/questions/30445638/azure-kudu-deployment-ignores-project-setting-when-deploy-cmd-is-specified">this question</a>, I can't set the app settings in the .deployment file. This differs from other articles on the net, but it still doesn't explain why SET isn't working in the deploy.cmd file.</p> <h1>Files</h1> <p><strong>.deployment</strong></p> <pre><code>[config] ;Change node version to change npm version to avoid long-file-name situations WEBSITE_NODE_DEFAULT_VERSION = 6.7.0 command = deploy.cmd </code></pre> <p><strong>deploy.cmd</strong></p> <pre><code>(REDACTED - default stuff) echo :: 4. NPM Install (borrowing from http://stackoverflow.com/questions/39480274/how-do-i-run-gulp-js-in-my-asp-net-core-project-when-deploying-to-azure-using-gi) IF EXIST "%DEPLOYMENT_TARGET%\package.json" ( :: Set the node version. Tried this in .deployment, but that didn't work. :: HELP! Why isn't this working??? echo %WEBSITE_NODE_DEFAULT_VERSION% before set :: Output: "4.4.7 before set" SET WEBSITE_NODE_DEFAULT_VERSION=6.7.0 echo %WEBSITE_NODE_DEFAULT_VERSION% after set :: Output: "4.4.7 after set" pushd "%DEPLOYMENT_TARGET%" call :ExecuteCmd npm install IF !ERRORLEVEL! NEQ 0 goto error popd ) echo :: 5. Bower Install (borrowing from http://stackoverflow.com/a/28591913/1876622) IF EXIST "%DEPLOYMENT_TARGET%\bower.json" ( pushd "%DEPLOYMENT_TARGET%" call :ExecuteCmd bower install IF !ERRORLEVEL! NEQ 0 goto error popd ) echo :: 6. Run Gulp (borrowed from https://blogs.msdn.microsoft.com/azureossds/2016/08/12/run-npm-bower-composer-gulp-grunt-in-azure-app-services-during-deployment/) IF EXIST "%DEPLOYMENT_TARGET%\gulpfile.js" ( pushd "%DEPLOYMENT_TARGET%" call :ExecuteCmd gulp IF !ERRORLEVEL! NEQ 0 goto error popd ) </code></pre>
<p>Turns out that when I created the Azure web app, it pre-set the WEBSITE_NODE_DEFAULT_VERSION in the portal (portal.azure.com). So the UI was superseding my programmatic requests to set the app setting.</p> <p>After deleting that app setting in the portal (below is a screenshot after removing the setting), I tried deploying again by setting the env var in the .deployment file only... <strong>success!</strong></p> <p><a href="https://i.stack.imgur.com/lVjwt.png" rel="nofollow"><img src="https://i.stack.imgur.com/lVjwt.png" alt="enter image description here"></a></p> <p><strong>.deployment</strong></p> <pre><code>[config] ;Change node version to change npm version to avoid long-file-name situations https://blogs.msdn.microsoft.com/azureossds/2016/04/20/nodejs-and-npm-versions-on-azure-app-services/ ;Make sure to delete the value in portal.azure.com &gt; Application settings &gt; App settings... because that will override this WEBSITE_NODE_DEFAULT_VERSION = 6.7.0 command = deploy.cmd </code></pre>
How to create text file for writing <p>I've a problem to write text in a file. What I've done so far is the following: I have a string with the text to store and the file name also as a string.</p> <pre><code>let someText = "abcd" let fileName = "file:///xxx" </code></pre> <p>Of course "xxx" is a .txt file under the document directory so it should be possible to write.<br> Then I found out that I can use the write method o the string. But for this call I need the file name as url so I have this piece of code:</p> <pre><code>let fileUrl = URL(string: fileName) do { try someText.write(to: fileUrl, atomically: false, encoding: String.Encoding.utf8) } catch { } </code></pre> <p>If I start my app then I will get an error "The file xxx does not exist". Ok that's correct because the file is not created. I thought that the write method does it automatically but it seems not so.<br> And that's the point I don't know how to solve this issue!</p> <p>I'm using Xcode 8 + Swift 3.</p> <p>+++ EDIT +++</p> <p>I try to explain what I'm exactly looking for.<br> Let's say I've two tasks: The first task builds file names and stores it in a database. That's why I work with strings:</p> <pre><code>var fileName = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).path if (!fileName.hasSuffix("/")) { fileName += "/" } fileName += "file.txt" </code></pre> <p>As you can see the file is not created at this moment because I only need the name in this task.</p> <p>Ok and then the second task. It has to select a specific file name from the database and append it with the file:// scheme:</p> <pre><code>let fileName = "file://" + fileNameFromDatabase </code></pre> <p>Then the text is written with the code above.<br> It's clear that the file not exists in this task because I only have the name. That's why I think that the error message of the write method is correct.<br> What I'm now looking for is a possibility to create the file/write the text in one step.</p>
<p>I recently ran into some problems by trying to just do: </p> <pre><code>"my string".writeToURL... </code></pre> <p>Which is how many of the tutorial show you how to do it. Eventually I came up with this method (is swift 2.3 for which i apologize). I kept getting an error saying I did not have permission to write. Then I started to get your error. The bottom is working for me. The param <code>file</code> is what you want the name of your file to be. </p> <pre><code>func writeDataToFile(file: String)-&gt; Bool{ let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]) let logsPath = documentsPath.URLByAppendingPathComponent("yourFolderDirectory") do { try NSFileManager.defaultManager().createDirectoryAtPath(logsPath!.path!, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { NSLog("Unable to create directory \(error.debugDescription)") } let str = "hello world" let fileName = logsPath?.URLByAppendingPathComponent(file + ".txt") do{ try str.writeToURL(fileName!, atomically: false, encoding: NSUTF8StringEncoding) return true } catch let error as NSError { print("Ooops! Something went wrong: \(error)") return false } } </code></pre>
How can I make columns full height of window between header and footer with CSS and prevent underwrap <p>I want to make a simple HTML layout using CSS where I have a header, two columns where the column on the right is a fixed width (say 100px for now). The left column will at some point have generated content, it shouldn't run past the page bottom but it may it may in the future... anyway I want both of my columns to stretch to the footer... here is my HTML:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Coming soon...&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="wrapper"&gt; &lt;div class="header"&gt; Header &lt;/div&gt; &lt;div class="content"&gt; Content Here will be dynamic... sometimes 1 word, sometimes 1000 words! Either way, I want to reach the footer! &lt;/div&gt; &lt;div class="right-menu"&gt; Here will be a menu... I want this to be the same height as the content DIV &lt;/div&gt; &lt;div class="footer"&gt; footer &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and here is my CSS:</p> <pre><code>.header { background-color: Coral ; width: 100%; } .content { background-color: BlanchedAlmond ; float:left; width:100%; margin-right: -100px; } .right-menu { background-color: BurlyWood ; float: right; width: 100px; } .footer { background-color: Coral; width: 100%; clear: both; position: absolute; bottom: 0; } </code></pre> <p>I made a JSFiddle of this and I noticed that my content div also seems to run under my menu... how could I prevent this too: <a href="https://jsfiddle.net/dwn82s81/" rel="nofollow">https://jsfiddle.net/dwn82s81/</a></p> <p>Many thanks in advance. I realized that I haven't written any CSS for ages!</p>
<p>Try this change to .content</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.content { background-color: BlanchedAlmond ; float:left; width: 95%; margin-right: -100px; }</code></pre> </div> </div> </p>
WordPress replaces html code with characters <p>Today I got one very bad experience with WordPress. After long normal work it started replacing <code>&amp;lt;</code> html code with <code>&lt;</code> symbols. With other symbols situation is the same.</p>
<p>You'll need to specify where these symbols are being used that it changes it. Without any clarification, I'm going to assume you using them in the WYSIWYG editor on a post/page. In this case, you may need to switch from the "Visual" to "Text" tab.</p> <p>Here is a link describing what I'm talking about: <a href="http://www.inmotionhosting.com/support/edu/wordpress/wordpress-introduction/adding-html-wordpress" rel="nofollow">http://www.inmotionhosting.com/support/edu/wordpress/wordpress-introduction/adding-html-wordpress</a></p> <p>If this isn't the problem you are facing, then please explain where you are using these symbols.</p>
Convolution Error in MATLAB <p>I have no idea why I don't get an identical image of 'ada.jpg' when I run the code below:</p> <pre><code>clear; I = rgb2gray(imread('ada.jpg')); figure(1) imshow(I) M = int8([0 0 0 ; 0 1 0 ; 0 0 0]); C = convn(M, I); figure(2) imshow(C) </code></pre> <p>Here the two images: <a href="https://i.stack.imgur.com/xrAim.jpg" rel="nofollow">input image - figure (1)</a> and <a href="https://i.stack.imgur.com/LUmiL.png" rel="nofollow">output image - figure (2)</a></p>
<p>The issue is that your input image data <code>I</code> has values between <code>0</code> and <code>255</code> and is of datatype <code>uint8</code>. After convolution, the output is a <code>double</code> and still has values between <code>0</code> and <code>255</code>.</p> <p>The default for <code>imshow</code> when the input is of type <code>double</code> is to scale the color axes such that <code>0</code> is black and <code>1</code> is white. Your image is showing up almost completely as white since most of your values are <code>&gt;1</code>.</p> <p>To fix this (since you need limits of <code>0</code> to <code>255</code>) , you can specify the range of values to use as the second input to <code>imshow</code></p> <pre><code>imshow(C, [0 255]) </code></pre> <p>Or you can just provide an empty array as the second input so the colors are automatically scaled to the extrema of the input image</p> <pre><code>imshow(C, []) </code></pre> <p>As a side-note, you can use <code>conv2</code> rather than <code>convn</code> since you are simply performing 2D convolution. <code>conv2</code> requires that all inputs are floating point numbers so we first convert <code>M</code> and <code>I</code> to <code>double</code>.</p> <pre><code>C = conv2(double(I), double(M), 'same'); </code></pre> <p>Alternately, you could use <code>imfilter</code> if you have the Image Processing Toolbox (as @rayryeng has suggested) and not have to worry about casting <code>M</code> and <code>I</code> as <code>double</code></p> <pre><code>C = imfilter(I, M); </code></pre>
Importing Templates in Meteor During Routing with Iron Router <p>One of the benefits to Meteor is that you only need to load content when it needs to be rendered, e.g. if you have a template file in /imports/ui/client it is not loaded unless you import it somewhere. However, when using Iron Router I've been unable to determine how I should include a template only when it needs to be rendered via the appropriate route. One approach I've tried is declaring the import in the route function:</p> <pre><code>Router.route('/', function () { import '/imports/ui/client/home.js'; this.render('home'); }); </code></pre> <p>This succeeds in loading the template file, though I've not seen any examples in the Iron Router documentation doing it this way and I've had some JavaScript issues that I didn't have previously, as such I'm doubtful this is the right/best approach.</p> <p>When using Meteor with Iron Router what is the best way to include templates only when they're needed? </p>
<pre><code>import '/imports/ui/client/home.js'; Router.route('/', function () { this.render('home'); }); </code></pre> <p>This is the 'standard' way as mentioned in most of the <a href="https://themeteorchef.com/snippets/understanding-the-imports-directory/" rel="nofollow">examples</a>, though I see no harm in your way.</p>
Convert Row to Column mySQL with ID (not pivoting) <p>I have a value store in a database like this:</p> <pre><code>ID | Date | Value ---------------------------------------------- 1 | 11/20 | 1 1 | 11/21 | 2 2 | 11/20 | 10 2 | 11/21 | 20 </code></pre> <p>However, I need it to be like this:</p> <pre><code> Date | Value ID 1 | Value ID 2 ---------------------------------------------- 11/20| 1 | 10 11/21| 2 | 20 </code></pre> <p>So the new column can be plot in a trend (column 1 = date, column 2 = value#1, column 3 = value #2, column 4 = value#4, etc).</p> <hr> <p>Here is the query for a single tag:</p> <pre><code>SELECT * FROM ( SELECT ID, _date, ESYNC_TAGSHISTORY.Val, @curRow := @curRow + 1 AS row_number FROM ESYNC_TAGSHISTORY JOIN (SELECT @curRow:=0) i INNER JOIN ESYNC_TAGS ON ESYNC_TAGSHISTORY.TAGID=ESYNC_TAGS.ID WHERE ESYNC_TAGS.NAME='I_TT_21052' AND ESYNC_TAGS.STATIONID=1 AND (_date BETWEEN now()-INTERVAL 45 MINUTE AND now()) ) s WHERE row_number mod 60 = 0; </code></pre> <p>And the results:</p> <pre><code> ID | Date | Value ID 1 | Row ---------------------------------------------- 1 | 11/20| 1 | 1 1 | 11/21| 2 | 2 </code></pre> <p>EDIT : </p> <p>With some modification my query look like this </p> <pre><code>SELECT * FROM ( SELECT ID, _date, ESYNC_TAGSHISTORY.Val, @curRow := @curRow + 1 AS row_number, if (ESYNC_TAGS.NAME='I_TT_21052', ESYNC_TAGSHISTORY.Val, NULL) as 'I_TT_21052', if (ESYNC_TAGS.NAME='I_TT_91214', ESYNC_TAGSHISTORY.Val, NULL) as 'I_TT_40011' FROM ESYNC_TAGSHISTORY JOIN (SELECT @curRow:=0) i INNER JOIN ESYNC_TAGS ON ESYNC_TAGSHISTORY.TAGID=ESYNC_TAGS.ID WHERE ESYNC_TAGS.STATIONID=1 AND (_date BETWEEN now()-INTERVAL 5 MINUTE AND now()) ) s WHERE row_number mod 1 = 0 ORDER BY ID ,_date; </code></pre> <p>Result look like this </p> <p><a href="https://i.stack.imgur.com/SDawF.png" rel="nofollow">SQL RESULT</a></p> <p>My Problem now is to move the data from the last column at the same place as the other (get the value line up with the date)</p> <p>EDIT #2 : Finally for further reference query look like this :</p> <pre><code>SELECT _date, I_TT_21052, I_TT_40011, row_number From( SELECT max(_date) as _date, max(I_TT_21052) as I_TT_21052, max(I_TT_40011) as I_TT_40011, @curRow := @curRow + 1 AS row_number FROM ( SELECT ID, _date, ESYNC_TAGSHISTORY.Val, if (ESYNC_TAGS.NAME='I_TT_21052', ESYNC_TAGSHISTORY.Val, NULL) as 'I_TT_21052', if (ESYNC_TAGS.NAME='I_TT_91214', ESYNC_TAGSHISTORY.Val, NULL) as 'I_TT_40011' FROM ESYNC_TAGSHISTORY JOIN (SELECT @curRow:=0) i INNER JOIN ESYNC_TAGS ON ESYNC_TAGSHISTORY.TAGID=ESYNC_TAGS.ID WHERE ESYNC_TAGS.STATIONID=1 AND (_date BETWEEN now()-INTERVAL 24 HOUR AND now()) ) s GROUP BY _date)v WHERE row_number mod 150 = 0; </code></pre>
<pre><code>select case when id=1 then count(Id) else 0 end) as Value1, case when id=2 then count(Id) else 0 end) as Value2 from ESYNC_TAGSHISTORY </code></pre> <p>This is not exact but try this kind of query you will get result</p>
Cannot find symbol getCurrentActivity when building an Android module for React-Native <p><a href="https://github.com/mmazzarolo/react-native-getactivity-test/" rel="nofollow">First of all, here is a test repo to replicate my issue</a> </p> <p>Hello there, I'm trying to create a simple Android module for React-Native and I'm having some trouble getting the current Activity from the Java code. </p> <p>This is not the first native module I worked on, but I never had to obtain an Activity reference since today.</p> <p>The <a href="https://github.com/mmazzarolo/react-native-getactivity-test/blob/master/react-native-estimote-android/android/src/main/java/com/mmazzarolo/estimoteandroid/EstimoteAndroidModule.java" rel="nofollow">interested module</a> is a bridge to the Estimote SDK, but this is not relevant to the issue.<br> The module in Android studio works perfectly, but when I try to build it with <code>react-native run android</code> I get the following error:</p> <pre><code>:react-native-estimote-android:compileReleaseJavaWithJavac /Users/matteo/dev/react-native-example/react-native-estimote-android/android/src/main/java/com/mmazzarolo/estimoteandroid/EstimoteAndroidModule.java:64: error: cannot find symbol Activity currentActivity = this.getCurrentActivity(); ^ symbol: method getCurrentActivity() 1 error :react-native-estimote-android:compileReleaseJavaWithJavac FAILED FAILURE: Build failed with an exception. </code></pre> <p>From my understanding extending <strong>ReactContextBaseJavaModule</strong> should be enough to grant me the usage of <strong>this.getCurrentActivity()</strong> (and Android studio agrees with me). </p> <p>This is what I already tried to do:<br> - Implementing <a href="https://facebook.github.io/react-native/docs/native-modules-android.html" rel="nofollow">ActivityEventListener</a>: same <strong>cannot find symbol</strong> error when I try to import ActivityEventListener;<br> - android/.gradlew clean<br> - watchman watch-del-all &amp;&amp; rm -rf node_modules/ &amp;&amp; npm cache clean &amp;&amp; npm prune &amp;&amp; npm i<br> - Tried the same repo on two different computers... </p> <p>Any hints? Thank you in advance.</p>
<pre><code> @ReactMethod public void start(final Callback callback) { Activity currentActivity = getCurrentActivity(); this.mBeaconManager.connect(new BeaconManager.ServiceReadyCallback() { @Override public void onServiceReady() { mBeaconManager.startRanging(region); callback.invoke(); } }); } </code></pre> <p>Remove this from start method, if you do this.getCurrentActivity() it will referr to EstimoteAndroidModule context not to the app ReactContextBaseJavaModule context</p>
Compress a 2D array into a 1D Array <p>i have a quad (2D array) which is composed of numbers which ranges from 0 to 255 and the most frequent value of the array ( in my case 2) is the background value</p> <p>i have to put all the values of the array except the background value ( i have to ignore all cases that contains a 2) in a 1D array with this arrangement </p> <p>the line,the column,the value,the line,the next column,the next value</p> <p>for example i have </p> <pre><code>{2,3,2,2}, {2,2,2,2}, </code></pre> <p>in the 1D array it will be like <code>{ 1,2,3,}</code></p> <p>i added spaces to make it more readable </p> <p>here is my array </p> <pre><code>int image1[MAXL][MAXC]= { {2,3,2,2}, {2,2,2,2}, {2,255,2,2}, {255,2,2,2}, {2,255,2,2} }; </code></pre> <p>and the loop </p> <pre><code> for (int i = 0; i&lt;nbc;i++) { for (int j=0; j&lt;nbl;j++) { if (image1[j][i]==BackColor) { } else } } </code></pre> <p>nbc and nbl are respectively the number of columns and lines</p> <p>thanks you for your help</p> <p>EDIT : i completely failed my example i didn't ignored the 2, should be fine now </p>
<p>A simple approach using <code>std::vector</code></p> <pre><code>std::vector&lt;int&gt; result; for (int i = 0; i&lt;MAXL;i++) { for (int j=0; j&lt;MAXC;j++) { if (image1[i][j] != BackColor) // Notice != { result.push_back(i+1); result.push_back(j+1); result.push_back(image1[i][j]); } } } for (auto x : result) { std::cout &lt;&lt; x &lt;&lt; " "; } std::cout &lt;&lt; endl; </code></pre> <blockquote> <p>Output:</p> <p>1 2 3 3 2 255 4 1 255 5 2 255 </p> </blockquote> <p><a href="http://ideone.com/yJawu5" rel="nofollow">http://ideone.com/yJawu5</a></p>
How to achieve this underline or bottom border effect without editing line-height? <p><img src="http://i.imgur.com/ok6FaOu.png" alt="like the orange underline here"></p> <p>I would like to achieve this underline, but without messing the line height.</p> <p>If I use text-decoration:underline; its too close to the text, not visually appealing, and if I use bottom-border its too far away and on the edge because of line height.</p> <p>Is there any other HTML&amp;CSS solution or workaround except changing the line height?</p>
<p>I sometimes use an :after or :before pseudo element for that sort of thing. That way I can be knit picky about how far away it is.</p> <p>The pseudo element can be absolute positioned to ensure that.</p> <p>So for a general example:</p> <pre><code>.nav-bar-item:after { content: ''; position: absolute; bottom: 8px; height: 4px; width: 100%; background-color: orange; display: none; } .nav-bar-item:hover:after { display: block; } </code></pre>
Display image 5 second after hidden <pre><code>override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Set the image view in the starting location moveobj.frame = CGRect(x: 100, y: 100, width: /* some width */, height: /* some height */) UIView.animate(withDuration: /* some duration */, animations: { // Move image view to new location self.moveobj.frame = CGRect(x: 300, y: 300, width: self.moveobj.frame.width, height: self.moveobj.frame.height) }) { (finished) in // Animation completed; hide the image view self.moveobj.isHidden = true } } </code></pre> <p>After animation is completed the image is hidden but I would like to display again this after 5 second in original position. How do I this? </p>
<p>Well all you'd have to do is chain a new animation to the finish that does the opposite of the previous animation (move back to the original location and unhide) - Courtesy of @Rob's comment. </p> <p>It'd just be:</p> <pre><code>override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Set the image view in the starting location let originalFrame = CGRect(x: 100, y: 100, width: /* some width */, height: /* some height */) moveobj.frame = originalFrame UIView.animate(withDuration: /* some duration */, animations: { // Move image view to new location self.moveobj.frame = CGRect(x: 300, y: 300, width: self.moveobj.frame.width, height: self.moveobj.frame.height) }) { (finished) in // Animation completed; hide the image view self.moveobj.isHidden = true // Next animation DispatchQueue.main.asyncAfter(deadline: .now() + 5){ self.moveobj.frame = originalFrame self.moveobj.isHidden = false } } } </code></pre>
Speeding up nested loops in python <p>How can I speed up this code in python?</p> <pre><code>while ( norm_corr &gt; corr_len ): correlation = 0.0 for i in xrange(6): for j in xrange(6): correlation += (p[i] * T_n[j][i]) * ((F[j] - Fbar) * (F[i] - Fbar)) Integral += correlation T_n =np.mat(T_n) * np.mat(TT) T_n = T_n.tolist() norm_corr = correlation / variance </code></pre> <p>Here, TT is a fixed 6x6 matrix, p is a fixed 1x6 matrix, and F is fixed 1x6 matrix. T_n is the nth power of TT. </p> <p>This while loop might be repeated for 10^4 times.</p>
<p>The way to do these things quickly is to use Numpy's built-in functions and operators to perform the operations. Numpy is implemented internally with optimized C code and if you set up your computation properly, it will run much faster.</p> <p>But leveraging Numpy effectively can sometimes be tricky. It's called "vectorizing" your code - you have to figure out how to express it in a way that acts on whole arrays, rather than with explicit loops.</p> <p>For example in your loop you have <code>p[i] * T_n[j][i]</code>, which IMHO can be done with a vector-by-matrix multiplication: if v is 1x6 and m is 6x6 then <code>v.dot(m)</code> is 1x6 that computes dot products of <code>v</code> with the columns of <code>m</code>. You can use transposes and reshapes to work in different dimensions, if necessary.</p>
Remove Duplicated Entries From an Array <p>For removing the duplicated entries I know I have to use <code>array_unique()</code> but unfortunately by using this I got unexpected result(s). My PHP code is this:</p> <pre><code> $query = $db-&gt;query(" SELECT sid,father_contact,residential_contact FROM ".TABLE_PREFIX."student_list {$where_clause} ORDER BY sid ASC"); while ($s = $db-&gt;fetch_array($query)) { if (!empty($s['father_contact'])) { $father_contact = $s['father_contact'].', '; } else { $father_contact = ''; } if (!empty($s['residential_contact'])) { $residential_contact = $s['residential_contact'].', '; } else { $residential_contact = ''; } $phone_nums_bit .= $father_contact.$residential_contact; } </code></pre> <p>This grabs all phone numbers from the database tables and print the result like this:</p> <pre><code>03334523675, 03124237009, 03134237002, 03124237009, 03217832173, 03134237002, 3134237002, 03124237009, </code></pre> <p>Notice that few numbers like <code>03134237002</code> is repeating thrice. I want to remove duplicate entries from this result. Please help me to sort it out. Thanks.</p>
<p>You can try to do it via array structures. Just to give you an idea:</p> <pre><code>$phones = []; while ($s = $db-&gt;fetch_array($query)) { if (!empty($s['father_contact'])) { $phones[] = $s['father_contact']; } if (!empty($s['residential_contact'])) { $phones[] = $s['residential_contact']; } } $phones = array_unique($phones); // and then combine into string $phone_nums_bit = implode(', ', $phones); </code></pre>
Strange CDATA behavior in XHTML with JavaScript <p>i'm using blogger and i want to make my own template from scratch so i began to understand the very basic structure of how things are. In my journey through this i encounter the CDATA thing And i wanted to test this code.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;b:skin&gt; &lt;![CDATA[ ]]&gt; &lt;/b:skin&gt; &lt;/head&gt; &lt;body&gt; &lt;b:section id='post'/&gt; &lt;script&gt; if(true&amp;&amp;true) alert("hello"); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>It gives me an error and i know that the "&amp;" should be "&amp;" instead because it's xhtml so i add the cdata my code will become like this</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;b:skin&gt; &lt;![CDATA[ ]]&gt; &lt;/b:skin&gt; &lt;/head&gt; &lt;body&gt; &lt;b:section id='post'/&gt; &lt;script&gt; &lt;![CDATA[ if(true&amp;&amp;true) alert("hello"); ]]&gt; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Now that i test it the alert message wouldn't show up so i put // before the opening and closing CDATA tag and it works. I want to understand why the reason it works with // and not without.</p>
<p>Blogger parses the XML templates as XML, so they need to be valid XML to work with Blogger's backend.</p> <p>However, when Blogger serves the resulting page to the browser it says that the Content-Type is <code>text/html; charset=UTF-8</code> (which is wrong, because it is XHTML (but see below)).</p> <p>HTML and XHTML are different languages so when the browser parses the XHTML as HTML it doesn't do anything special with <code>&lt;![CDATA[</code> and just passes it to the JavaScript engine.</p> <p><code>&lt;![CDATA[</code> isn't valid JavaScript, so this throws an exception.</p> <p>By prefixing it <code>//</code>, you change the invalid JavaScript into a valid JavaScript line comment.</p> <hr> <p><em>aside</em>: XHTML and HTML are similar enough that you can get away with pretending your XHTML is HTML if you <a href="https://www.w3.org/TR/xhtml-media-types/" rel="nofollow">follow the compatibility guidelines</a>.</p>
Go slices and loops: Multilple loop through slice items while reducing the items with 1 each on each loop <p>I have a slice of ints that I want to loop through multiple times, but each time I do another loop, I want to exclude the item from the parent loop.</p> <p>Something like this:</p> <pre><code>func main() { as := []int{0, 1, 2, 3} for i, a := range as { bs := make([]int, len(as)) copy(bs, as) bs = append(bs[:i], bs[i+1:]...) for i, b := range bs { cs := make([]int, len(bs)) copy(cs, bs) cs = append(cs[:i], cs[i+1:]...) for i, c := range cs { ds := make([]int, len(cs)) copy(ds, cs) ds = append(ds[:i], ds[i+1:]...) for _, d := range ds { fmt.Println(a, b, c, d) } } } } } </code></pre> <p>The output of this code is:</p> <pre><code>0123 0132 0213 0231 0312 0321 1023 1032 1203 1230 1302 1320 2013 2031 2103 2130 2301 2310 3012 3021 3102 3120 3201 3210 </code></pre> <p>Which is what I wanted. But this code does not look so good. I have to copy the slice multiple times before I remove an item, and then loop through the items on that slice. Is there a better and more dry way for me to achieve what I am doing here? I am going to the same thing for a slice that looks like this: <code>[]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}</code></p> <p>I don't think writing each loop like I have done 10 times is a good way of doing things. Any suggestions how I can do this?</p>
<p>You don't seem to know that what you are doing is called <em>generating permutations</em>. Otherwise it would be easy to google an efficient algorithm for doing it.</p>
exception thrown when creating an array c++ <p>Im basically generating a array for a flat plane in my game using this algorithm, but I couldn't get it to work as there is a exception when I run the program. (GLuint is just unsigned int in opengl)</p> <pre><code>const GLuint planeDimension = 30.0f; const GLuint half = planeDimension / 2; const GLuint verticesCount = planeDimension * planeDimension; int counter = 0; GLfloat planeVertices[verticesCount]; for (GLuint length = 0; length &lt; planeDimension; length++) { for (GLuint width = 0; width &lt; planeDimension; width++) { planeVertices[counter++] = length - half; planeVertices[counter++] = 0.0f; planeVertices[counter++] = width - half; } } </code></pre>
<p>You're accessing outside the array in your loop. Your loop has as one iteration for each element in <code>planeVertices</code>. But you're incrementing <code>counter</code> 3 times each time through the loop. So about 1/3 of the way through all the loops <code>counter</code> will reach the end of the array, then you'll start writing outside the array, which causes undefined behavior.</p> <p>I'm not sure what you're trying to do. Why are you writing 3 different elements of the array each time through the loop? So it's not clear how to fix it. You could simply declare it 3 times as large:</p> <pre><code>GLfloat planeVertices[verticesCount * 3]; </code></pre> <p>Or you could declare it as a 2-dimensional array:</p> <pre><code>GLfloat planeVertices[verticesCount][3]; </code></pre> <p>Then your loop would do:</p> <pre><code>planeVertices[counter][0] = length - half; planeVertices[counter][1] = 0.0f; planeVertices[counter][2] = width - half; counter++; </code></pre>
XSLT grouping by sibling node value <p>In the following sample XML subsides should be grouped to "Number"-node value. I already tried grouping the Muenchian method but couldn't get it done yet. The XSLT must be in 1.0. For every Number-node a box should be created and each value should be grouped to it. Problems is also possible multiple values in node, these should be shown separately. Thank you for any assistance you give me in this!</p> <pre><code>&lt;ROOT&gt; &lt;PROC&gt; &lt;DATA&gt; &lt;Number&gt;002&lt;/Number&gt; &lt;Registration&gt;27754&lt;/Registration&gt; &lt;Country&gt;Finland&lt;/Country&gt; &lt;DATA&gt; &lt;PROC&gt; &lt;PROC&gt; &lt;DATA&gt; &lt;Number&gt;003&lt;/Number&gt; &lt;Registration&gt;42852&lt;/Registration&gt; &lt;Country&gt;Sweden&lt;/Country&gt; &lt;DATA&gt; &lt;PROC&gt; &lt;PROC&gt; &lt;DATA&gt; &lt;Number&gt;003&lt;/Number&gt; &lt;Registration&gt;H/11/019|H/11/020|H/11/021&lt;/Registration&gt; &lt;Country&gt;Slovenia&lt;/Country&gt; &lt;DATA&gt; &lt;PROC&gt; &lt;PROC&gt; &lt;DATA&gt; &lt;Number&gt;002&lt;/Number&gt; &lt;Registration&gt;19481&lt;/Registration&gt; &lt;Country&gt;Denmark&lt;/Country&gt; &lt;DATA&gt; &lt;PROC&gt; &lt;PROC&gt; &lt;DATA&gt; &lt;Number&gt;004&lt;/Number&gt; &lt;Registration&gt;09-23&lt;/Registration&gt; &lt;Country&gt;Norway&lt;/Country&gt; &lt;DATA&gt; &lt;PROC&gt; &lt;/ROOT&gt; </code></pre> <p>The above code should be shown as followed:</p> <pre><code>&lt;main&gt; &lt;rbox&gt; &lt;vNumber&gt;002&lt;/vNumber&gt; &lt;bbox&gt; &lt;State&gt;Finland&lt;/State&gt; &lt;gbox&gt; &lt;Registrations&gt; &lt;Registration&gt;27754&lt;/Registration&gt; &lt;/Registrations&gt; &lt;/gbox&gt; &lt;/bbox&gt; &lt;bbox&gt; &lt;State&gt;Denmark&lt;/State&gt; &lt;gbox&gt; &lt;Registrations&gt; &lt;Registration&gt;19481&lt;/Registration&gt; &lt;/Registrations&gt; &lt;/gbox&gt; &lt;/bbox&gt; &lt;/rbox&gt; &lt;rbox&gt; &lt;vNumber&gt;003&lt;/vNumber&gt; &lt;bbox&gt; &lt;State&gt;Slovenia&lt;/State&gt; &lt;gbox&gt; &lt;Registrations&gt; &lt;Registration&gt;H/11/019&lt;/Registration&gt; &lt;/Registrations&gt; &lt;Registrations&gt; &lt;Registration&gt;H/11/020&lt;/Registration&gt; &lt;/Registrations&gt; &lt;Registrations&gt; &lt;Registration&gt;H/11/021&lt;/Registration&gt; &lt;/Registrations&gt; &lt;/gbox&gt; &lt;/bbox&gt; &lt;bbox&gt; &lt;State&gt;Sweden&lt;/State&gt; &lt;gbox&gt; &lt;Registrations&gt; &lt;Registration&gt;42852&lt;/Registration&gt; &lt;/Registrations&gt; &lt;/gbox&gt; &lt;/bbox&gt; &lt;/rbox&gt; ... &lt;/main&gt; </code></pre> <hr> <p>thank your for your fast response. Here is my code so far. I couldn't manage to get the Country and Registration Data to sort to the number record without creating multiple values. I also tried concate values in the key "use" but this also doesn't work.</p> <pre><code>&lt;xsl:key name="country" match="ROOT/PROC/DATA" use="Country"/&gt; &lt;xsl:key name="registration" match="ROOT/PROC/DATA" use="Registration"/&gt; &lt;xsl:template match="/"&gt; &lt;main&gt; &lt;xsl:for-each select="//Number[not(.=preceding::*)]"&gt; &lt;rbox&gt; &lt;xsl:element name="vNumber"&gt; &lt;vNumber&gt;&lt;xsl:value-of select="."/&gt;&lt;/vNumber&gt; &lt;xsl:for-each select="//DATA[generate-id() = generate-id(key('country', Country)[1])]"&gt; &lt;bbox&gt; &lt;State&gt;&lt;xsl:value-of select="Country"/&gt;&lt;/State&gt; &lt;gbox&gt; &lt;xsl:for-each select="//DATA[generate-id() = generate-id(key('registration', Registration)[1])]"&gt; &lt;Registrations&gt; &lt;Registration&gt;&lt;xsl:value-of select="Registration"/&gt;&lt;/Registration&gt; &lt;/Registrations&gt; &lt;/xsl:for-each&gt; &lt;/gbox&gt; &lt;/bbox&gt; &lt;/xsl:for-each&gt; &lt;/xsl:element&gt; &lt;/rbox&gt; &lt;/xsl:for-each&gt; &lt;/main&gt; &lt;/xsl:template&gt; </code></pre> <p>**** EDIT: Complete stylesheet after help from michael.hor257k regarding grouping problem ---> Concerned products</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/" xmlns:maa="http://www.oma.trp/maa/" xmlns:rdm="http://www.oma.trp/dictionary/" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"&gt; &lt;xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/&gt; &lt;xsl:param name="ns-prefix" select="'xfa'"/&gt; &lt;xsl:param name="ns-namespace" select="'http://www.xfa.org/schema/xfa-data/1.0/'"/&gt; &lt;xsl:param name="ns-prefix1" select="'maa'"/&gt; &lt;xsl:param name="ns-namespace1" select="'http://www.oma.trp/maa/'"/&gt; &lt;xsl:param name="ns-prefix2" select="'rdm'"/&gt; &lt;xsl:param name="ns-namespace2" select="'http://www.oma.trp/dictionary/'"/&gt; &lt;xsl:param name="ns-prefix3" select="'xsi'"/&gt; &lt;xsl:param name="ns-namespace3" select="'http://www.w3.org/2001/XMLSchemainstance'"/&gt; &lt;xsl:param name="ns-prefix4" select="'schemaLocation'"/&gt; &lt;xsl:param name="ns-namespace4" select="'http://www.oma.trp/maa/variations.xsd'"/&gt; &lt;xsl:param name="ns-schema" select="'http://www.oma.trp/maa/variations.xsd'"/&gt; &lt;xsl:variable name="vRdm" select="document('')/*/namespace::*[name()='rdm']"/&gt; &lt;xsl:variable name="vXsi" select="document('')/*/namespace::*[name()='xsi']"/&gt; &lt;xsl:variable name="vSchemaLocation" select="document('')/*/namespace::*[name()='schemaLocation']"/&gt; &lt;xsl:template match="/"&gt; &lt;xsl:element name="{$ns-prefix}:data" namespace="{$ns-namespace}"&gt; &lt;xsl:element name="{$ns-prefix1}:eu_application_form" namespace="{$ns-namespace1}"&gt; &lt;xsl:copy-of select="$vRdm"/&gt; &lt;xsl:copy-of select="$vXsi"/&gt; &lt;xsl:copy-of select="$vSchemaLocation"/&gt; &lt;xsl:attribute name="xsi:schemaLocation"&gt; &lt;xsl:value-of select="$ns-schema" /&gt; &lt;/xsl:attribute&gt; &lt;xsl:template match="/"&gt; &lt;maa:variations-form&gt; &lt;xsl:element name="{$ns-prefix1}:applicationInformation"&gt; &lt;xsl:element name="{$ns-prefix1}:human"&gt;1&lt;/xsl:element&gt; &lt;xsl:element name="{$ns-prefix1}:veterinary"&gt;0&lt;/xsl:element&gt; &lt;xsl:element name="{$ns-prefix1}:nationalAuthInMRP"&gt;1&lt;/xsl:element&gt; &lt;xsl:element name="{$ns-prefix1}:euAuthorisation"&gt;0&lt;/xsl:element&gt; &lt;xsl:element name="{$ns-prefix1}:nationalAuthorisation"&gt;0&lt;/xsl:element&gt; &lt;xsl:element name="{$ns-prefix1}:procedureNumbers"&gt; &lt;xsl:element name="{$ns-prefix1}:procedureNumber"&gt;&lt;/xsl:element&gt; &lt;/xsl:element&gt; &lt;!--RMS country Loop start --&gt; &lt;xsl:template match="/"&gt; &lt;xsl:element name="{$ns-prefix1}:referenceMemberState"&gt; &lt;xsl:choose&gt; &lt;xsl:when test="ROOT/PROC/DATA/Procedure_Number[contains(text(),'DK')]"&gt; &lt;xsl:text&gt;Denmark&lt;/xsl:text&gt; &lt;/xsl:when&gt; &lt;xsl:when test="ROOT/PROC/DATA/Procedure_Number[contains(text(),'SI')]"&gt; &lt;xsl:text&gt;Slovenia&lt;/xsl:text&gt; &lt;/xsl:when&gt; &lt;/xsl:choose&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; &lt;!--RMS country Loop end --&gt; &lt;!--CMS country Loop start --&gt; &lt;xsl:template match="/"&gt; &lt;xsl:for-each select="//Country_Name[not(.=preceding::*)]"&gt; &lt;maa:concernedMemberStates&gt; &lt;maa:concernedMemberState&gt;&lt;xsl:value-of select="."/&gt;&lt;/maa:concernedMemberState&gt; &lt;/maa:concernedMemberStates&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; &lt;!--CMS country Loop end --&gt; &lt;!--CONCERNED PRODUCTS --&gt; &lt;/xsl:element&gt; &lt;xsl:template match="/"&gt; &lt;main&gt; &lt;products&gt; &lt;maa:formAndStrengthFlag&gt;0&lt;/maa:formAndStrengthFlag&gt; &lt;maa:footnote/&gt; &lt;!--CONCERNED PRODUCTS --&gt; &lt;xsl:key name="strength" match="ROOT/PROC/DATA" use="Speciality_Number"/&gt; &lt;xsl:for-each select="ROOT/PROC/DATA[generate-id() = generate-id(key('strength', Speciality_Number)[1])]"&gt; &lt;redbox&gt; &lt;variationNumber&gt;&lt;xsl:value-of select="Speciality_Number"/&gt;&lt;/variationNumber&gt; &lt;!-- for each member of the current group --&gt; &lt;xsl:for-each select="key('strength', Speciality_Number)"&gt; &lt;blueBox&gt; &lt;memberState&gt;&lt;xsl:value-of select="Country_Name"/&gt;&lt;/memberState&gt; &lt;greenBox&gt; &lt;maNumbers&gt; &lt;maNumber&gt;&lt;xsl:value-of select="Registration_Number"/&gt;&lt;/maNumber&gt; &lt;/maNumbers&gt; &lt;/greenBox&gt; &lt;/blueBox&gt; &lt;/xsl:for-each&gt; &lt;/redbox&gt; &lt;/xsl:for-each&gt; &lt;/products&gt; &lt;/main&gt; &lt;/xsl:template&gt; &lt;/maa:variations-form&gt; &lt;/xsl:template&gt; &lt;/xsl:element&gt; &lt;xsl:element name="FSTEMPLATE_"&gt;/Applications/eAFForms/1.20/Forms/Variation/Form/variation.xdp &lt;/xsl:element&gt; &lt;xsl:element name="FSFORMQUERY_"&gt;/Applications/eAFForms/1.20/Forms/Variation/Form/variation.xdp &lt;/xsl:element&gt; &lt;xsl:element name="FSTRANSFORMATIONID_"&gt;PDFForm&lt;/xsl:element&gt; &lt;xsl:element name="FSTARGETURL_"/&gt; &lt;xsl:element name="FSAWR_"/&gt; &lt;xsl:element name="FSWR_"/&gt; &lt;xsl:element name="FSCRURI_"&gt;repository://&lt;/xsl:element&gt; &lt;xsl:element name="FSBASEURL_"/&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; </code></pre> <p></p>
<p>If you want to group the <code>DATA</code> elements by <code>Number</code>, you need to make your key match <code>DATA</code> and use <code>Number</code>.</p> <p>Try the following stylesheet:</p> <p><strong>XSLT 1.0</strong></p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/&gt; &lt;xsl:key name="grp" match="DATA" use="Number"/&gt; &lt;xsl:template match="/ROOT"&gt; &lt;main&gt; &lt;!-- create a group for each distinct Number --&gt; &lt;xsl:for-each select="PROC/DATA[generate-id() = generate-id(key('grp', Number)[1])]"&gt; &lt;rbox&gt; &lt;vNumber&gt; &lt;xsl:value-of select="Number"/&gt; &lt;/vNumber&gt; &lt;!-- for each member of the current group --&gt; &lt;xsl:for-each select="key('grp', Number)"&gt; &lt;bbox&gt; &lt;State&gt; &lt;xsl:value-of select="Country"/&gt; &lt;/State&gt; &lt;gbox&gt; &lt;Registrations&gt; &lt;xsl:copy-of select="Registration"/&gt; &lt;/Registrations&gt; &lt;/gbox&gt; &lt;/bbox&gt; &lt;/xsl:for-each&gt; &lt;/rbox&gt; &lt;/xsl:for-each&gt; &lt;/main&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <hr> <p>Your input is not well-formed XML, but when the above stylesheet is applied to the following input:</p> <p><strong>XML</strong></p> <pre><code>&lt;ROOT&gt; &lt;PROC&gt; &lt;DATA&gt; &lt;Number&gt;002&lt;/Number&gt; &lt;Registration&gt;27754&lt;/Registration&gt; &lt;Country&gt;Finland&lt;/Country&gt; &lt;/DATA&gt; &lt;/PROC&gt; &lt;PROC&gt; &lt;DATA&gt; &lt;Number&gt;003&lt;/Number&gt; &lt;Registration&gt;42852&lt;/Registration&gt; &lt;Country&gt;Sweden&lt;/Country&gt; &lt;/DATA&gt; &lt;/PROC&gt; &lt;PROC&gt; &lt;DATA&gt; &lt;Number&gt;003&lt;/Number&gt; &lt;Registration&gt;H/11/019|H/11/020|H/11/021&lt;/Registration&gt; &lt;Country&gt;Slovenia&lt;/Country&gt; &lt;/DATA&gt; &lt;/PROC&gt; &lt;PROC&gt; &lt;DATA&gt; &lt;Number&gt;002&lt;/Number&gt; &lt;Registration&gt;19481&lt;/Registration&gt; &lt;Country&gt;Denmark&lt;/Country&gt; &lt;/DATA&gt; &lt;/PROC&gt; &lt;PROC&gt; &lt;DATA&gt; &lt;Number&gt;004&lt;/Number&gt; &lt;Registration&gt;09-23&lt;/Registration&gt; &lt;Country&gt;Norway&lt;/Country&gt; &lt;/DATA&gt; &lt;/PROC&gt; &lt;/ROOT&gt; </code></pre> <p>the result will be:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;main&gt; &lt;rbox&gt; &lt;vNumber&gt;002&lt;/vNumber&gt; &lt;bbox&gt; &lt;State&gt;Finland&lt;/State&gt; &lt;gbox&gt; &lt;Registrations&gt; &lt;Registration&gt;27754&lt;/Registration&gt; &lt;/Registrations&gt; &lt;/gbox&gt; &lt;/bbox&gt; &lt;bbox&gt; &lt;State&gt;Denmark&lt;/State&gt; &lt;gbox&gt; &lt;Registrations&gt; &lt;Registration&gt;19481&lt;/Registration&gt; &lt;/Registrations&gt; &lt;/gbox&gt; &lt;/bbox&gt; &lt;/rbox&gt; &lt;rbox&gt; &lt;vNumber&gt;003&lt;/vNumber&gt; &lt;bbox&gt; &lt;State&gt;Sweden&lt;/State&gt; &lt;gbox&gt; &lt;Registrations&gt; &lt;Registration&gt;42852&lt;/Registration&gt; &lt;/Registrations&gt; &lt;/gbox&gt; &lt;/bbox&gt; &lt;bbox&gt; &lt;State&gt;Slovenia&lt;/State&gt; &lt;gbox&gt; &lt;Registrations&gt; &lt;Registration&gt;H/11/019|H/11/020|H/11/021&lt;/Registration&gt; &lt;/Registrations&gt; &lt;/gbox&gt; &lt;/bbox&gt; &lt;/rbox&gt; &lt;rbox&gt; &lt;vNumber&gt;004&lt;/vNumber&gt; &lt;bbox&gt; &lt;State&gt;Norway&lt;/State&gt; &lt;gbox&gt; &lt;Registrations&gt; &lt;Registration&gt;09-23&lt;/Registration&gt; &lt;/Registrations&gt; &lt;/gbox&gt; &lt;/bbox&gt; &lt;/rbox&gt; &lt;/main&gt; </code></pre>
Why Python pickling library complain about class member that doesn't exist? <p>I have the following simple class definition:</p> <pre><code>def apmSimUp(i): return APMSim(i) def simDown(sim): sim.close() class APMSimFixture(TestCase): def setUp(self): self.pool = multiprocessing.Pool() self.sims = self.pool.map( apmSimUp, range(numCores) ) def tearDown(self): self.pool.map( simDown, self.sims ) </code></pre> <p>Where class APMSim is defined purely by plain simple python primitive types (string, list etc.) the only exception is a static member, which is a multiprocessing manager.list</p> <p>However, when I try to execute this class, I got the following error information:</p> <pre><code>Error Traceback (most recent call last): File "/home/peng/git/datapassport/spookystuff/mav/pyspookystuff_test/mav/__init__.py", line 77, in setUp range(numCores) File "/usr/lib/python2.7/multiprocessing/pool.py", line 251, in map return self.map_async(func, iterable, chunksize).get() File "/usr/lib/python2.7/multiprocessing/pool.py", line 567, in get raise self._value MaybeEncodingError: Error sending result: '[&lt;pyspookystuff.mav.sim.APMSim object at 0x7f643c4ca8d0&gt;]'. Reason: 'TypeError("can't pickle thread.lock objects",)' </code></pre> <p>Which is strange as thread.lock cannot be found anywhere, I strictly avoid any multithreading component (as you can see, only multiprocessing component is used). And none of these component exist in my class, or only as static member, what should I do to make this class picklable?</p> <p>BTW, is there a way to exclude a black sheep member from pickling? Like Java's @transient annotation?</p> <p>Thanks a lot for any help!</p> <p><strong>UPDATE</strong>: The following is my full APMSim class, please see if you find anything that violates it picklability:</p> <pre><code>usedINums = mav.manager.list() class APMSim(object): global usedINums @staticmethod def nextINum(): port = mav.nextUnused(usedINums, range(0, 254)) return port def __init__(self, iNum): # type: (int) -&gt; None self.iNum = iNum self.args = sitl_args + ['-I' + str(iNum)] @staticmethod def create(): index = APMSim.nextINum() try: result = APMSim(index) return result except Exception as ee: usedINums.remove(index) raise @lazy def _sitl(self): sitl = SITL() sitl.download('copter', '3.3') sitl.launch(self.args, await_ready=True, restart=True) print("launching .... ", sitl.p.pid) return sitl @lazy def sitl(self): self.setParamAndRelaunch('SYSID_THISMAV', self.iNum + 1) return self._sitl def _getConnStr(self): return tcp_master(self.iNum) @lazy def connStr(self): self.sitl return self._getConnStr() def setParamAndRelaunch(self, key, value): wd = self._sitl.wd print("relaunching .... ", self._sitl.p.pid) v = connect(self._getConnStr(), wait_ready=True) # if use connStr will trigger cyclic invocation v.parameters.set(key, value, wait_ready=True) v.close() self._sitl.stop() self._sitl.launch(self.args, await_ready=True, restart=True, wd=wd, use_saved_data=True) v = connect(self._getConnStr(), wait_ready=True) # This fn actually rate limits itself to every 2s. # Just retry with persistence to get our first param stream. v._master.param_fetch_all() v.wait_ready() actualValue = v._params_map[key] assert actualValue == value v.close() def close(self): self._sitl.stop() usedINums.remove(self.iNum) </code></pre> <p>lazy decorator is from this library:</p> <p><a href="https://docs.python.org/2/tutorial/classes.html#generator-expressions" rel="nofollow">https://docs.python.org/2/tutorial/classes.html#generator-expressions</a></p>
<p>It would help to see how your class looks, but if it has methods from <code>multiprocessing</code> you may have issues just pickling it by default. Multiprocessing objects can use locks as well, and these are (obviously) unpickle-able.</p> <p>You can customize pickling with the <a href="https://docs.python.org/dev/library/pickle.html?highlight=pickle#object.__getstate__" rel="nofollow"><code>__getstate__</code></a> method, or <code>__reduce__</code> (documented in the same place).</p>
Rx - CombineLatest Queue <p>I am trying to achieve Queue like functionality using Rx (I know I can accomplish it using a Queue + Locking, but trying to learn + use Rx as I don't get many opportunities to use it).</p> <p>Functionality is, I want to take some action on an event to do, but only want to process one at a time, and once finished, process the next/last one (if it is new).</p> <p>This is what I have at the moment (using an incrementing flag observable so I can do <code>DistinctUntilChanged</code>, but that feels like a hack).</p> <pre><code> // Some source var events = new Subject&lt;string&gt;(); events.Subscribe(s =&gt; Console.WriteLine("Event: " + s)); // How can I get rid of this var counter = 0; var flag = new Subject&lt;int&gt;(); flag.Subscribe(i =&gt; Console.WriteLine("Flag: " + i)); var combined = events .CombineLatest(flag, (s, i) =&gt; new {Event = s, Flag = i}); var worker = combined .DistinctUntilChanged(arg =&gt; arg.Flag) .DistinctUntilChanged(arg =&gt; arg.Event); worker.Subscribe(x =&gt; Console.WriteLine("\r\nDo Work: " + x.Event + "\r\n")); flag.OnNext(counter++); // Ready events.OnNext("one"); // Idle, Start eight events.OnNext("two"); events.OnNext("three"); events.OnNext("four"); events.OnNext("five"); // Process flag.OnNext(counter++); // Finished one, start five events.OnNext("six"); events.OnNext("seven"); events.OnNext("eight"); // Idle, Start eight flag.OnNext(counter++); // Finished five, start eight flag.OnNext(counter++); // Finished eight events.OnNext("nine"); // Should be processed </code></pre> <p>If you run this code, you will see that the last event does not get processed, even though the actor is idle.</p> <p>Feels like I am missing something here....</p> <p>At the moment I am looking at using Observables of Observables somehow.... but been trying to figure this out for last couple or so hours :-(</p> <h1>Edit</h1> <p>Managed to do it by changing subject to ReplaySubject</p> <pre><code> var events = new ReplaySubject&lt;string&gt;(1); </code></pre> <p>and introducing one more variable, but seems like another hack, but it did let me get rid of the counter.</p> <pre><code> string lastSeen = null; flag.Select(x =&gt; events.Where(s =&gt; s != lastSeen).Take(1)) .Subscribe(x =&gt; x.Subscribe(s =&gt; { lastSeen = s; Console.WriteLine(s); }) ); </code></pre> <p>If someone knows a better way where I can get rid of <code>string lastSeen</code> or simplify my nesting/subscriptions that would be great.</p>
<p>If you are willing to mix in TPL DataFlow Blocks you can do what you want. Though I must say it's a bit non-Rxish.</p> <pre><code>var source = Observable.Interval(TimeSpan.FromSeconds(1)); var queue = new BroadcastBlock&lt;long&gt;(null); var subscription = queue.AsObservable().DistinctUntilChanged().Subscribe(l =&gt; { Thread.Sleep(2500); Console.WriteLine(l); }); source.SubscribeOn(ThreadPoolScheduler.Instance).Subscribe(queue.AsObserver()); </code></pre> <p>The <a href="https://msdn.microsoft.com/en-us/library/hh160447(v=vs.110).aspx" rel="nofollow">BroadcastBlock</a> is the queue that will only hold the last value. The TPL DataFlow Blocks do have nice support with Rx. So we can subscribe to the event and put that into the BroadcastBlock and then subscribe off the BroadcastBlock. </p>
C# and Javascript - How to Add Remove Objects To A Javascript Array and Postback to Server? <p>I have a form where there is a section for a user to add multiple appointment dates. This section of the form has the following fields: startdate, enddate and a add button.</p> <pre><code> &lt;form action="/someaction"&gt; Start Date &lt;input type="text" id="StartDate" name="StartDate"&gt;&lt;br&gt; End Date: &lt;input type="text" id="EndDate" name="EndDate"&gt;&lt;br&gt; &lt;a class="btn btn-default js-add" href="#" role="button"&gt;Add&lt;/a&gt; &lt;table class="table" &gt; &lt;tbody id="dates" &gt; &lt;/tbody&gt; &lt;/table&gt; // Other form fields &lt;input type="submit" value="Submit"&gt; &lt;/form&gt; </code></pre> <p>Each time a user adds an appointment I want to store the values in an JavaScript object array and display the number of items in the array along with details of the object added with an option to remove it from the list. Below is my initial attempt:</p> <pre><code>&lt;script&gt; var appointments = []; $(".js-add").click(function (e) { e.preventDefault(); var startDate = $("#StartDate").val(); var endDate = ("#EndDate").val() // What can I use to uniquely identify each object incase we need to delete??? appointments.push( { startDate: startDate , endDate: endDate }); $('&lt;tr/&gt;', { html: '&lt;td &gt;' + startDate + '&lt;/td&gt;&lt;td&gt;' + endDate + '&lt;/td&gt;&lt;td&gt;&lt;a class="js-delete" href="" data-id=""&gt;delete&lt;/a&gt;&lt;/td&gt;'}) .appendTo($('#dates')); } $(".js-delete").click(function (e) { e.preventDefault(); var id = $(this).attr("data-id"); // How do I remove the selected object from the array??? // appointments.splice(x,1); } &lt;/script&gt; </code></pre> <p>How do I remove the object from the array using the array index. I have a data-id attribute on the delete link which would contain the array index.</p> <p>But the array index can change each time an object is added or deleted so how can I update the data-id attribute on existing rows?</p> <p>Secondly, how do I pass this object back to the server since it isn't attached to any form input field? </p> <p>Some help would be appreciated?</p>
<blockquote> <p>How do I remove the object from the array. I have a data-id attribute on the delete link but what can I use to uniquely identify the object.</p> </blockquote> <p>Because you create a new table row you need to:</p> <ul> <li>delegate event (i.e.: $(document).on('click', '.js-delete', function (e) {)</li> <li>use the data-id attribute to assign it the value of the index of the current element in array.</li> <li>on deleting a row you need to rearrange the values of the data-id </li> </ul> <blockquote> <p>How do I pass this object back to the server </p> </blockquote> <p>You may use an hidden input field and set its value with the array value.</p> <p>The snippet:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var appointments = []; // // delegated event // $(document).on('click', '.js-delete', function (e) { e.preventDefault(); var id = +$(this).attr("data-id"); appointments.splice(id, 1); $(this).closest('tr').remove(); // // rearrange the values of data-id attributes // $('#dates tr td:nth-child(3) a').each(function(index, element) { var tId = +$(element).attr("data-id"); if (tId &gt; id) { $(element).attr("data-id", tId - 1); } }); }); $(function () { $(".js-add").click(function (e) { e.preventDefault(); var startDate = $("#StartDate").val(); var endDate = $("#EndDate").val(); // In order to uniquely identify each object you can set the // value of data-id attribute with current array index appointments.push( { startDate: startDate , endDate: endDate }); $('&lt;tr/&gt;', { html: '&lt;td &gt;' + startDate + '&lt;/td&gt;&lt;td&gt;' + endDate + '&lt;/td&gt;&lt;td&gt;&lt;a class="js-delete" href="" data-id="' + (appointments.length - 1) + '"&gt;delete&lt;/a&gt;&lt;/td&gt;'}) .appendTo($('#dates')); // // a possible sorting.... Consider to use a date compare // instead of a string compare function. // $.each($('#dates tr').get().sort(function(a, b) { return a.childNodes[0].textContent.localeCompare(b.childNodes[0].textContent); }), function(index, ele) { $('#dates').append(ele); }); }); // // On form submit stringify your array and save it into // an hidden input field // $('input[type="submit"]').on('click', function(e) { e.preventDefault(); $('#appointments').val(JSON.stringify(appointments)); console.log($('#appointments').val()); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://code.jquery.com/jquery-1.12.4.min.js"&gt;&lt;/script&gt; &lt;form action="/someaction"&gt; &lt;input id="appointments" type="hidden"&gt; Start Date &lt;input type="text" id="StartDate" name="StartDate"&gt;&lt;br&gt; End Date: &lt;input type="text" id="EndDate" name="EndDate"&gt;&lt;br&gt; &lt;a class="btn btn-default js-add" href="#" role="button"&gt;Add&lt;/a&gt; &lt;table class="table" &gt; &lt;tbody id="dates" &gt; &lt;/tbody&gt; &lt;/table&gt; &lt;!-- Other form fields --&gt; &lt;input type="submit" value="Submit"&gt; &lt;/form&gt;</code></pre> </div> </div> </p>
I don't understand what args[0][0]-'!' means <p>I stumbled upon this block of code and I want to understand what <code>args[0][0]-'!'</code> means?</p> <pre><code>else if (args[0][0]-'!' ==0) { int x = args[0][1]- '0'; int z = args[0][2]- '0'; if(x&gt;count) //second letter check { printf("\nNo Such Command in the history\n"); strcpy(inputBuffer,"Wrong command"); } else if (z!=-48) //third letter check { printf("\nNo Such Command in the history. Enter &lt;=!9 (buffer size is 10 along with current command)\n"); strcpy(inputBuffer,"Wrong command"); } else { if(x==-15)//Checking for '!!',ascii value of '!' is 33. { strcpy(inputBuffer,history[0]); // this will be your 10 th(last) command } else if(x==0) //Checking for '!0' { printf("Enter proper command"); strcpy(inputBuffer,"Wrong command"); } else if(x&gt;=1) //Checking for '!n', n &gt;=1 { strcpy(inputBuffer,history[count-x]); } } </code></pre> <p>This code is from this github account: <a href="https://github.com/deepakavs/Unix-shell-and-history-feature-C/blob/master/shell2.c" rel="nofollow">https://github.com/deepakavs/Unix-shell-and-history-feature-C/blob/master/shell2.c</a></p>
<p><code>args</code> is a <code>char**</code>, or in other words, an array of strings (character arrays). So:</p> <pre><code>args[0] // first string in args args[0][0] // first character of first string in args args[0][0]-'!' // value of subtracting the character value of ! from // the first character in the first string in args args[0][0]-'!' == 0 // is said difference equal to zero </code></pre> <p>In other words, it checks if the first string in <code>args</code> starts with the <code>!</code> character.</p> <p>It could (and arguably should) be rewritten as</p> <pre><code>args[0][0] == '!' </code></pre> <p>As well as (but don't use this one):</p> <pre><code>**args == '!' </code></pre>
Why i can't declare and then assign value to a variable in a class without any method IN JAVA <p>It may sounds crazy but what i really want to do is just declare and initialize a member variable within a public class and then re-assign this variable with another value which is quite realistic in C. But it fails in Java. </p> <pre><code>public class App { public int id=6; // got an error of "Syntax error on token ";", , expected" id=7; } </code></pre> <p>But this could be done within a method. For example: </p> <pre><code>public class App { public int id=6; // id = 7; public void method() { id = 7; // that's okay } } </code></pre> <p>So, what really perplexing to me is that what makes the difference of using a method there in stead of re-assigning the member variable in the next line. I'm really looking forward to learn the insight conception of it if there exists any. </p> <p><strong>Difference to duplicate: I want to learn the methodology why OOPL forces to use methods/constructors if I try to re-assign any variable after initializing it ???</strong></p>
<p>Generally, in object oriented programming the 'class' represents a description of a particular object. If we use the analogy of a car, think of it as the 'blueprint'. </p> <p>The blueprint does a number of things:</p> <ul> <li>Describes what kind of properties the object can have (so a car might have color and speed)</li> <li>Describes what things the object can <em>do</em> (its 'methods')</li> <li>Describes what the initial state of the object is each time it is created</li> </ul> <p>The line <code>public int id=6</code> does the first and the last of these. It says that any <code>App</code> object must have an <code>id</code> property, and its initial state is the value <code>6</code>. If you then put the line <code>id=7</code> in the class definition this isn't part of the blue print - it doesn't make sense to say that the default value of <code>id</code> is 6, and then decide it is 7 - so this is an error.</p> <p>In Java, as with many object oriented languages, actual code that modifies state MUST take place inside a 'method', since every time something is happening in OOP, it is an 'object' <em>doing something</em>.</p> <p><strong>Edit</strong></p> <p>Your error is </p> <blockquote> <p>Syntax error on token ";", , expected</p> </blockquote> <p>This makes sense - it sees the following code</p> <pre><code> public int id=6; id=7; </code></pre> <p>And thinks what you really meant to do was</p> <pre><code> public int id=6, id=7; </code></pre> <p>Which would be the same as </p> <pre><code> public int id=6, id=7; </code></pre> <p>Of course this would generate another error probably unless you changed the name of the second definition.</p>
Loading font-family from disk to PrivateFontCollection <p>I'm using the following code to load a font into memory for generating an image with GDI+:</p> <pre><code>var fontCollection = new PrivateFontCollection(); fontCollection.AddFontFile(Server.MapPath("~/fonts/abraham-webfont.ttf")); fontCollection.Families.Count(); // =&gt; This line tells me, that the collection has 0 items. </code></pre> <p>There are no exceptions, but the fontCollection Families property is empty after the <code>AddFontFile</code> method has run without any exceptions.</p> <p>I've verified that the path is valid (<code>File.Exists</code> returns <code>true</code>):</p> <pre><code>Response.Write(System.IO.File.Exists(Server.MapPath("~/fonts/abraham-webfont.ttf"))); // # =&gt; Renders "True" </code></pre> <p>The TTF-file seems to work fine, when I open the file, so it's not an invalid TTF-file: <a href="https://i.stack.imgur.com/0R8HC.png" rel="nofollow"><img src="https://i.stack.imgur.com/0R8HC.png" alt="https://dl.dropboxusercontent.com/u/4899329/2016-10-12_22-44-52.png"></a></p> <p>Any suggestions?</p>
<p>Answer from Hans Passant solved the problem:</p> <p><em>PrivateFontCollection is notoriously flakey. One failure mode that's pretty common today is that the font is actually an OpenType font with TrueType outlines. GDI+ only supports "pure" ones. The shoe fits, the web says that Abraham is an OpenType font. Works in WPF, not in Winforms.</em></p>
UICollectionView not loading fully until I scroll <p>I have a collection view that I want to display hourly weather in. I seem to have a problem with loading the cell, and for some reason scrolling forwards and then back loads the cell fully. Before I scroll the collection view, all of the constraints do not work and one label doesn't show it's info.</p> <p><a href="https://i.stack.imgur.com/y6LbK.png" rel="nofollow"><img src="https://i.stack.imgur.com/y6LbK.png" alt="Before scrolling"></a> Before scrolling</p> <p><a href="https://i.stack.imgur.com/EWcfQ.png" rel="nofollow"><img src="https://i.stack.imgur.com/EWcfQ.png" alt="After scrolling (this is how I want the cells to look like)"></a> After scrolling (this is how I want the cells to look like)</p> <pre><code>func numberOfSectionsInCollectionView(collectionView: UICollectionView) -&gt; Int { // #warning Incomplete implementation, return the number of sections return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int { // #warning Incomplete implementation, return the number of items return newhourlyWeather.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -&gt; UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! hourlyWeatherCell // Configure the cell let hWeather = newhourlyWeather[indexPath.row] if let HourlyTemp = hWeather.temperatureh { cell.temperatureHLabel.text = "\(HourlyTemp)º" } if let HourlyTime = hWeather.convertedTimeH { cell.timeHLabel.text = "\(HourlyTime)" } if let HourlyRain = hWeather.precipProbabilityh { cell.rainChanceHLabel.text = "\(HourlyRain)%" } cell.iconhView.image = hWeather.iconh return cell self.collectionView.reloadData() } </code></pre>
<p>Seems like you populate your cells asynchronously, if so then add a mycollectionview.reloadData() at the end.</p>
Cannot resolve Mockito dependency in Gradle <p>Although I saw two different posts with this error message nothing worked with me:</p> <blockquote> <p>Error:(25, 17) Failed to resolve: org.mockito:mockito-core:1.10.19</p> </blockquote> <p>I tried to change the Mockito dependency using compile, androidTestCompile and testCompile and in the global Gradle file I tried to add Maven as repository but did not work.</p> <p>EDIT: I am using Android Studio 2.1</p> <p>This is my app build.gradle</p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 24 buildToolsVersion "24.0.0" defaultConfig { applicationId "ivano.android.com.mockitoexample" minSdkVersion 15 targetSdkVersion 24 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:24.2.1' testCompile 'junit:junit:4.12' testCompile 'org.mockito:mockito-core:1.10.19' } </code></pre> <p>and this the global one</p> <pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.1.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } </code></pre>
<p>I found the solution. In most of the tutorials is written to add mockito-core. Instead adding mockito-all fixed my problem, making gradle compiling without mistakes</p>
Insert empty row into jtable if lowest row gets edited <p>Is there a way to insert always an empty row if the lowest row gets edited?<br> I always want to have a free row on the bottom and if someone edits the lowest row, there should be automatically inserted a new one. </p> <p>I use that AbstractTableModel:</p> <pre><code>public class NativeTableModel extends AbstractTableModel { private static final long serialVersionUID = 1L; private ArrayList&lt;Spieler&gt; myObjects = null; private String[] columnNames = { "Vorname", "Nachname", "Trikotnummer" }; public NativeTableModel() { myObjects = new ArrayList&lt;Spieler&gt;(JNIResultSet.getMeineSpieler()); } @Override public int getRowCount() { return myObjects.size(); } @Override public String getColumnName(int index) { return columnNames[index]; } @Override public int getColumnCount() { return columnNames.length; } @Override public boolean isCellEditable(int row, int col) { boolean retValue = false; if (col &gt;= 1) { retValue = true; } return retValue; } @Override public void setValueAt(Object value, int row, int col) { switch (col) { case 0: if (value instanceof String) { // } break; case 1: if (value instanceof Integer) { // } break; } fireTableCellUpdated(row, col); } @Override public Object getValueAt(int rowIndex, int columnIndex) { Object value = ""; Spieler s = this.myObjects.get(rowIndex); switch (columnIndex) { case 0: value = s.getVorname(); break; case 1: value = s.getNachname(); break; case 2: value = s.getTrikotnummer(); break; } return value; } } </code></pre> <p>How can I check if the lowest row is empty or not and if it's empty insert a new row?</p>
<p>Suggestions:</p> <ul> <li>Change your table model to use an ArrayList as its data nucleus, not an inflexible 2D array.</li> <li>The generic type of the ArrayList should be a class that holds the data of a single row of your JTable.</li> <li>It should have an empty default state that signifies a row devoid of data.</li> <li>When data is changed in your table model's methods, check the last row of the model to see if the object held by the list here is default or holds data. </li> <li>If it holds data, add a new object to the list and call the appropriate fireXxx notification method.</li> <li>In setValue, you can check the rowCount, and you can compare it with the row parameter passed into the method. If they match, then add a new row. But you have to be careful of circular references if you do this, since adding the new row will likely call setValue as well, and so you'll have to have logic present to prevent a stackoverflow. Again, we can help better if we can work with your <a href="http://sscce.org" rel="nofollow">SSCCE</a>.</li> </ul>
How to process panel data for use in a recurrent neural network (RNN) <p>I have been doing some research on recurrent neural networks, but I am having trouble understanding if and how they could be used to analyze panel data (meaning cross-sectional data that is captured at different periods in time for several subjects -- see sample data below for example).Most examples of RNNs I have seen have to do with sequences of text, rather than true panel data, so I'm not sure if they are applicable to this type of data.</p> <p>Sample data:</p> <pre><code>ID TIME Y X1 X2 X3 1 1 5 3 0 10 1 2 5 2 2 6 1 3 6 6 3 11 2 1 2 2 7 2 2 2 3 3 1 19 2 3 3 8 6 1 3 1 7 0 2 0 </code></pre> <p>If I want to predict Y at a particular time given the covariates X1, X2 and X3 (as well as their values in previous time periods), can this kind of sequence be evaluated by a recurrent neural network? If so, do you have any resources or ideas on how to turn this type of data into feature vectors and matching labels that can be passed to an RNN (I'm using Python, but am open to other implementations).</p>
<p>I find no reason in being able to train neural network with panel data. What neural network does is that it maps one set of values with other set of values who have non-linear relation. In a time series a value at a particular instance depends on previous occuring values. Example: your pronunciation of a letter may vary depending on what letter you pronounced just earlier. For time series prediction Recurrent Neural Network outperforms feed-forward neural networks. How we train time series with a regular feed-forward network is illustrated in this picture. <a href="http://www.obitko.com/tutorials/neural-network-prediction/images/train.gif" rel="nofollow">Image</a></p> <p>In RNN we can create a feedback loop in the internal states of the network and that's why RNN is better at predicting time series. In your example data one thing to consider : do values of x1, x2, x3 have effect on y1 or vice-versa ? If it doesn't then you can train your model as such x1,x2,x3, y4 are same type of data i.e train them independently using same network (subject to experimentation). If your target is to predict a value where their values of one has effect on another i.e correlated you can convert them to one dimensional data where single time frame contains all variants of sample type. Another way might be train four neural networks where first three map their time series using RNN and last one is a feed-forward network which takes 2 inputs from 2 time series output and maps to 3rd time series output and do this for all possible combinations. (still subject to experimentation as we can't surely predict the performance of neural network model without experimenting)</p> <p><strong>Reading suggestion:</strong> Read about "Granger causality", might help you a bit.</p>
How can I create a CSS3 overflow hidden unmasking spotlight effect with rotation? <p>I want to create an effect whereby I have a static image, and that image is being unmasked by a rotating mask. I understand there is no way to do native masking in HTML5/CSS (that works in all browsers) so I'm using the mask:overflow method. </p> <p>I came across this link posted by Google: <a href="https://storage.googleapis.com/html5-demos/MaskRotateTranslate/index.html" rel="nofollow">https://storage.googleapis.com/html5-demos/MaskRotateTranslate/index.html</a></p> <p>I'm trying to achieve what's pictured in the second example. The only difference is that I don't need the inner image to animate, only it's "mask".</p> <p>This example appears to have been generated via Google Web Designer, so I can't really use it's code.</p> <p>I attempted to recreate it using the counter animation method (A div inside a div. The outer div acts as the 'mask'. When the outer div moves 30px to the right, the other moves -30px, creating the illusion of static content). This method worked for me until I started rotating the divs. Rotation seems to affect the x and y values of the content which kind of messes up the countering effect.</p> <p>Long story short.. How can I achieve a similar effect using simple Javascript or CSS animation? Has anyone had any success with this type of animation?</p>
<p>Here is my try :</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.image { width: 400px; height: 300px; background-image: url(http://placekitten.com/800/600); background-size: contain; position: absolute; left: 0px; right: 0px; animation: inner 4s infinite; } .container { width: 400px; height: 300px; left: 400px; position: relative; animation: outer 4s infinite; border: solid red 1px; overflow: hidden; } @keyframes inner { from {transform: rotate(0deg) translate(500px);} to {transform: rotate(360deg) translate(0px); } } @keyframes outer { from {transform: translate(-500px) rotate(0deg);} to {transform: translate(0px) rotate(-360deg);} }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt; &lt;div class="image"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
Looping through table to calculate separations - Python <p>Okay so I have a table of xy coordinates for a bunch of different points like this:</p> <blockquote> <pre><code> ID X Y 1 403.294 111.401 2 1771.424 62.183 3 804.812 71.674 4 2066.54 43.456 5 2208.55 40.907 </code></pre> </blockquote> <p>Each row represents an object with its ID, X, and Y listed. In reality, my table contains about 1345 rows. What I'm trying to do is loop through each row and calculate the separation of that object from all other objects in the table which I'll eventually use to make a histogram. What I have so far is: </p> <pre><code>sep_dat = np.zeros(shape=(5,5)) #create array for writing into dat = np.loadtxt('SEA_mini_test.tab') #table of data IDs = dat[:,0] X_dat = dat[:,1] X_dat = np.sort(X_dat) Y_dat = dat[:,2] Y_dat = np.sort(Y_dat) for i, x, y in zip(xrange(len(X_dat)), X_dat, Y_dat): sep_dat[i] = math.sqrt((x-X_dat)**2+(y-Y_dat)**2) np.savetxt('SEA_mini_seps.dat', sep_dat, fmt='%10.9f') </code></pre> <p>But I have yet to get it to run successfully. The last error I got was: </p> <blockquote> <p>TypeError: only length-1 arrays can be converted to Python scalars</p> </blockquote> <p>So how can I get this to run properly? </p> <p>And how could I get it to ignore itself when its doing the calculations? Like for object 1 (row 1) I don't want it to calculate the separation from itself. I tried adding the IDs into zip and adding an if statement inside the for loop before the calculation like <code>if id != id:</code> but that wouldn't work. Does anyone have an idea on how I could do this?</p> <p>And another question I had was, how could I write all the data into a flattened array? Right now, I have it create an empty array of zeros that I write over with the calculated values, but in the end I get a (5,5) array. But I want a (5,1) so that I can plot it as a histogram. Any ideas?</p>
<p>The error occurs because math.sqrt() can only take a float value, if you pass an np.array it will attempt to convert to a float. This only works if the array contains a single value.</p> <pre><code>&gt; math.sqrt(np.array([2])) 1.4142135623730951 &gt; math.sqrt(np.array([2,1])) Traceback (most recent call last): File "&lt;ipython-input-49-f9a9c77bfbdf&gt;", line 1, in &lt;module&gt; math.sqrt(np.array([2,1])) TypeError: only length-1 arrays can be converted to Python scalars </code></pre> <p>You can use np.sqrt() which will return an array of square roots.</p> <pre><code>&gt; x = np.arange(1,5) #[1,2,3,4] &gt; y = x[::-1] #[4,3,2,1] &gt; z = x**2 + y**2 #[1*1+4*4,...,4*4+1*1] &gt; np.sqrt(z) array([ 4.12310563, 3.60555128, 3.60555128, 4.12310563]) </code></pre> <p>If this is the desired behaviour</p>
Display: flex won't work in firefox or safari <p>I've seen this issue several places on here, but the solutions always had some little fix (e.g. including -moz-, typos, etc), all of which (I believe) I have checked. I'm trying to use flex to center some text vertically within its container. It works 100% in Chrome, but in both Firefox and Safari, I haven't had as much luck - the text I'm trying to display always ends up outside my container (typically to the right). In the pen at <a href="http://codepen.io/drewtadams/pen/XjYrGB" rel="nofollow">http://codepen.io/drewtadams/pen/XjYrGB</a>, I'm using squares with set heights/widths, but I need it to be able to work more dynamically than "top: 65px; left: 65px;" - the inline elements (black squares) will be text. Is there a fix to the display: flex, or is there a better/more conventional way to do this?</p> <p>HTML:</p> <pre><code>&lt;div class="flex-container valign--center"&gt; &lt;div class="box-container valign--center"&gt; &lt;div class="box1"&gt;&lt;/div&gt; &lt;div class="box2"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="box-container valign--center"&gt; &lt;div class="box1"&gt;&lt;/div&gt; &lt;div class="box2"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="box-container valign--center"&gt; &lt;div class="box1"&gt;&lt;/div&gt; &lt;div class="box2"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="box-container valign--center"&gt; &lt;div class="box1"&gt;&lt;/div&gt; &lt;div class="box2"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>.valign { display: -webkit-flex; display: -moz-flex; display: flex; -webkit-justify-content: center; -moz-justify-content: center; justify-content: center; } .valign--center { @extend .valign; align-items: center; -webkit-align-items: center; -moz-align-items: center; -ms-align-items: center; } .flex-container { border: 1px dashed red; .box-container { .box1 { background-color: green; height: 100px; width: 100px; margin: 25px; } .box2 { background-color: black; display: none; height: 20px; width: 20px; position: absolute; z-index: 2; } &amp;:hover { .box1 { opacity: 0.6; } .box2 { display: inline; } } }// end .box-container }// end .flex-container </code></pre> <p>P.S. I have a second container I'm playing with below the flex-container in the pen.</p>
<p>Why don't you set their heights to be the same, and then the second container set to vertically align in the center. I would use a plugin like matchHeight.js. It's super easy and you just put a matching data tag on each element and it will set the heights. for example and . That will match the heights for you and then just use the basic flex box to vertically center them.</p> <p><a href="https://github.com/liabru/jquery-match-height" rel="nofollow">https://github.com/liabru/jquery-match-height</a></p> <p>here is some flexbox vertical center code.</p> <pre><code>.vertical_center{ display:flex; flex-direction:column; justify-content:center; resize:vertical; align-items:center; min-height:25px; } </code></pre>
Spread operator in PhpStorm <p>my problem is that PhpStorm "red strikes" a spread operator in this line : <code>if(Math.max(...yearstab) !== (date + 2))</code>. I'd like to know if you found a way to prevent problems like that. Thanks.</p>
<p>Since spread operator was introduced in the <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-array-initializer" rel="nofollow">ECMAScript 2015 (6th Edition, ECMA-262)</a> you need to tell PhpStorm that you're using this version. </p> <p>You can do this by going in the project settings, "Languages &amp; Frameworks", "JavaScript" and set "JavaScript language version" to "ECMAScript 6"</p> <p><a href="https://i.stack.imgur.com/R0TAG.png" rel="nofollow"><img src="https://i.stack.imgur.com/R0TAG.png" alt="Screenshot"></a></p>
User input in my code is not working, what am I doing wrong? <p>My assignment is to take an array of ten numbers of the user input, and then find the lowest and highest numbers.</p> <p>I have done it according to class notes, but it is not working on netbeans.</p> <pre><code>import static java.lang.System.in; import java.util.Scanner; public class FindLargestSmallestNumber { public static void main(String[] args) { //array of 10 numbers int numbers[] = new int[]{0,0,0,0,0,0,0,0,0,0}; int i=0; for(int x=1; x&lt;numbers.length; i++) { Scanner user_input = new Scanner( System.in ); System.out.println ("What is the "+ x +" number of the array"); numbers [x] = in.nextInt( ); } //assign first element of an array to largest and smallest int smallest = numbers[0]; int largest = numbers[0]; for(i=1; i&lt; numbers.length; i++) { if(numbers[i] &gt; largest) largest = numbers[i]; else if (numbers[i] &lt; smallest) smallest = numbers[i]; } System.out.println("Largest Number is : " + largest); System.out.println("Smallest Number is : " + smallest); } } </code></pre>
<p>Your problem is you are incrementing <code>i</code> in the for loop and not <code>x</code> in the first for loop. That makes it run forever with <code>x==1</code>. Each time the loop code runs you are changing <code>i</code> which has no effect on the loop condition <code>x&lt;numbers.length</code>.</p> <p>You'll also want to start <code>x</code> at <code>0</code> instead of <code>1</code> since you index arrays starting at <code>0</code>.</p> <p>also, inside that for loop <code>in</code> is actually <code>System.in</code> since you statically imported it. you should write <code>user_input.nextInt()</code> instead, since that the <code>Scanner</code> you made. This kind of thing should be obvious to you, especially if you are using an IDE that highlights the stuff for you like netbeans.</p>
Refreshing Spark Properties on a Running Streaming job <p>I want to update the spark properties of a currently running spark streaming job.</p> <p>I have set some properties on SparkConf in the programs and some on spark-defaults.conf.</p> <p>How do i update them so that my curently running job will pick them?</p> <p>Is it possible to do like that?</p>
<p>Usually it is not possible to refresh configuration during runtime. Only certain SQL options can be changed with active context.</p> <p>Otherwise:</p> <ul> <li>modify configuration</li> <li>restart app</li> </ul>
How does Angular 2 know the parent instance without any explicit code? <p>Could anyone shed some light on me please. I have followed <a href="https://gist.github.com/nickjohnson-dev/bec769ee72fa2e8510323dce784cfab9" rel="nofollow">this example</a> to sketch out a simple wizard app in Angular 2. It works like a charm, except - what actually bothers me is the constructor in file <code>my-wizard-step.ts</code>. How come the private property <code>private parent: MyWizard</code> becomes automatically populated and this line <code>this.step = this.parent.addStep();</code> in <code>my-wizard-step.ts</code> works out of the box?</p> <p>I think there is something implicit going on which I don't quite figure out.</p> <p>How does Angular know that the parent is an instance of MyWizard that contains MyWizardStep? It's almost, kind of equivalent of jQuery's <code>.closest('.myWizard')</code> but I don't know the Angular2's rules that stand behind it.</p> <p>Anyone care to explain it to me, please?</p>
<p>In Angular 2, every component has its own injector. These 'injectors' form a tree that mirrors the tree of the components themselves. This means that when you ask for a service in a component, the Angular DI system tries to find a provider for that service first in the injector of that component, and then in the injector for the parent component and continues upward throughout the component tree.</p> <p>The last piece of the puzzle is that every component registers itself in its own injector. Therefore, in your example, when you ask for an instance of MyWizard, the DI system looks for a provider in the MyWizardStep component's injector and doesn't find it, then looks up to MyWizardStep's parent (which is MyWizard) and asks that injector for an instance of the MyWizard class. Since each component registers itself in its own injector, MyWizard is available as an injectable class.</p> <p>See <a href="https://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#find-parent" rel="nofollow" title="See the Angular Guide">the Angular 2 advanced guide on dependency injection</a></p>
Sentinel not working properly <pre><code>def load(): global name global count global shares global pp global sp global commission name=input("Enter stock name OR -999 to Quit: ") count =0 while name != '-999': count=count+1 shares=int(input("Enter number of shares: ")) pp=float(input("Enter purchase price: ")) sp=float(input("Enter selling price: ")) commission=float(input("Enter commission: ")) calc() display() name=input("\nEnter stock name OR -999 to Quit: ") def calc(): global amount_paid global amount_sold global profit_loss global commission_paid_sale global commission_paid_purchase amount_paid=shares*pp commission_paid_purchase=amount_paid*commission amount_sold=shares*sp commission_paid_sale=amount_sold*commission profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase) def display(): print("\nStock Name:", name) print("Amount paid for the stock: $", format(amount_paid, '10,.2f')) print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f')) print("Amount the stock sold for: $", format(amount_sold, '10,.2f')) print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f')) print("Profit (or loss if negative): $", format(profit_loss, '10,.2f')) def main(): load() calc() display() main() </code></pre> <p>Sentinel "works" in the sense that it ends the program, but not without outputting the previous stock's data (that is erroneous). I would like the sentinel to immediately stop the program and kick to ">>>" after entering '-999'. Here is what the output looks like:</p> <pre><code>============= RESTART: C:\Users\ElsaTime\Desktop\answer2.py ============= Enter stock name OR -999 to Quit: M$FT Enter number of shares: 1000 Enter purchase price: 15 Enter selling price: 150 Enter commission: 0.03 Stock Name: M$FT Amount paid for the stock: $ 15,000.00 Commission paid on the purchase: $ 450.00 Amount the stock sold for: $ 150,000.00 Commission paid on the sale: $ 4,500.00 Profit (or loss if negative): $ 130,050.00 Enter stock name OR -999 to Quit: -999 Stock Name: -999 Amount paid for the stock: $ 15,000.00 Commission paid on the purchase: $ 450.00 Amount the stock sold for: $ 150,000.00 Commission paid on the sale: $ 4,500.00 Profit (or loss if negative): $ 130,050.00 &gt;&gt;&gt; </code></pre>
<p>Remove <code>calc()</code> and <code>display()</code> from <code>main()</code>. You're already doing those things in <code>load()</code>.</p>
how to use retrofit 2 to send file and other params together <p>I am looking for an example how could I send file and other params together to server.</p> <p>I have to send server JSON which </p> <pre><code>{ "title": "title", "file": "uploaded file instance", "location": { "lat": 48.8583, "lng": 2.29232, "place": "Eiffel Tower" } } </code></pre> <p>How could I create Retrofit to handle this case?</p> <p>If file is a string I know how to handle this. If file is File object I have no idea how to do this.</p>
<p>Use <code>gson</code> and create a model class for the location.</p> <p>Add the following dependencies to your <code>build.gradle</code>.</p> <pre><code>compile 'com.squareup.retrofit2:converter-gson:2.0.0' compile 'com.google.code.gson:gson:2.5' </code></pre> <p>Create a model to represent the location.</p> <pre><code>public class Location { double lat; double lng; String location; public Location(double lat, double lon, String place) { this.lat = lat; this.lon = long; this.place = place; } } </code></pre> <p>If the variable names for the payload fields don't match the actual required name for the endpoint you will need to add the annotation <code>@SerializedName([expected name])</code></p> <p>ex:</p> <pre><code>import com.google.gson.annotations.SerializedName; public class Location { @SerializedName("lat") double latitude; @SerializedName("lng") double longitude; @SerializedName("place") String location; public Location(double lat, double lon, String place) { latitude = lat; longitude = long; location = place; } } </code></pre> <p>Define the api interface.</p> <pre><code>public interface Api { @POST("upload/") @Multipart Call&lt;ResponseBody&gt; uploadFile(@Part("title") RequestBody title, @Part MultipartBody.Part imageFile, @Part("location") Location location ); } </code></pre> <p>Create a <code>Retrofit</code> instance and call the api.</p> <pre><code>File file; // create retrofit instance Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://baseurl.com/api/") .addConverterFactory(GsonConverterFactory.create()) .build(); // create api instance Api api = retrofit.create(Api.class); // create call object Call&lt;ResponseBody&gt; uploadFileCall = api.uploadFile( RequestBody.create(MediaType.parse("text/plain"), "title"), MultipartBody.Part.createFormData( "file", file.getName(), RequestBody.create(MediaType.parse("image"), file)), new Location(48.8583, 2.29232, "Eiffel Tower")); // sync call try { ResponseBody responseBody = uploadFileCall.execute().body(); } catch (IOException e) { e.printStackTrace(); } // async call uploadFileCall.enqueue(new Callback&lt;ResponseBody&gt;() { @Override public void onResponse(Call&lt;ResponseBody&gt; call, Response&lt;ResponseBody&gt; response) { if (response.isSuccessful()) { // TODO } } @Override public void onFailure(Call&lt;ResponseBody&gt; call, Throwable t) { // TODO } }); </code></pre> <p>You will need to change the <code>MediaType.parse()</code> call if you are not using an image file.</p> <p>You can similarly create a custom response type object and replace <code>ResponseBody</code> with it to receive a deserialized result object.</p> <p>Let me know if this works. I didn't have a chance to test in your exact scenario obviously but I'm fairly confident this should work. The only part I'm not 100% on is whether <code>@Part("location") Location location</code> should be <code>@Body("location") Location location</code></p>
How can i split a string based on word boundary in R? <p>How can i split a string based on space/word boundary in R? </p> <pre><code>t = "ID=gene:Bra032485;biotype=protein_coding;description=AT5G40170 (E%3D6e-176) AtRLP54 | AtRLP54 (Receptor Like Protein 54)%3B kinase/ protein binding ;gene_id=Bra032485;logic_name=glean;version=1" </code></pre> <p>I have tried this but it did not worked</p> <pre><code>sub("([A-Za-z1-9]+)+[[:space:]]","\\1",t) </code></pre> <p>The output i want is</p> <pre><code>ID=gene:Bra032485;biotype=protein_coding;description=AT5G40170 </code></pre>
<pre><code>&gt; strsplit(t, " ")[[1]][1] [1] "ID=gene:Bra032485;biotype=protein_coding;description=AT5G40170" </code></pre>
Error CS1501: No overload for method `PopulateWithData' takes `2' arguments <p>HI Apologies in advance for a for asking this question, I'm only learning c# and i can't get my head around the arguments passed into the method.</p> <p>I keep getting an error in xamarin studio on one of the prebuilt apps.</p> <p><a href="https://i.stack.imgur.com/fW38W.png" rel="nofollow">Error CS1501</a></p> <p>has two arguments not been passed into the method or am i missing something? <a href="https://i.stack.imgur.com/f1Fkh.png" rel="nofollow">The method</a> Again apologies i would really appreciate anyone to point me in the right direction, thanks in advance.</p> <p>k</p>
<p>Generally, when dealing with methods, functions, subroutines etc, you have to match the arguments you pass when calling them.</p> <p>For instance, if you have (or declared) a function like this:</p> <pre><code>void myFunction(int a, int b) { ... } </code></pre> <p>You have to call it passing 2 ints (no less, no more)</p> <pre><code>myFunction(10, 20); </code></pre> <p>There are some languages that accepts overload of methods, in these cases you could have something like this:</p> <pre><code>void myFunction(int a) { ... } void myFunction(int a, int b) { ... } void myFunction(int a, int b, int c) { ... } </code></pre> <p>This way you´d have 3 possible ways to call your function:</p> <pre><code>myFunction(10); myFunction(10, 20); myFunction(10, 20, 30); </code></pre>
How can I get text-decoration: underline to ignore descenders <p>I've seen it around, most recently here: <a href="http://pitchfork.com/news/67863-amazon-launches-new-streaming-service-undercutting-spotify-and-apple-music/" rel="nofollow">http://pitchfork.com/news/67863-amazon-launches-new-streaming-service-undercutting-spotify-and-apple-music/</a></p> <p>Notice the underline skips the "p" and "y" descenders. If I go to another site that's using the same font and throw text-decoration: underline in, it doesn't apply the same underline styling. Any ideas?</p>
<p>If you inspect that element in the site, you will find out that it isn't really a text decoration but a line simulation of it, because text decoration is inactive. </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.contents a { color: #1A1A1A; background: linear-gradient(#fff,#fff),linear-gradient(#fff,#fff),linear-gradient(#FF3530,#FF3530); background-size: .05em 1px,.05em 1px,1px 1px; background-repeat: no-repeat,no-repeat,repeat-x; text-shadow: .03em 0 #fff,-.03em 0 #fff,0 .03em #fff,0 -.03em #fff,.06em 0 #fff,-.06em 0 #fff,.09em 0 #fff,-.09em 0 #fff,.12em 0 #fff,-.12em 0 #fff,.15em 0 #fff,-.15em 0 #fff; background-position: 0 95%,100% 95%,0 95%; } a { text-decoration: none; background-color: transparent; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="contents"&gt;"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod &lt;a&gt;tempor&lt;/a&gt; incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in &lt;a&gt;reprehenderit&lt;/a&gt; in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."&lt;/div&gt;</code></pre> </div> </div> </p>
JDBC Instrumentation and ORA-01000: maximum open cursors exceeded <p>I am trying to better instrument which web applications make use of Oracle (11g) connections in our Tomcat JDBC connection pool when a connection is <strong>created</strong> and <strong>closed</strong>; this way, we can see what applications are using connections by monitoring the <code>V$SESSION</code> table. This is working, but since adding this "instrumentation" I am seeing <code>ORA-01000: maximum open cursors exceeded</code> errors being logged and noticing some connections being dropped out of the pool during load testing (which is probably fine as I have <code>testOnBorrow</code> enabled, so I'm assuming the connection is being flagged as invalid and dropped from the pool).</p> <p>I have spent the better part of the week scouring the internet for possible answers. Here is what I have tried (all result in the open cursors error after a period of time)...</p> <p>The below methods are all called the same way...</p> <h2>On Create</h2> <ol> <li>We obtain a connection from the pool</li> <li>We call a method that executes the below code, passing in the context name of the web application</li> </ol> <h2>On Close</h2> <ol> <li>We have the connection being closed (returned to the pool)</li> <li>Before we issue <code>close()</code> on the connection, we call a method that executes the code below, passing in "Idle" as the name to store in <code>V$SESSION</code></li> </ol> <h1>Method 1:</h1> <pre><code>CallableStatement cs = connection.prepareCall("{call DBMS_APPLICATION_INFO.SET_MODULE(?,?)}"); try { cs.setString(1, appId); cs.setNull(2, Types.VARCHAR); cs.execute(); log.trace("&gt;&gt;&gt; Executed Oracle DBMS_APPLICATION_INFO.SET_MODULE with module_name of '" + appId + "'"); } catch (SQLException sqle) { log.error("Error trying to call DBMS_APPLICATION_INFO.SET_MODULE('" + appId + "')", sqle); } finally { cs.close(); } </code></pre> <h1>Method 2:</h1> <p>I upgraded to the 12c OJDBC driver (ojdbc7) and used the native <code>setClientInfo</code> method on the connection...</p> <pre><code>// requires ojdbc7.jar and oraclepki.jar to work (setEndToEndMetrics is deprecated in ojdbc7) connection.setClientInfo("OCSID.CLIENTID", appId); </code></pre> <h1>Method 3:</h1> <p>I'm currently using this method.</p> <pre><code>String[] app_instrumentation = new String[OracleConnection.END_TO_END_STATE_INDEX_MAX]; app_instrumentation[OracleConnection.END_TO_END_CLIENTID_INDEX] = appId; connection.unwrap(OracleConnection.class).setEndToEndMetrics(app_instrumentation, (short)0); // in order for this to be sent, a query needs to be sent to the database - this works fine when a // connection is created, but when it is closed, we need a little something to get the change into the db // try using isValid() connection.isValid(1); </code></pre> <h1>Method 4:</h1> <pre><code>String[] app_instrumentation = new String[OracleConnection.END_TO_END_STATE_INDEX_MAX]; app_instrumentation[OracleConnection.END_TO_END_CLIENTID_INDEX] = appId; connection.unwrap(OracleConnection.class).setEndToEndMetrics(app_instrumentation, (short)0); // in order for this to be sent, a query needs to be sent to the database - this works fine when a // connection is created, but when it is closed, we need a little something to get the change into the db if ("Idle".equalsIgnoreCase(appId)) { Statement stmt = null; ResultSet rs = null; try { stmt = connection.createStatement(); rs = stmt.executeQuery("select 1 from dual"); } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } } </code></pre> <p>When I query for open cursors, I notice the following SQL being returned on the account being used in the pool (for each connection in the pool)...</p> <pre><code>select NULL NAME, -1 MAX_LEN, NULL DEFAULT_VALUE, NULL DESCR </code></pre> <p>This does not explicitly exist anywhere in our code, so I can only assume it is coming from the pool when running the validation query (<code>select 1 from dual</code>) or from the <code>setEndToEndMetrics</code> method (or from the <code>DBMS_APPLICATION_INFO.SET_MODULE</code> proc, or from the <code>isValid()</code> call). I tried to be explicit in creating and closing <code>Statement</code> (<code>CallableStatement</code>) and <code>ResultSet</code> objects in methods 1 and 4, but they made no difference.</p> <p>I don't want to increase the number of allowed cursors, as this will only delay the inevitable (and we have never had this issue until I added in the "instrumentation").</p> <p>I've read through the excellent post <a href="http://stackoverflow.com/questions/12192592/java-sql-sqlexception-ora-01000-maximum-open-cursors-exceeded">here</a> (<em>java.sql.SQLException: - ORA-01000: maximum open cursors exceeded</em>), but I must still be missing something. Any help would be greatly appreciated.</p>
<p>So Mr. Poole's statement: "<em>that query looks like it's getting fake metadata</em>" set off a bell in my head. </p> <p>I started to wonder if it was some unknown remnant of the validation query being run on the <code>testOnBorrow</code> attribute of the pool's datasource (even though the validation query is defined as <code>select 1 from dual</code>). I removed this from the configuration, but it had no effect.</p> <p>I then tried removing the code that sets the client info in <code>V$SESSION</code> (Method 3 above); Oracle continued to show that unusual query and after only a few minutes, the session would hit the maximum open cursors limit.</p> <p>I then found that there was a "logging" method in our DAO class that logged some metadata from the connection object (values for settings like current auto commit, current transaction isolation level, JDBC driver version, etc.). Within this logging was the use of the <code>getClientInfoProperties()</code> method on the <code>DatabaseMetaData</code> object. When I looked at the JavaDocs for this method, it became crystal clear where that unusual query was coming from; check it out...</p> <pre><code>ResultSet java.sql.DatabaseMetaData.getClientInfoProperties() throws SQLException Retrieves a list of the client info properties that the driver supports. The result set contains the following columns 1. NAME String=&gt; The name of the client info property 2. MAX_LEN int=&gt; The maximum length of the value for the property 3. DEFAULT_VALUE String=&gt; The default value of the property 4. DESCRIPTION String=&gt; A description of the property. This will typically contain information as to where this property is stored in the database. The ResultSet is sorted by the NAME column Returns: A ResultSet object; each row is a supported client info property </code></pre> <p>You can clearly see that unusual query (<code>select NULL NAME, -1 MAX_LEN, NULL DEFAULT_VALUE, NULL DESCR</code>) matches what the JavaDocs say about the <code>DatabaseMetaData.getClientInfoProperties()</code> method. Wow, right!?</p> <p>This is the code that was performing the function. As best as I can tell, it looks correct from a "closing of the <code>ResultSet</code>" standpoint - not sure what was happening that would keep the <code>ResultSet</code> open - it clearly being closed in the <code>finally</code> block.</p> <pre><code>log.debug("&gt;&gt;&gt;&gt;&gt;&gt; DatabaseMetaData Client Info Properties (jdbc driver)..."); ResultSet rsDmd = null; try { boolean hasResults = false; rsDmd = dmd.getClientInfoProperties(); while (rsDmd.next()) { hasResults = true; log.debug("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; NAME = '" + rsDmd.getString("NAME") + "'; DEFAULT_VALUE = '" + rsDmd.getString("DEFAULT_VALUE") + "'; DESCRIPTION = '" + rsDmd.getString("DESCRIPTION") + "'"); } if (!hasResults) { log.debug("&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; DatabaseMetaData Client Info Properties was empty (nothing returned by jdbc driver)"); } } catch (SQLException sqleDmd) { log.warn("DatabaseMetaData Client Info Properties (jdbc driver) not supported or no access to system tables under current id"); } finally { if (rsDmd != null) { rsDmd.close(); } } </code></pre> <p>Looking at the logs, when an Oracle connection was used, the <code>&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; DatabaseMetaData Client Info Properties was empty (nothing returned by jdbc driver)</code> line was logged, so an exception wasn't being thrown, but no record was being returned either. I can only assume that the ojdbc6 (11.2.0.x.x) driver doesn't properly support the <code>getClientInfoProperties()</code> method - it is weird (I think) that an exception wasn't being thrown, as the query itself is missing the <code>FROM</code> keyword (it won't run when executed in TOAD for example). And no matter what, the <code>ResultSet</code> should have at least been getting closed (the connection itself would still be in use though - maybe this causes Oracle to not release the cursors even though the <code>ResultSet</code> was closed).</p> <p>So all of the work I was doing was in a branch (I mentioned in a comment to my original question that I was working in trunk - my mistake - I was in a branch that was already created thinking it was based on trunk code and not modified - I failed to do my due diligence here), so I checked the SVN commit history and found that this additional logging functionality was added by a fellow teammate a couple of weeks ago (fortunately it hasn't been promoted to trunk or to higher environments - note this code works fine against our Sybase database). My update from the SVN branch brought in his code, but I never really paid attention to what got updated (my bad). I spoke with him about what this code was doing against Oracle, and we agreed to remove the code from the logging method. We also put in place a check to only log the connection metadata when in our development environment (he said he added this code to help troubleshoot some driver version and auto commit questions he had). Once this was done, I was able to run my load tests without any open cursor issues (success!!!).</p> <p>Anyway, I wanted to answer this question because when I searched for <code>select NULL NAME, -1 MAX_LEN, NULL DEFAULT_VALUE, NULL DESCR</code> and <code>ORA-01000 open cursors</code> no credible hits were returned (the majority of the hits returned were to make sure you are closing your connection resources, i.e., <code>ResultSet</code>s, <code>Statement</code>s, etc.). I think this shows it was the database metadata query through JDBC against Oracle was the culprit of the <code>ORA-01000</code> error. I hope this is useful to others. Thanks.</p>
Get local network hostnames in iOS <p>I would like to get All device name in entire local network. I just been searching over 2 days and haven't find a solution yet.</p> <p>I can able to get Bonjour services with using NSNetServiceBrowser. What i am trying to do is same as Fing app ( in app store) does. </p> <p>As screenshot below, I would like to get "My iPhone" iPhone name with iOS.</p> <p><a href="https://i.stack.imgur.com/dRhVw.png" rel="nofollow"><img src="https://i.stack.imgur.com/dRhVw.png" alt="Fing can fetch all device name entire local-network successfully"></a></p> <p>Regards</p> <p>Onder</p>
<p>Seems like <code>NEHotspotHelper</code> is what you're looking for. Specifically a <code>class func supportedNetworkInterfaces() -&gt; [Any]</code> method.</p> <p>In order to make it work, you'll need to accomplish some additional steps. Please, check <a href="http://stackoverflow.com/a/39189063/1090309">this question</a> to get more information.</p> <p>Also don't forget to add <strong>NetworkExtension.framework</strong> to your target.</p>
connecting to a remote server and downloading and extracting binary tar file using python <p>I would like to connect to a remote server, download and extract binary tar file into a specific directory on that host. I am using python 2.6.8</p> <ol> <li>What would be a simple way to ssh to that server?</li> <li><p>I see the below errors on my script to download the tar file and extract it</p> <p>Traceback (most recent call last): File "./wgetscript.py", line 16, in tar = tarfile.open(file_tmp) File "/usr/lib64/python2.6/tarfile.py", line 1653, in open return func(name, "r", fileobj, **kwargs) File "/usr/lib64/python2.6/tarfile.py", line 1715, in gzopen fileobj = bltn_open(name, mode + "b") TypeError: coercing to Unicode: need string or buffer, tuple found</p></li> </ol> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>#!/usr/bin/env python import os import tarfile import urllib url = 'http://**************/Lintel/Mongodb/mongodb-linux-x86_64-enterprise-suse12-3.2.6.tgz' fullfilename = os.path.join('/tmp/demo1','file.tgz') file_tmp = urllib.urlretrieve(url,fullfilename) print file_tmp base_name = os.path.basename(url) print base_name file_name, file_extension = os.path.splitext(base_name) print file_name, file_extension tar = tarfile.open(file_tmp) nameoffile = os.path.join('/tmp/demo1','file') tar.extractall(file_name,nameoffile) tar.close()</code></pre> </div> </div> </p>
<p>There are 2 errors here:</p> <ul> <li><code>urllib.urlretrieve</code> (or <code>urllib.requests.urlretrieve</code> in Python 3) returns a <code>tuple</code>: filename, httprequest. You have to unpack the result in 2 values (or in the original <code>fullfilename</code>)</li> <li>download is OK but the <code>tarfile</code> module doesn't work the way to think it works: <code>tar.extractall</code> takes 2 arguments: path of the .tar/.tgz file and optional <code>list</code> of members (that you can get with <code>tar.getmembers()</code> in your case). For this example, I propose that we drop that filter and extract all the contents in the temp directory.</li> </ul> <p>Fixed code:</p> <pre><code>url = 'http://**************/Lintel/Mongodb/mongodb-linux-x86_64-enterprise-suse12-3.2.6.tgz' temp_dir = '/tmp/demo1' fullfilename = os.path.join(temp_dir,'file.tgz') # urllib.request in Python 3 file_tmp,http_message = urllib.urlretrieve(url,fullfilename) base_name = os.path.basename(url) file_name, file_extension = os.path.splitext(base_name) tar = tarfile.open(file_tmp) #print(tar.getmembers()[0:5]) # would print 5 first members of the archive tar.extractall(os.path.join(temp_dir,file_name)) tar.close() </code></pre>
getEventsForDay() formatting issues with datepicker return value <p>I'm trying to use the Calendar API to pull up some events based on datepicker output. The issue that i'm facing with my AppScript is formatting properly the value that i get from the datepicker that will serve as input for the getEventsForDay() function.</p> <pre><code>function testing(){ var z = CalendarApp.getCalendarsByName("X")[0]; var date = new Date('2016-10-12'); var dateformatted =Utilities.formatDate(date), "GMT", "yyyy-MM-dd hh:mm:ss a"); var a = z.getEventsForDay(dateformatted, {search: 'OOO'}); </code></pre> <p>The output of a into this scenario is a empty object - which is expected because this formatting is not working at all. (i've read 1000 posts that this should work).</p> <p>For context as well, i have one working example with today's date, which it works fine becase the input is a new Date(). Here you go:</p> <pre><code> var datetoday = new Date(); var b = z.getEventsForDay(datetoday, {search: 'OOO'}); </code></pre> <p>Any ideas on what i'm missing here?</p> <p>Thanks in advance.</p>
<p>Since <code>new Date()</code> returns the Date object in UTC and not the local timezone, you may be querying the wrong day and hence the empty object if the other day does not have any events.</p> <p>You can covert the date to the current timezone like</p> <pre><code>date.setTime(date.getTime() + date.getTimezoneOffset()*60*1000) </code></pre> <p>This should return the date in the local timezone and you will get the events for the correct day.</p> <p>Hope it helps</p>
List of NetSuite GL Posting Transactions and their recordtypes <p>I'm wondering if anyone knows a way to obtain a list of NetSuite GL Posting transactions and their recordtypes. I've created a savedsearch in my account against transactions and set the posting field to true, then grouped by recordtype. This gives me a list of transactions that I've used (already created) that are GL posting. This is not what I'm looking for.</p> <p>I need to know all GL Posting transactions and I've been unable to find them in the usergroup or stackoverflow.</p> <p>FYI, this is my first question for what it's worth...</p>
<p>I would recommend to go through help topic <code>Understanding General Ledger Impact of Transactions</code> or SuiteAnswer Id 7821</p>
Put a text on top of a button - android <p>i have a regular android button </p> <pre><code>&lt;Button android:id="@+id/btn_0" style="@style/def_button_numb" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1" android:text="0" /&gt; </code></pre> <p>First: I need to put some text on top of this button, just like keyboards does.</p> <p>And second: On longpress needs to show a popup (also like keyboards), to let user choose two more options of buttons.</p> <p>is there an ease way to do so?</p>
<p>you can simply add this code</p> <p>android:text="SEND DATA TO FRAGMENT B"</p>
"No route found" error with Asana Connect <p>As per <a href="https://asana.com/developers/documentation/getting-started/auth#quick-reference" rel="nofollow">this</a>, I'm trying to use the code received from the authorization endpoint to exchange for a token, using the Authorization Code Grant flow. I first issue this call:</p> <p><a href="https://app.asana.com/-/oauth_authorize?response_type=code&amp;client_id=123468022031234&amp;redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&amp;state=foo" rel="nofollow">https://app.asana.com/-/oauth_authorize?response_type=code&amp;client_id=123468022031234&amp;redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&amp;state=foo</a></p> <p>(I admit I don't know how the 'state' param should be used - the documentation doesn't clarify this, and it's required; also, my app is not web-based so the value for the redirect URL is auto-generated on the Developer App Management page for my app)</p> <p>That gives me this code (slightly obfuscated): 0/12341234fd6ccf6d168420f7f8600c93</p> <p>Which I then use for this call:</p> <p><a href="https://app.asana.com/-/oauth_token?grant_type=authorization_code&amp;client_id=123468022031234&amp;client_secret=1234123442d5048f64ac39ca857ec57a&amp;redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&amp;code=0%2F12341234fd6ccf6d168420f7f8600c93" rel="nofollow">https://app.asana.com/-/oauth_token?grant_type=authorization_code&amp;client_id=123468022031234&amp;client_secret=1234123442d5048f64ac39ca857ec57a&amp;redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&amp;code=0%2F12341234fd6ccf6d168420f7f8600c93</a></p> <p>Which unfortunately returns "No route found" instead of the token I need. What am I doing wrong?</p>
<p>It has to be a POST. I was using a GET call.</p>
Timing blocks of code - Python <p>I'm trying to measure the time it takes to run a block of instructions in Python, but I don't want to write things like:</p> <pre><code>start = time.clock() ... &lt;lines of code&gt; ... time_elapsed = time.clock() - start </code></pre> <p>Instead, I want to know if there is a way I can send the block of instructions as a parameter to a function that returns the elapsed time, like</p> <pre><code>time_elapsed = time_it_takes(&lt;lines of code&gt;) </code></pre> <p>The implementation of this method could be something like</p> <pre><code>def time_it_takes(&lt;lines of code&gt;): start = time.clock() result = &lt;lines of code&gt; return (result, time.clock() - start) </code></pre> <p>Does anybody know if there is some way I can do this? Thanks in advanced.</p>
<p>This would be a good use of a decorator. You could write a decorator that does that like this</p> <pre><code>import time def timer(func): def wrapper(*args, **kwargs): start = time.time() func(*args, **kwargs) print('The function ran for', time.time() - start) return wrapper @timer def just_sleep(): time.sleep(5) just_sleep() </code></pre> <p>Output</p> <pre><code>The function ran for 5.0050904750823975 </code></pre> <p>and then you can decorate any function you want to time with <code>@timer</code> and you can also do some other fancy things inside the decorator. Like if the function ran for more than 15 seconds do something...else do another thing</p> <p><strong>Note: This is not the most accurate way to measure execution time of a function in python</strong></p>
How do I set up a Kubernetes Ingress rule with a regex path? <p>I'd like to use regex in the path of an Ingress rule, but I haven't been able to get it to work. <a href="https://github.com/nginxinc/kubernetes-ingress/blob/master/examples/complete-example/cafe-ingress.yaml" rel="nofollow">For example</a>:</p> <pre><code>apiVersion: extensions/v1beta1 kind: Ingress metadata: name: cafe-ingress spec: tls: - hosts: - cafe.example.com secretName: cafe-secret rules: - host: cafe.example.com http: paths: - path: /tea backend: serviceName: tea-svc servicePort: 80 - path: /coffee backend: serviceName: coffee-svc servicePort: 80 </code></pre> <p>I tried putting <code>/t[a-z]a</code> for the first path, but then any path I tried that should match that regex took me to the default backend instead of the service I expected.</p> <p>Note: I'm using an nginx ingress controller, which should be able to support regex.</p>
<p>I don't think there is an option to use regexp in Ingress objects. Ingress is designed to work with multiple IngressController implementations, both provided by cloud services or by self-hosted ingress like nginx one from kubernetes/contrib (which I use on my setup). Thus ingress should cover features that are commonly available on most common implementations, while specific, non-standard behaviours can be set using annotations (like ie. many nginx ingress features).</p>
Count the number of times a player plays a game in a different difficulty level <p>I have a xml and xslt files like below. And Im showing in a table the gamename and the player name. But now Im trying to do one thing and Im not see how.</p> <p>I want to show how many times a player played a game in a novice, easy, medium, hard, legend level and the total. For example I want each row like this:</p> <pre><code>GameName | Player Name | NoviceLevels | EasyLevels | MediumLevels | HardLevels | Total </code></pre> <p>I already try a lot of alternatives but Im not having success put this working like this. Do you see how to achieve this?</p> <pre><code>&lt;games&gt; &lt;game&gt; &lt;gamename&gt;GameTitle 1&lt;/gamename&gt; &lt;players&gt; &lt;player&gt; &lt;playername&gt;John&lt;/playername&gt; &lt;difficultlevel&gt;Novice&lt;/difficultlevel&gt; &lt;duration&gt;130&lt;/duration&gt; &lt;/player&gt; &lt;player&gt; &lt;playername&gt;John&lt;/playername&gt; &lt;difficultlevel&gt;Easy&lt;/difficultlevel&gt; &lt;duration&gt;210&lt;/duration&gt; &lt;/player&gt; &lt;player&gt; &lt;playername&gt;Zed&lt;/playername&gt; &lt;difficultlevel&gt;Medium&lt;/difficultlevel&gt; &lt;duration&gt;300&lt;/duration&gt; &lt;/player&gt; &lt;/players&gt; &lt;/game&gt; &lt;/games&gt; </code></pre> <p>And this xslt:</p> <pre><code>&lt;table&gt; &lt;xsl:for-each select="//games"&gt; &lt;tr&gt; &lt;th&gt;GameName&lt;/th&gt; &lt;th&gt;Player&lt;/th&gt; &lt;th&gt;Beginner&lt;/th&gt; &lt;th&gt;Beginner&lt;/th&gt; &lt;th&gt;Medium&lt;/th&gt; &lt;th&gt;Hard&lt;/th&gt; &lt;th&gt;Legend&lt;/th&gt; &lt;th&gt;Total&lt;/th&gt; &lt;/tr&gt; &lt;xsl:for-each select="game"&gt; &lt;tr&gt; &lt;td&gt;&lt;xsl:value-of select="gamename"/&gt;&lt;/td&gt; &lt;td&gt;&lt;xsl:value-of select="players/player/playername"/&gt;&lt;/td&gt; ....??? &lt;/tr&gt; &lt;/xsl:for-each&gt; &lt;/table&gt; </code></pre> <p>What I have is here: <a href="http://xsltransform.net/pPJ8LVb/1" rel="nofollow">http://xsltransform.net/pPJ8LVb/1</a></p>
<p>Here is an adaption of what you tried, assuming an XSLT 2.0 processor as it uses <code>for-each-group</code>:</p> <pre><code>&lt;html xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xsl:version="2.0"&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;GameName&lt;/th&gt; &lt;th&gt;Player&lt;/th&gt; &lt;th&gt;NoviceLevels&lt;/th&gt; &lt;th&gt;EasyLevels&lt;/th&gt; &lt;th&gt;Medium&lt;/th&gt; &lt;th&gt;Hard&lt;/th&gt; &lt;th&gt;Legend&lt;/th&gt; &lt;th&gt;Total&lt;/th&gt; &lt;/tr&gt; &lt;xsl:for-each select="games/game"&gt; &lt;xsl:for-each-group select="players/player" group-by="playername"&gt; &lt;tr&gt; &lt;td&gt;&lt;xsl:value-of select="ancestor::game/gamename"/&gt;&lt;/td&gt; &lt;td&gt;&lt;xsl:value-of select="playername"/&gt;&lt;/td&gt; &lt;td&gt;&lt;xsl:value-of select="current-group()[difficultlevel = 'Novice']/duration"/&gt;&lt;/td&gt; &lt;td&gt;...&lt;/td&gt; &lt;td&gt;...&lt;/td&gt; &lt;td&gt;...&lt;/td&gt; &lt;td&gt;...&lt;/td&gt; &lt;td&gt;&lt;xsl:value-of select="sum(current-group()/duration)"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/xsl:for-each-group&gt; &lt;/xsl:for-each&gt; &lt;/table&gt; &lt;/html&gt; </code></pre> <p>I haven't spelled out the code for all table cells respectively levels, it should be clear how to do that I hope from the one level spelled out.</p> <p>I am also not sure whether the approach shown suffices, it assumes for any player there is only one entry for each difficulty level per game, if not, you would need to use a nested grouping by <code>difficultylevel</code>.</p>
How many records BizTalk EDI Batching Service can handle? <p>I have a BizTalk application deployed to assembly X12 834 files. it works fine to assembly a valid EDI file with about 100K records, the final file generated is about 70-80M. </p> <p>But when the record count reached to about 1.2M, the performance of batching service is significantly dropped, it takes forever to complete the batch. </p> <p>I tried to config the batching to release a file for about every 200K interchanges, it can generate several files but the performance also changed to unacceptable after about 500K records feeds in it. </p> <p>I even tried to run the bts_CleanupMsgbox script to clear out everything in MsgBox before start the batching.</p> <p>So the question is: Can BizTalk batching service handle this amount of data? The performance issue is simply cause by the design of batching service (store as XML/save state to database in every persistence points in orchestration), or I can archive to assemble file with this volume of data by some performance tuning.</p>
<p>I don't think the built-in batching is appropriate for such amounts of data. </p> <p>Is there any reason why you need such big batches? I do quite a lot of EDI, but have never encountered such a requirements.</p> <p>I don't know whether this is applicable for you, but you can actually bypass the entire built-in EDI batching orchestration by mapping to an X12InterchangeXml schema. An added advantage would be that you can also control the order of the messages in the interchange as well. There are some tricks to it, but in general this might be a lot more performant.</p>
OSError: .pynative/... : file too short <p>When I try to apply OCRopus (a python-based OCR tool) to a TIFF image, I get the following python error:</p> <pre><code> Traceback (most recent call last): File "/usr/local/bin/ocropus-nlbin", line 10, in &lt;module&gt; import ocrolib File "/usr/local/lib/python2.7/dist-packages/ocrolib/__init__.py", line 12, in &lt;module&gt; from common import * File "/usr/local/lib/python2.7/dist-packages/ocrolib/common.py", line 18, in &lt;module&gt; import lstm File "/usr/local/lib/python2.7/dist-packages/ocrolib/lstm.py", line 32, in &lt;module&gt; import nutils File "/usr/local/lib/python2.7/dist-packages/ocrolib/nutils.py", line 25, in &lt;module&gt; lstm_native = compile_and_load(lstm_utils) File "/usr/local/lib/python2.7/dist-packages/ocrolib/native.py", line 68, in compile_and_load return ctypes.CDLL(path) File "/usr/lib/python2.7/ctypes/__init__.py", line 365, in __init__ self._handle = _dlopen(self._name, mode) OSError: .pynative/cccd32009099f8dade0fe6cd205bf188.so: file too short Traceback (most recent call last): File "/usr/local/bin/ocropus-gpageseg", line 22, in &lt;module&gt; import ocrolib File "/usr/local/lib/python2.7/dist-packages/ocrolib/__init__.py", line 12, in &lt;module&gt; from common import * File "/usr/local/lib/python2.7/dist-packages/ocrolib/common.py", line 18, in &lt;module&gt; import lstm File "/usr/local/lib/python2.7/dist-packages/ocrolib/lstm.py", line 32, in &lt;module&gt; import nutils File "/usr/local/lib/python2.7/dist-packages/ocrolib/nutils.py", line 25, in &lt;module&gt; lstm_native = compile_and_load(lstm_utils) File "/usr/local/lib/python2.7/dist-packages/ocrolib/native.py", line 68, in compile_and_load return ctypes.CDLL(path) File "/usr/lib/python2.7/ctypes/__init__.py", line 365, in __init__ self._handle = _dlopen(self._name, mode) OSError: .pynative/cccd32009099f8dade0fe6cd205bf188.so: file too short Traceback (most recent call last): File "/usr/local/bin/ocropus-rpred", line 7, in &lt;module&gt; import ocrolib File "/usr/local/lib/python2.7/dist-packages/ocrolib/__init__.py", line 12, in &lt;module&gt; from common import * File "/usr/local/lib/python2.7/dist-packages/ocrolib/common.py", line 18, in &lt;module&gt; import lstm File "/usr/local/lib/python2.7/dist-packages/ocrolib/lstm.py", line 32, in &lt;module&gt; import nutils File "/usr/local/lib/python2.7/dist-packages/ocrolib/nutils.py", line 25, in &lt;module&gt; lstm_native = compile_and_load(lstm_utils) File "/usr/local/lib/python2.7/dist-packages/ocrolib/native.py", line 68, in compile_and_load return ctypes.CDLL(path) File "/usr/lib/python2.7/ctypes/__init__.py", line 365, in __init__ self._handle = _dlopen(self._name, mode) OSError: .pynative/cccd32009099f8dade0fe6cd205bf188.so: file too short Traceback (most recent call last): File "/usr/local/bin/ocropus-hocr", line 8, in &lt;module&gt; import ocrolib File "/usr/local/lib/python2.7/dist-packages/ocrolib/__init__.py", line 12, in &lt;module&gt; from common import * File "/usr/local/lib/python2.7/dist-packages/ocrolib/common.py", line 18, in &lt;module&gt; import lstm File "/usr/local/lib/python2.7/dist-packages/ocrolib/lstm.py", line 32, in &lt;module&gt; import nutils File "/usr/local/lib/python2.7/dist-packages/ocrolib/nutils.py", line 25, in &lt;module&gt; lstm_native = compile_and_load(lstm_utils) File "/usr/local/lib/python2.7/dist-packages/ocrolib/native.py", line 68, in compile_and_load return ctypes.CDLL(path) File "/usr/lib/python2.7/ctypes/__init__.py", line 365, in __init__ self._handle = _dlopen(self._name, mode) OSError: .pynative/cccd32009099f8dade0fe6cd205bf188.so: file too short </code></pre> <p>Since this is as python issue, I haven't tagged OCROpus, should I tag it as well? Could it be an Python installation matter? If so, how can I solve it?</p>
<p>Problem solved. I saw other people having trouble (on diverse matters) with: </p> <blockquote> <p>OSError:<strong>[X]</strong>... : file too short</p> </blockquote> <p>My suggestion is: whatever you are doing, check for hidden directories named [X] in the current directory and delete them.</p>
Eloquent, combine row columns in where statement <p>let's say I've got a database containing some films, with the date that they have first been released in a column and the number of months for which I should be showing them in the cinemas in another colum. </p> <p>What I would like to do is get all the cinemas that are showing any film. I'm trying to condense this in a single query, something like this</p> <pre><code> Cinemas::whereHas('films', function($q){ $q-&gt;where('date_created', '&gt;=', \Carbon::now()-&gt;subMonths(showing_months))); })-&gt;get(); </code></pre> <p>showing_months is the number of months for which the film is showing. Is there anyway to access that column in a similar why to which i "access" date_created? </p> <p>Thanks</p>
<p>I am not sure it makes sense to add months to a date like you do it, but a calculation based on two columns and a passed parameter could look the following: </p> <pre><code>Cinemas::whereHas('films', function($q){ $q-&gt;whereRaw('date_created &gt;= (? + showing_months)', [Carbon::now()]); })-&gt;get(); </code></pre> <p><strong>Solution for the edited question:</strong></p> <pre><code>Cinemas::whereHas('films', function($q){ $q-&gt;whereRaw('date_created &gt;= DATE_SUB(?, INTERVAL showing_months MONTH)', [Carbon::now()]); })-&gt;get(); </code></pre>
Git rebase one branch on top of another branch <p>In my git repo, I have a <code>Master</code> branch. One of the remote devs created a branch <code>Branch1</code> and had a bunch of commits on it. I branched from <code>Branch1</code>, creating a new branch called <code>Branch2</code> (<code>git checkout -b Branch2 Branch1</code>) such that <code>Branch2</code> head was on the last commit added to <code>Branch1</code>:(Looks like this)</p> <pre><code>Master--- \ Branch1--commit1--commit2 \ Branch2 (my local branch) </code></pre> <p><code>Branch1</code> has had a number of changes. The other dev squashed his commits and then added a few more commits. Meanwhile, ive had a bunch of changes in my branch but havent committed anything yet. Current structure looks like this:</p> <pre><code> Master--- \ Branch1--squashed commit1,2--commit3--commit4 \ Branch2 (my local branch) </code></pre> <p>Now I want have to rebase my changes on top of <code>Branch1</code>. I am supremely confused on how to go about this. I know the 1st step will be to commit my changes using <code>git add .</code> and <code>git commit -m "message"</code>. But do i then push? using <code>git push origin Branch2</code> ? or <code>git push origin Branch2 Branch1</code> ? Help is much needed and GREATLY appreciated, also if I can some how create a backup of my branch, it will be great in case I screw something up</p>
<p>First backup your current <code>Branch2</code>:</p> <pre><code># from Branch2 git checkout -b Branch2_backup </code></pre> <p>Then rebase <code>Branch2</code> on <code>Branch1</code>:</p> <pre><code># from Branch2 git fetch origin # update all tracking branches, including Branch1 git rebase origin/Branch1 # rebase on latest Branch1 </code></pre> <p>After the rebase your branch structure should look like this:</p> <pre><code>master -- \ 1 -- 2 -- 3 -- 4 -- Branch2' </code></pre> <p>In the diagram above, the apostrophe on <code>Branch2</code> indicates that every commit in the rebased <code>Branch2</code> <em>after</em> commit 4 is actually a rewrite.</p> <p>Keep in mind that you have now rewritten the history of <code>Branch2</code> and if the branch is already published you will have to force push it to the remote via</p> <pre><code>git push --force origin Branch2 </code></pre> <p>Force pushing can cause problems for anyone else using <code>Branch2</code> so you should be careful when doing this.</p>
What is the meaning of the object in the python classes <p>what is the meaning of the following command:</p> <pre><code>def run_initial(self) -&gt; object: </code></pre> <p>I don't know why he put <code>object</code> after the arrow. What is the meaning of the object here?</p>
<p>They are type annotations.</p> <p>Type annotations are type hints that were brought in with <a href="https://www.python.org/dev/peps/pep-0484/" rel="nofollow">pep-0484</a>. They were made to allow developers to use third party tools or modules that consume these to give more information to the user about types for example.</p> <p>The more obvious use case imho right now is that the Python visual editor PyCharm (which is afaik the most used pycharm editor after sublime, which is not a complete editor) supports them to give programmers information about types, and for auto complete.</p> <p>See <a href="https://www.jetbrains.com/help/pycharm/2016.1/type-hinting-in-pycharm.html" rel="nofollow">https://www.jetbrains.com/help/pycharm/2016.1/type-hinting-in-pycharm.html</a></p>
Multiple Linear Regression-Interactions Between Transformed Quadratic Variable and Factor Variable <p>I have a multiple linear regression as seen below that contains interaction terms, where some of my terms are factor variables (season, month, holiday, weekday, weathersit)</p> <pre><code>regwithint=lm(casual~season:temp+season:month+year:temp+ month:temp+holiday:temp+weekday:hum+season+ month+holiday+weekday+weathersit+temp+windspeed ,data=training) </code></pre> <p>However, the variables temp and windspeed were transformed to (temp^3) and (windspeed^2). </p> <p>Looking at the interaction terms, I have an interaction between <strong>temp:weekday</strong> where temp is <strong>temp^3</strong> and weekday is a <strong>factor</strong> variable.</p> <p>I know for most cases I should use <strong><em>I(temp^3)</em></strong> but does the fact that it is paired with a factor variable mean I should use <strong>poly(temp,3,raw=T)</strong> instead?</p> <p>Thank You.</p>
<p>First, let's establish that <code>I()</code> works fine with factor variable interactions:</p> <pre><code>data(iris) reg &lt;- lm(Sepal.Length~Species:I(Petal.Length^2), data=iris) summary(reg) </code></pre> <blockquote> <pre><code>Call: lm(formula = Sepal.Length ~ Species:I(Petal.Length^2), data = iris) Residuals: Min 1Q Median 3Q Max -0.87875 -0.22363 -0.00197 0.21664 1.06243 Coefficients: Estimate Std. Error t value Pr(&gt;|t|) (Intercept) 4.245539 0.133172 31.880 &lt; 2e-16 *** Speciessetosa:I(Petal.Length^2) 0.341688 0.062196 5.494 1.7e-07 *** Speciesversicolor:I(Petal.Length^2) 0.092381 0.007413 12.462 &lt; 2e-16 *** Speciesvirginica:I(Petal.Length^2) 0.075714 0.004388 17.253 &lt; 2e-16 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.3431 on 146 degrees of freedom Multiple R-squared: 0.8318, Adjusted R-squared: 0.8284 F-statistic: 240.7 on 3 and 146 DF, p-value: &lt; 2.2e-16 </code></pre> </blockquote> <p>Now let's see if your function works too:</p> <pre><code>data(iris) reg &lt;- lm(Sepal.Length~Species: poly(Petal.Length,2,raw=T), data=iris) summary(reg) </code></pre> <p>It does (note it's different in that it necessary has the lower order term too):</p> <blockquote> <pre><code>Call: lm(formula = Sepal.Length ~ Species:poly(Petal.Length, 2, raw = T), data = iris) Residuals: Min 1Q Median 3Q Max -0.73849 -0.22814 -0.01978 0.24177 0.98833 Coefficients: Estimate Std. Error t value Pr(&gt;|t|) (Intercept) 1.79002 1.58957 1.126 0.2620 Speciessetosa:poly(Petal.Length, 2, raw = T)1 3.87221 2.16771 1.786 0.0762 . Speciesversicolor:poly(Petal.Length, 2, raw = T)1 1.13016 0.78109 1.447 0.1501 Speciesvirginica:poly(Petal.Length, 2, raw = T)1 0.74216 0.56640 1.310 0.1922 Speciessetosa:poly(Petal.Length, 2, raw = T)2 -1.12847 0.74087 -1.523 0.1299 Speciesversicolor:poly(Petal.Length, 2, raw = T)2 -0.03641 0.09628 -0.378 0.7059 Speciesvirginica:poly(Petal.Length, 2, raw = T)2 0.02178 0.05107 0.426 0.6705 --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 Residual standard error: 0.3367 on 143 degrees of freedom Multiple R-squared: 0.8413, Adjusted R-squared: 0.8346 F-statistic: 126.4 on 6 and 143 DF, p-value: &lt; 2.2e-16 </code></pre> </blockquote> <p>So what's the difference? </p> <p>Well, like I was saying in your other question basically just that <code>I()</code> is what the vast majority of R programmers use in <code>lm</code> and <code>glm</code> equations because it's far more flexible -- can be used for any transformation within the equation. </p> <p>But to each his own. SO disallows opinion-based questions, so I'm going to interpret the question as "do both work?" to which the answer is "yes" and "why is I() used ubiquitously?" to which the answer is "it's flexible to any transformation". As for whether you <strong><em>should</em></strong> use it, that's not a question we can legitimately ask or answer on SO, but you could probably ask it on the Programmers Stack Exchange (or whatever they're calling it these days) or the Code Review Stack Exchange.</p>
Spark: Caching an RDD/DF for use across multiple programs <p>I have a dataset that is being read from multiple programs. Instead of reading this dataset into memory a number of times each day, is there a way for spark to effectively cache the dataset, allowing any program to call upon it? </p>
<p>RDDs and Datasets cannot be shared between application (at least, there is no official API to share memory)</p> <p>However, you may be interested in Data Grid. Look at <a href="http://ignite.apache.org/" rel="nofollow">Apache Ignite</a>. You can i.e. load data to Spark, preprocess it and save to grid. Then, in other applications you could just read data from Ignite cache. </p> <p>There is a special type of RDD, named IgniteRDD, which allows you to use Ignite cache just like other data sources. Of course, like any other RDD, it can be converted to Dataset</p> <p>It would be something like this:</p> <pre><code>val rdd = igniteContext.fromCache("igniteCache") val dataFrame = rdd.toDF </code></pre> <p>More information about IgniteContext and IgniteRDD you can find <a href="https://apacheignite-fs.readme.io/docs/ignitecontext-igniterdd" rel="nofollow">here</a></p>
How to use rfind() to separate and print string according to username? <p>I don't ask many questions here, so I hope this is specific enough to be answered. </p> <p>I'm working on a project for a Software Construction class I am in, and am having trouble with part of the assignment. Basically we are writing a program that allows new users to be created, and then those users can post messages. </p> <p>Every time a message is posted, it is appended to a string (which I'm calling message_buffer). So, even if multiple users post, all their messages just get added to this string. The user names are enclosed in "%(" and ")%" and then their message is appended after that.</p> <p>Now, one of the options that the user(s) have is to print their "wall page." When they choose to print their wall page, only the messages posted by that user are to be printed in reverse chronological order. So for instance, if message_buffer contains "%(Jane)%Hey$^How are you?$^%(Jane)%How was your summer?$^" (the "$^" string just indicates that the user input a multi-line message, and is later replaced by "\n" escape sequence) then when the user chooses to print out their wall page, it should print:</p> <p>How was your summer?</p> <p>Hey</p> <p>How are you?</p> <p><strong>Why the professor wants the most recent messages to be at the top, I don't know, but c'est la vie.</strong></p> <p>So, my approach to this problem was to use rfind() to search for "%(" and then to determine the name enclosed by using rfind() to search for ")%". I then compare the name enclosed to the current user (since only their messages should be posted, and there can be multiple user messages in message_buffer) and if it does <em>not</em> match the current user's name, I erase everything starting at "%(" to the end, and then keep searching. If the name <em>does</em> match, then I print out everything, starting at "%(" until the end (I have a function which deleted the "$^" and replaces it with "\n", and also deletes the "%(name)%" part, since the users name isn't supposed to be included in the wall page). I continue to search until i reach the beginning of message_buffer.</p> <p>So, this works fine if there is only one message, for example: "%(Jane)%Hey$^How was your summer?$^ would print out correctly. But, if there is more than one name in message_buffer (like the example I gave in the beginning), then it doesn't correctly find the name, thus not correctly printing out all the messages. </p> <p>I suppose that is enough explaining, so here is the function I created to try and handle this:</p> <pre><code>void parseMessages(string bufferIn) { string message; string bCopy = bufferIn; string name; int index1; do { index1 = bCopy.rfind("%("); name = bCopy.substr(index1 + 2, bCopy.rfind(")%") - 2); if (name != username) { bCopy.erase(index1, bCopy.length()); } else if (name == username) { message = bCopy.substr(index1, bCopy.length()); bCopy.erase(index1, bCopy.length()); } message = format(message); cout &lt;&lt; message &lt;&lt; endl; if (index1 == 0) { index1 = -1; } } while (index1 &gt;= 0); } </code></pre> <p>So, if you were to input the first example I gave where there are two "%(Jane)%" messages, for some reason the variable name is set to "Jane)%How was your summer?$^" and I cannot for the life of me figure out why. If there is only one "%(Jane)%" string, then it works find; Variable name is set to "Jane" and the message prints out fine. </p> <p>What am I doing wrong here? Any help is <strong>greatly</strong> appreciated!</p>
<p>This should provide some insight.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; template&lt;class Func&gt; void reverse_iterate_messages(std::string const&amp; buffer, Func&amp;&amp; f) { auto current = buffer.size(); while (current) { auto pos = buffer.rfind("%(", current - 1); auto end_name = buffer.find(")%", pos + 2); if (end_name &lt; current) { auto name = buffer.substr(pos + 2, end_name - pos - 2); auto message = buffer.substr(end_name + 2, current - end_name - 2); f(name, message); current = pos; } else { break; // incorrectly formatted string } } } void show(std::string const&amp; name, std::string message) { if (name == "Jane") { for (std::size_t pos = 0 ; pos &lt; message.size() ; ) { auto i = message.find("$^", pos); if (i == std::string::npos) break; message.replace(i, 2, "\n"); pos = i + 1; } std::cout &lt;&lt; message; } } int main() { auto test_string = "%(Jane)%Hey$^How are you?$^%(Jane)%How was your summer?$^"; reverse_iterate_messages(test_string, show); } </code></pre> <p>expected output:</p> <pre><code>How was your summer? Hey How are you? </code></pre>
ng-disabled not working properly 5 <p>As Question and Answer related to ng-disabled didn't help, so I am writing this question for help.</p> <p>The problem is in my angularjs app ng-disabled is not working properly.</p> <p>Here is the jsfiddle of the problem <br> <a href="http://fiddle.jshell.net/80cLw91j/" rel="nofollow">http://fiddle.jshell.net/80cLw91j/</a></p> <p>the desired behaviour is when you click the start button, all input elements including the start button should get disabled and stop button should get enabled and vice versa when you click stop button.</p>
<p>Answer is pretty simple. You facing <a href="http://stackoverflow.com/a/17607794/511374">Angular scope dot problem</a> and <a href="http://fiddle.jshell.net/wr894tau/" rel="nofollow">here</a> is jsfiddle for you. </p>
django-pipeline throwing ValueError: the file could not be found <p>When running <code>python manage.py collectstatic --noinput</code> I'm getting the following error:</p> <pre><code>Post-processing 'jquery-ui-dist/jquery-ui.css' failed! Traceback (most recent call last): File "manage_local.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 193, in handle collected = self.collect() File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 145, in collect raise processed File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 257, in post_process content = pattern.sub(converter, content) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 187, in converter hashed_url = self.url(unquote(target_name), force=True) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 132, in url hashed_name = self.stored_name(clean_name) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 292, in stored_name cache_name = self.clean_name(self.hashed_name(name)) File "/Users/michaelbates/GoogleDrive/Development/inl/venv/lib/python3.4/site-packages/django/contrib/staticfiles/storage.py", line 95, in hashed_name (clean_name, self)) ValueError: The file 'jquery-ui-dist/"images/ui-icons_555555_256x240.png"' could not be found with &lt;pipeline.storage.PipelineCachedStorage object at 0x1073e2c50&gt;. </code></pre> <p>If I run <code>python manage.py findstatic jquery-ui-dist/"images/ui-icons_555555_256x240.png"</code> I get:</p> <pre><code>Found 'jquery-ui-dist/images/ui-icons_555555_256x240.png' here: /Users/michaelbates/GoogleDrive/Development/inl/node_modules/jquery-ui-dist/images/ui-icons_555555_256x240.png /Users/michaelbates/GoogleDrive/Development/inl/staticfiles/jquery-ui-dist/images/ui-icons_555555_256x240.png </code></pre> <p>Here are some relevant settings:</p> <pre><code>STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'pipeline.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'node_modules'), ) </code></pre> <p>My <code>PIPELINE</code> settings dict is huge so I won't post the entire thing, but some parts of it are:</p> <pre><code>PIPELINE = { 'STYLESHEETS': { 'pricing': { 'source_filenames': ( 'jquery-ui-dist/jquery-ui.min.css', ), 'output_filename': 'css/pricing.min.css' }, } 'JS_COMPRESSOR': 'pipeline.compressors.yuglify.YuglifyCompressor', 'CSS_COMPRESSOR': 'pipeline.compressors.yuglify.YuglifyCompressor', 'COMPILERS': ( 'pipeline.compilers.sass.SASSCompiler', ) } </code></pre> <p>I've tried changing the STATICFILES_FINDERS to the django-pipeline specific ones but it makes no difference.</p> <p>Can anyone shed some light on why that png file can't be found during collectstatic but can with findstatic?</p>
<p>Your problem is related to <a href="https://code.djangoproject.com/ticket/21080" rel="nofollow">this bug</a> on the Django project.</p> <p>In short, django-pipeline is post-processing the <code>url()</code> calls with Django's <code>CachedStaticFilesStorage</code> to append the md5 checksum to the filename (<a href="https://docs.djangoproject.com/en/1.10/ref/contrib/staticfiles/#manifeststaticfilesstorage" rel="nofollow">more details here</a>) and doesn't detect when it is inside a comment.</p> <p>If you look on the header of the <code>jquery-ui.css</code> (and similar) files there is a comment that starts with </p> <blockquote> <ul> <li>To view and modify this theme, visit [...]</li> </ul> </blockquote> <p>Inside the URL on this line there is a parameter that is being interpreted as an <code>url()</code> call and generating the error you see.</p> <p>To work around this issue you can simply remove the above line from <code>jquery-ui.css</code> and <code>collectstatic</code> should work properly.</p>
How to fix error in trying to implement Google Maps after updating SDK in Android Studio? <p>After updating the Android SDK, GooglePlayServices isn't working anymore. I went back to test a maps app I had and updated play services from 8.4.0 to 9.6.1 because of other dependency update requirements. I am using build tools 24.0.3, and Android Studio 2.2. When I run the app after updating sdk and syncing gradle, the app crashes stating that it is failing to find FirebaseInitProvider. Yet I am not using any Firebase utilites/dependencies.</p> <p><strong>LOGCAT</strong></p> <pre><code> 10-12 16:27:57.509 15347-15347/? D/dalvikvm: Late-enabling CheckJNI 10-12 16:27:57.536 15347-15353/? D/dalvikvm: Debugger has detached; object registry had 1 entries 10-12 16:27:57.573 15347-15347/? D/AndroidRuntime: Shutting down VM 10-12 16:27:57.573 15347-15347/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x4169ed58) 10-12 16:27:57.575 15347-15347/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.curtrostudios.maptest, PID: 15347 java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/com.curtrostudios.maptest-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.curtrostudios.maptest-1, /vendor/lib, /system/lib]] at android.app.ActivityThread.installProvider(ActivityThread.java:4848) at android.app.ActivityThread.installContentProviders(ActivityThread.java:4440) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4380) at android.app.ActivityThread.access$1500(ActivityThread.java:138) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1259) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5072) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider" on path: DexPathList[[zip file "/data/app/com.curtrostudios.maptest-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.curtrostudios.maptest-1, /vendor/lib, /system/lib]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56) at java.lang.ClassLoader.loadClass(ClassLoader.java:497) at java.lang.ClassLoader.loadClass(ClassLoader.java:457) at android.app.ActivityThread.installProvider(ActivityThread.java:4833) at android.app.ActivityThread.installContentProviders(ActivityThread.java:4440)  at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4380)  at android.app.ActivityThread.access$1500(ActivityThread.java:138)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1259)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:136)  at android.app.ActivityThread.main(ActivityThread.java:5072)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:515)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)  at dalvik.system.NativeStart.main(Native Method)  </code></pre> <p><strong>TOOLS</strong></p> <p>com.android.support:appcompat-v7:24.2.1</p> <p>com.google.android.gms:play-services:9.6.1</p> <p>buildToolsVersion 24.0.3</p> <p>Android Studios v2.2 RC2</p> <p>Asus PadFone Android v4.4.2</p> <p>*No other dependencies are being used at this time.</p> <p><strong>WHAT I'VE TRIED</strong></p> <ul> <li>applicationId is already defined</li> <li>I've cleaned project, rebuilt, and run</li> <li>I've invalidated caches and restarted</li> <li>I've removed the app from the device, restarted device, reinstalled</li> <li>I've tried reverting to PlayServices 8.4.0 Still nothing works. </li> </ul> <p>I've searched Google and nothing indicates that Google Maps requires or relies on the Firebase API.</p>
<p>In order to use maps, it's better to use the split of play services:</p> <pre><code>compile 'com.google.android.gms:play-services-maps:9.6.1' </code></pre> <p>if using Gps etc add also:</p> <pre><code>compile 'com.google.android.gms:play-services-location:9.6.1' </code></pre>
Scene rendering black when entering VR mode in A-Frame <p>I am using A-Frame 0.3.0. Everything renders fine on the screen, but when I enter VR mode, it renders black. I have tried the latest Chromium and Firefox Nightly builds from September. Even the A-Frame examples do not working.</p> <pre><code>&lt;script src="https://aframe.io/releases/0.3.1/aframe.min.js"&gt;&lt;/script&gt; &lt;a-scene&gt; &lt;a-box color="red"&gt;&lt;/a-box&gt; &lt;/a-scene&gt; </code></pre>
<p>This is because the September 2016 builds of Chromium and Firefox Nightly were updated to use the new WebVR 1.1 API spec, whereas A-Frame was working on WebVR 1.0 API spec.</p> <p>This has been updated in A-Frame v0.3.2, where we have bumped VREffect to match the latest API changes.</p> <pre><code>&lt;script src="https://aframe.io/releases/0.3.2/aframe.min.js"&gt;&lt;/script&gt; &lt;a-scene&gt; &lt;a-box color="red"&gt;&lt;/a-box&gt; &lt;/a-scene&gt; </code></pre> <p>EDIT: additional breaking changes have been announced for WebVR 1.1, so things may break in future experimental versions of the browser temporarily until A-Frame updates again</p>
Non-type template arguments explicit instantiation in source file <p>I am wrapping a library into my class design. I would like to call a template method with unsigned int non-type parameter provided in the library in my class constructor. </p> <pre><code>#include &lt;iostream&gt; #include &lt;bar.h&gt; // template header in here class foo { foo(unsigned num) { BAR&lt;num&gt;(); // a template method BAR inside "bar.h" } }; </code></pre> <p>When I tries to play around with this it seems that the non-type parameter is a constexpr. So the above code will generate error indicating that there is const error inside the function call.</p> <p>So I decide to make the foo class a class template and pass this unsigned non-type parameter in foo's template argument parameter.</p> <pre><code>#include &lt;iostream&gt; #include &lt;bar.h&gt; // template header in here template &lt;unsigned num&gt; class foo { foo() { BAR&lt;num&gt;(); // a template method BAR inside "bar.h" } }; </code></pre> <p>This seems to be working well. However, I would like to separate the header and source file into separate .hpp/.cpp files. According to <a href="http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file">this thread</a>, if I want to place template implementation inside .cpp source file, I have to explicitly instantiate all possible template argument at the end of .cpp file. For non-type parameter like unsigned integer, does that mean I have to instantiate thousands of possible unsigned int number to make the template available to all unsigned number object? Thanks for the help.</p>
<p>I wouldn't recommend separating the implementation of a template class into a source file. If I understand your situation correctly then I don't think it's possible to do that unless you instantiate all possible values of the template parameter, which is impossible for an <code>unsigned</code>.</p>
Submitting form with AJAX not working. It ignores ajax <p>I've never used Ajax before, but from researching and other posts here it looks like it should be able to run a form submit code without having to reload the page, but it doesn't seem to work.</p> <p>It just redirects to ajax_submit.php as if the js file isn't there. I was trying to use Ajax to get to ajax_submit without reloading anything.</p> <p>Is what i'm trying to do even possible?</p> <p>HTML form:</p> <pre><code>&lt;form class="ajax_form" action="ajax_submit.php" method="post"&gt; &lt;input class="input" id="license" type="text" name="license" placeholder="License" value="&lt;?php echo htmlentities($person['license1']); ?&gt;" /&gt; &lt;input class="input" id="license_number" type="text" name="license_number" placeholder="License number" value="&lt;?php echo htmlentities($person['license_number1']); ?&gt;" /&gt; &lt;input type="submit" class="form_button" name="submit_license1" value="Save"/&gt; &lt;input type="submit" class="form_button" name="clear1" value="Clear"/&gt; &lt;/form&gt; </code></pre> <p>in scripts.js file:</p> <pre><code>$(document).ready(function(){ $('.ajax_form').submit(function (event) { alert('ok'); event.preventDefault(); var form = $(this); $.ajax({ type: "POST", url: "ajax_submit.php",//form.attr('action'), data: form.serialize(), success: function (data) {alert('ok');} }); }); }); </code></pre> <p>in ajax_submit.php:</p> <pre><code>require_once("functions.php"); require_once("session.php"); include("open_db.php"); if(isset($_POST["submit_license1"])){ //query to insert }elseif(isset($_POST['clear1'])) { //query to delete } </code></pre> <p>I have "<code>&lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"&gt;&lt;/script&gt;</code>" in the html head</p>
<p><code>form.serialize()</code> doesn't know which button was used to submit the form, so it can't include any buttons in the result. So when the PHP script checks which submit button is set in <code>$_POST</code>, neither of them will match.</p> <p>Instead of using a handler on the <code>submit</code> event, use a click handler on the buttons, and add the button's name and value to the <code>data</code> parameter.</p> <pre><code>$(":submit").click(function(event) { alert('ok'); event.preventDefault(); var form = $(this.form); $.ajax({ type: "POST", url: "ajax_submit.php",//form.attr('action'), data: form.serialize() + '&amp;' + this.name + '=' + this.value, success: function (data) {alert('ok');} }); }); </code></pre>
Symfony2 redirect from old url to new url <p>I am using Symfony 2.8 and I've created a section (on the Admin Bundle) to register old paths and the new paths where to redirect when accessing the first ones. For example: My domain is <code>www.mypage.com</code>. My old webpage "About us" route was: <code>www.mypage.com/about</code>. My new webpage "About us" route is: <code>www.mypage.com/about-us</code>. So, I registered on the admin redirections section the old path and the new path this way: <code>/about</code> (old one) and <code>/about-us</code> (new one).</p> <p>My question is: Where and how to compare the path, because my controller has to recognize the old path on my database and redirect to the new one.</p> <p>Thanks!</p>
<p>To do that, you can use the eventlistener of symfony2. </p> <p>Referer to : <a href="https://github.com/adashbob/ecommerce/blob/master/src/Ecommerce/FrontBundle/Resources/config/services/listeners_services.yml" rel="nofollow">declare a eventlistener</a></p> <p><a href="https://github.com/adashbob/ecommerce/blob/master/src/Ecommerce/FrontBundle/EventListener/RedirectionListener.php" rel="nofollow">EventListener's Class</a></p>
Is there a way to hide the side bar in Sublime Text 2? <p>Is there a way to hide the side bar that shows you what line you're on in <code>Sublime Text 2</code>?</p> <p>Here is the bar: <a href="https://i.stack.imgur.com/vbuwt.png" rel="nofollow"><img src="https://i.stack.imgur.com/vbuwt.png" alt="enter image description here"></a></p>
<p>Add <code>"gutter":false</code> to user preferences.</p>
Assigning variables values in a better way <p>I have a written a bash script which uses number of parameters. I have assigned variables in the following format.</p> <pre><code>x=$1 y=$2 z=$3 k=$4 </code></pre> <p>The arguments are optional, and it runs without them as well For example :</p> <pre><code>./myscript.sh ./myscript.sh x y ... </code></pre> <p>both cases are working fine.</p> <p>I am looking for a better approach, from design point of view as I don't like the way the variables are getting the value.</p> <p>it will not look nice if in the future my arguments increase till 9</p> <p>Thanks.</p>
<p>You can use <code>read</code> combined with herestring and the quote reconstruction ability of <code>printf</code>:</p> <pre><code>read x y z k &lt;&lt;&lt;$(printf " %q" "$@") </code></pre> <p>By example:</p> <pre><code>$ cat example.bash #!/bin/bash read x y z k &lt;&lt;&lt;$(printf " %q" "$@") echo "x=[$x]" echo "y=[$y]" echo "z=[$z]" echo "k=[$k]" $ ./example.bash a b "c d" x=[a] y=[b] z=[c d] k=[] </code></pre> <p>So, what's going on here? Let's work from the inside out.</p> <p><code>printf " %q" "$@"</code> <a href="http://stackoverflow.com/a/10836225/2908724">quotes</a> the arguments it's given in a way equivalent to the original command line arguments. Without this quoting reconstruction, command line arguments with spaces would be treated as <em>separate arguments even if originally quoted</em>. To see what I mean, try <code>read x y z w &lt;&lt;&lt;"$@"</code>: z is assigned "c" and k is assigned "d".</p> <p><code>read</code> receives the reconstituted command line, then assigns every non-escaped-space separated string into the given variables, left to right.</p> <p>Back to our example:</p> <ul> <li><code>"$@"</code> is essentially <code>a b "c d"</code></li> <li><code>printf " %q" "$@"</code> is <code>a b c\ d</code></li> <li><code>read x y z k &lt;&lt;&lt;"a b c\ d"</code> is a hard-coded representation of what you want.</li> </ul> <p>While this is compact and extensible, it's also tricky. If your script takes arguments representing <em>options</em> (script behavior changes based on presence of absence of said arguments) then I'd suggest using <code>getopts</code>. If, however, your script takes many arguments representing <em>values</em> (like inputs into a matrix calculation) then reading into an array (<code>read -a</code>) might be easier to understand.</p> <hr> <p>You might also want to handle the case where no command line arguments are provided. That requires a slight elaboration:</p> <pre><code>read x y z k &lt;&lt;&lt;$([ 0 -eq $# ] &amp;&amp; echo '' || printf " %q" "$@") </code></pre> <p>In this variant, the number of arguments are checked and if there are some, then the printf requoting business is performed.</p>
unable to set property 'visibility' or 'display' <p>I have a dropdownlist box in the datagrid and I need to hide or show it. I can get the element. However I get an error 'Unable to set property 'display' of undefined or null reference. when I want to hide it. I tried to use visibility and it has same type of error too. Would someone show me how to do it. Thanks</p> <p>My control:</p> <pre><code>&lt;asp:dropdownList ID="dropID" runat="server" cssclass="selectColor w175 show"/&gt; </code></pre> <p>The class in my style sheet:</p> <pre><code>.show { display: normal; } .selectColor { color: #333333; } .w175 { width:175px; } </code></pre> <p>my javascript function:</p> <pre><code>function NeedChange(id) { var dropID = document.getElementById(id); if (dropID!=undefined ){ //dropID.style.visibility="hidden"; dropID.style.display='none'; } } </code></pre>
<p>This should work</p> <pre><code>function NeedChange(id) { var dropID = document.getElementById(id); if (dropID!=undefined ){ //dropID.style.visibility="hidden"; $("#dropID").removeClass("show"); } } </code></pre>
check if nested form records are null <p>Can I check if some record in the nested form is null? I am trying this but it does not work</p> <pre><code>&lt;%= f.fields_for :detallepromo do |builder| %&gt; &lt;% if builder.Monto == nil %&gt; &lt;div class="well center-block"&gt; &lt;div class="form-group"&gt; &lt;h3 class="col-md-5"&gt;Promocion Base:&lt;/h3&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;%= builder.label :Monto,"Monto:", class: "control-label col-md-2" %&gt; &lt;div class="col-md-3"&gt; &lt;%= builder.text_field :Monto, class: "form-control mensaje_fechafinal" %&gt; &lt;/div&gt; &lt;% end %&gt; &lt;% end &gt; </code></pre>
<p>how, if like this:</p> <pre><code> &lt;% if :detallepromo? %&gt; &lt;p&gt;bla.bla..&lt;/p&gt; &lt;% else %&gt; &lt;%= f.fields_for :detallepromo do |builder| %&gt; &lt;div class="well center-block"&gt; &lt;div class="form-group"&gt; &lt;h3 class="col-md-5"&gt;Promocion Base:&lt;/h3&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;%= builder.label :Monto,"Monto:", class: "control-label col-md-2" %&gt; &lt;div class="col-md-3"&gt; &lt;%= builder.text_field :Monto, class: "form-control mensaje_fechafinal"%&gt; &lt;/div&gt; &lt;% end %&gt; &lt;% end &gt; </code></pre>
Inserting data into database with python/sqlite3 by recognising the column name <p>I've got a problem that I don't know how to solve, I've tried many solutions but always getting that Operational error: near...</p> <pre><code>def insert_medicine_to_table(): con = sqlite3.connect('med_db3.db') cur = con.cursor() table_name = 'medicines' column_name = "présentation" value = 'Boîte de 2 seringues pré-remplies' cur.execute("INSERT INTO medicines {} VALUES (?)".format(column_name), value) con.commit() con.close() sqlite3.OperationalError: near "présentation": syntax error </code></pre> <p>The goal here is that either the script or python has to recognize the field (column name) and insert the value into "that" field, like the following:</p> <pre><code>fields = ['présentation', 'princeps', 'distributeur_ou_fabriquant', 'composition', 'famille', 'code_atc', 'ppv', 'prix_hospitalier', 'remboursement', 'base_de_remboursement__ppv', 'nature_du_produit'] values = ['Boîte de 2 seringues pré-remplies', 'Oui', 'SANOFI', 'Héparine', 'Anticoagulant héparinique', 'B01AB01', '43.80', '27.40', 'Oui', '43.80', 'Médicament'] </code></pre> <p>That is one entry in the database. The problem here is that other entries can or not have one or more values for some field, and also the fields are not presented in the same order in other entries.</p> <p>It has to recognize each field in the database table and insert each value into the right column. </p>
<p>The problem causing your error is that your SQL isn't valid. The statement you are trying to execute is:</p> <pre><code>INSERT INTO medicines présentation VALUES (?) </code></pre> <p>The statement you want to execute is:</p> <pre><code>INSERT INTO medicines ("présentation") VALUES (?) </code></pre> <p>As far as your larger question is concerned, if you create both the list of columns <code>("présentation")</code> and list of parameter markers <code>(?)</code> and build the query using them, you're most of the way there. </p> <p>If a field can have multiple values supplied for each "entry" in your database, you may need to change your database design to handle that. You'll at least need to figure out how you want to handle the situation, but that would be a matter for a different question.</p>
How to reference ASP.Net Identity User Email property as Foreign Key <p>New to coding so please bare with me, and apologies in advance for the worlds longest question.</p> <p>Trying to reference the Email property of an ASP.Net Identity User as a Foreign Key but keep getting an error message</p> <p>using MVC6, EF7</p> <p>I have an <code>AppAccount</code> which is the Primary model and the <code>ApplicationUser: IdentityUser</code> is the dependant.</p> <p>I'm trying to set the <code>Email</code> property of the <code>ApplicationUser</code> as a foreign key the <code>AppAccount</code> model</p> <pre><code>public class AppAccount { public string AppAccountID { get; set; } public string AccountType { get; set; } public DateTime DateCreated { get; set; } public virtual ApplicationUser AppUser { get; set; } } public class ApplicationUser : IdentityUser { public string FirstName { get; set; } public string Surname { get; set; } public DateTime DOB { get; set; } public virtual AppAccount AppAccount { get; set; } } </code></pre> <p>'Peeking' to the definition of the IdentityUser tells me the Email property is of type string...</p> <pre><code>public class IdentityUser&lt;TKey&gt; where TKey : IEquatable&lt;TKey&gt; { ... // // Summary: // Gets or sets the email address for this user. public virtual string Email { get; set; } ... } </code></pre> <p>I have set the PK of the <code>AppAccount</code> Model to string and made the <code>Email</code> property of the <code>ApplicationUser</code> an Alternate key, then set a One-To-One relationship using fluent API...</p> <pre><code>builder.Entity&lt;ApplicationUser&gt;(au =&gt; { au.HasAlternateKey(u =&gt; u.Email); au.HasAlternateKey(u =&gt; u.UserName); }); builder.Entity&lt;AppAccount&gt;(aa =&gt; { aa.HasKey(a =&gt; a.AppAccountID); aa.HasOne(a =&gt; a.AppUser) .WithOne(u =&gt; u.AppAccount) .HasPrincipalKey&lt;ApplicationUser&gt;(u =&gt; u.Email); // PK of AppAccount is FK of AppUser }); </code></pre> <p>When I run the migration it works ok but when I try to update the database I get the following error</p> <pre><code>Error Number:1753,State:0,Class:16 Column 'AspNetUsers.Email' is not the same length or scale as referencing column 'AppAccount.AppAccountID' in foreign key 'FK_AppAccount_ApplicationUser_AppAccountID'. Columns participating in a foreign key relationship must be defined with the same length and scale. Could not create constraint or index. See previous errors. </code></pre> <p>I have tried manually setting the maximum length of the <code>AppAccountID</code> and <code>Email</code> properties to the same limit</p> <pre><code>builder.Entity&lt;ApplicationUser&gt;(au =&gt; { ... au.Property(u =&gt; u.Email).HasMaxLength(100); }); builder.Entity&lt;AppAccount&gt;(aa =&gt; { ... aa.Property(a =&gt; a.AppAccountID).HasMaxLength(100); ... }); </code></pre> <p>I have tried setting both properties to the same type on the server...</p> <pre><code>builder.Entity&lt;ApplicationUser&gt;(au =&gt; { ... au.Property(u =&gt; u.Email).ForSqlServerHasColumnType("nvarchar(100)"); }); builder.Entity&lt;AppAccount&gt;(aa =&gt; { ... aa.Property(a =&gt; a.AppAccountID).ForSqlServerHasColumnType("nvarchar(100)"); ... }); </code></pre> <p>tried overriding the <code>Email</code> property in the <code>ApplicationUser</code> class to</p> <pre><code>public override string Email {get ; set ;} </code></pre> <p>and I tried setting the <code>AppAccountID</code> property of the <code>AppAccount</code> Model to <code>virtual</code></p> <pre><code>`public virtual string AppAccountID {get ; set ;} </code></pre> <p>I think this may be a server issue but checking the database the <code>Email</code> column type is nvarchar, so I dont understand why it doesnt compile?</p>
<p>Try this Model</p> <pre><code>public class AppAccount { public string AppAccountID { get; set; } public string AccountType { get; set; } public DateTime DateCreated { get; set; } [ForeignKey("UserId") public virtual ApplicationUser AppUser { get; set; } } </code></pre>
What are interviewers looking for when they ask "How would you test this"? <p>In a Software Engineering interview, oftentimes I come across the question "How would you test this?" after writing out the solution to their coding prompt. They always state they are not interested in functional/unit type of testing, so what kinds of answers are interviewers looking for?</p> <p>For example, suppose the coding prompt was to write a function that returns a unique string abbreviation following a certain format for all strings passed in. Then you wrote the solution and then are asked what tests you would perform on this function disregarding functional/unit cases. How would you answer?</p>
<p>I don't think this question belongs here, but unless someone removes it I'll say what I'm thinking:</p> <p>Most likely what a hiring manager would like to see is that you test for standard and corner cases, firstly to ensure that your solution works in all cases (especially to see that you've considered the corner cases). Secondly, if your solution doesn't work in the corner cases you've thought of, why not, how can you support these cases.. It's nice to show that you've considered all cases, even those that are not so obvious. Most importantly, they don't want you to miss most of the corner cases which could be a big demerit.</p>
Does Spring Data for MongoDB allow documents with optional fields? <p>Can I have a nullable field that: - if its value is null, we wouldn't store the field (name or value) on the document, and - if its value is non-null, we would store the field name and value on it. </p>
<p>Yes, it does, just do not set the property while creating the model and that field and the value will not be inserted in mongodb document. The fields for which the values are set, only those will be stored in the mongodb document.</p> <pre><code>package org.scalar.test; import org.scalar.model.Product; import org.scalar.model.Summary; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.mongodb.core.MongoTemplate; public class App { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring/applicationContext.xml"); for (int i=0;i&lt;10;i++) { Product product = new Product(); product.setId(String.valueOf(i)); /*Summary summary = new Summary(); */ MongoTemplate template = (MongoTemplate)context.getBean("mongoTemplate"); template.save(product); } System.out.println("end"); ((ClassPathXmlApplicationContext)context).close(); } } </code></pre> <p>Product.java</p> <pre><code>package org.scalar.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection="products") public class Product { @Id public String id; public Summary summary; public String getId() { return id; } public void setId(String id) { this.id = id; } public Summary getSummary() { return summary; } public void setSummary(Summary summary) { this.summary = summary; } } </code></pre> <p>Mongodb output</p> <pre><code>&gt; db.products.find(); { "_id" : "0", "_class" : "org.scalar.model.Product" } { "_id" : "1", "_class" : "org.scalar.model.Product" } { "_id" : "2", "_class" : "org.scalar.model.Product" } { "_id" : "3", "_class" : "org.scalar.model.Product" } { "_id" : "4", "_class" : "org.scalar.model.Product" } { "_id" : "5", "_class" : "org.scalar.model.Product" } { "_id" : "6", "_class" : "org.scalar.model.Product" } { "_id" : "7", "_class" : "org.scalar.model.Product" } { "_id" : "8", "_class" : "org.scalar.model.Product" } { "_id" : "9", "_class" : "org.scalar.model.Product" } </code></pre> <p>HTH</p>
How do I pass the jQuery selection object into a function being called by the selection? <p>New to jQuery and I don't know how else to say it.</p> <p>When the function below is within the jquery selection, it works fine. When I try to break out the function I'm not sure what object/variable needs to be passed into the function in order to make the function work.</p> <pre><code>//function included in selection works great $('#id1 tbody tr').find('td:eq(2)').text( function(i,t){ return Math.round((parseInt(t,10) / 60)*100)/100; }); //function broken out returns NaN in HTML $('#id2 tbody tr').find('td:eq(2)').text(minutesToHours()); function minutesToHours(i,t){ return Math.round((parseInt(t,10) / 60)*100)/100; } </code></pre> <p>It's the same function but returns 'NaN' in the HTML. I know I need to pass the object into the function <code>minutesToHours()</code>, but nothing I've tried works-- <code>this</code> or <code>$(this)</code>. <code>minutesToHours('whatGoes','here')</code></p> <p><a href="https://jsfiddle.net/bkuethen/nu6zczu4/" rel="nofollow">JSFiddle</a></p> <p>I'm assuming this has something to do with <a href="http://stackoverflow.com/questions/3630054/how-do-i-pass-the-this-context-to-a-function">context</a> but I can't figure it out.</p> <p>Example HTML</p> <pre><code>&lt;table id="id1"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;John&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;td&gt;800&lt;/td&gt; &lt;td&gt;4&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Sally&lt;/td&gt; &lt;td&gt;5&lt;/td&gt; &lt;td&gt;610&lt;/td&gt; &lt;td&gt;9&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Bob&lt;/td&gt; &lt;td&gt;7&lt;/td&gt; &lt;td&gt;249&lt;/td&gt; &lt;td&gt;3&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;table id="id2" style="margin-top:1em;"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;John&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;td&gt;800&lt;/td&gt; &lt;td&gt;4&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Sally&lt;/td&gt; &lt;td&gt;5&lt;/td&gt; &lt;td&gt;610&lt;/td&gt; &lt;td&gt;9&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Bob&lt;/td&gt; &lt;td&gt;7&lt;/td&gt; &lt;td&gt;249&lt;/td&gt; &lt;td&gt;3&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>Result</p> <pre><code>Included function John 2 13.33 4 Sally 5 10.17 9 Bob 7 4.15 3 Broken out function John 2 NaN 4 Sally 5 NaN 9 Bob 7 NaN 3 </code></pre> <p>Thanks for your help!</p>
<p>To further explain Adeno's answer in the comments:</p> <p><a href="http://api.jquery.com/text/" rel="nofollow">From the docs:</a></p> <blockquote> <p>.text( function )</p> <p>function</p> <p>Type: Function( Integer index, <strong>String text</strong> ) => String A function returning the text content to set. <em>Receives the index position of the element in the set and the old text value as arguments.</em></p> </blockquote> <p>This means that when you call the below, <code>t</code> is filled with <em>the old text value</em>:</p> <pre><code>$('#id1 tbody tr').find('td:eq(2)').text( function(i,t){ return Math.round((parseInt(t,10) / 60)*100)/100; }); </code></pre> <p>However, when you use <code>minutesToHours()</code> in the below, you are actually calling <code>minutesToHours()</code> <em>with no parameters</em> and passing the returned value into <code>.text()</code> Since you didnt pass any variables to the function,<code>t</code> is undefined and the function produces <code>NaN</code>:</p> <pre><code>$('#id2 tbody tr').find('td:eq(2)').text(minutesToHours()); function minutesToHours(i,t){ return Math.round((parseInt(t,10) / 60)*100)/100; } </code></pre> <p>And a different signature for <code>.text()</code> is used:</p> <blockquote> <p>.text( text )</p> <p>text</p> <p>Type: String or Number or Boolean The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation.</p> </blockquote> <p>With Adeno's suggestion, you drop the <code>()</code> from <code>minutesToHours()</code> like the below. Now you are passing a reference to the <code>minutesToHours</code> function into <code>.text()</code> <em>not calling the function</em> . When, <code>.text()</code> sees the parameter is a function, it will call the function in that context, passing in the two values <code>(index, text )</code> and all is right with the world:</p> <pre><code>$('#id2 tbody tr').find('td:eq(2)').text(minutesToHours); function minutesToHours(i,t){ return Math.round((parseInt(t,10) / 60)*100)/100; } </code></pre>
2 different post layouts in a loop <p>I have just created thus BEAUTIFUL loop</p> <pre><code> &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;div class="row sectionrow" onclick="void(0)"&gt; &lt;div class="col-sm-4 sectionrecipes" style="background-image:url('&lt;?php echo the_field(background_image_title); ?&gt;');"&gt; &lt;div class="textsmall" &gt; &lt;?php the_field(titlebreak); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-8"&gt; &lt;div class="sectionrecipes" style="background-image:url('&lt;?php echo the_field(background_image_detail); ?&gt;');"&gt; &lt;div class="textbigrecipes"&gt; &lt;div class="inner"&gt; &lt;?php the_excerpt(); ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;button type="button" class="btn btn-default"&gt;READ MORE&lt;/button&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>But I would like to invert the positon of the bootstrap divs on the second post and return to orginal on the third and ....</p> <pre><code> &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;div class="row sectionrow" onclick="void(0)"&gt; &lt;div class="col-sm-8"&gt; &lt;div class="sectionrecipes" style="background-image:url('&lt;?php echo the_field(background_image_detail); ?&gt;');"&gt; &lt;div class="textbigrecipes"&gt; &lt;div class="inner"&gt; &lt;?php the_excerpt(); ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;button type="button" class="btn btn-default"&gt;READ MORE&lt;/button&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-4 sectionrecipes" style="background-image:url('&lt;?php echo the_field(background_image_title); ?&gt;');"&gt; &lt;div class="textsmall" &gt; &lt;?php the_field(titlebreak); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Is it possible?</p>
<pre><code>1. First declare a variable Outside the loop (like as $i =1), </code></pre> <ol start="2"> <li><p>Then check the condition. Mode of i</p> <pre><code>example: if($i% 2 == 0) { -----layout First code----- }else { -----layout Second code----- } </code></pre></li> <li>Increment the variable value ($i++) </li> </ol>
How to generate debug information in gcc/clang with separated compilation/link process in Makefile (-c -g)? <p>I had made a Makefile from Hilton Lipschitz's <a href="http://hiltmon.com/blog/2015/09/28/the-simple-c-plus-plus-makefile-executable-edition/" rel="nofollow">blog</a>, and made little changes to it in order to generate debug information. Main parts are listed:</p> <pre><code>CC := clang -arch x86_64 CFLAGS := -c -O0 $(TARGET): $(OBJECTS) @echo " Linking $(TARGET)"; $(CC) $^ -o $(TARGET) $(LIB) $(BUILDDIR)/%.o: $(SRCDIR)/%.$(SRCEXT) @mkdir -p $(BUILDLIST) @echo "Compiling $&lt;..."; $(CC) $(CFLAGS) $(INC) -o $@ $&lt; debug: CFLAGS += -g debug: $(TARGET) </code></pre> <p>Now <code>make</code> runs these commands (paths are summarized with <code>...</code>):</p> <pre><code>clang -arch x86_64 -c -O0 -I... -o build/program.o src/program.c clang -arch x86_64 build/program.o -o bin/program -L... </code></pre> <p>While <code>make debug</code> runs these commands:</p> <pre><code>clang -arch x86_64 -c -O0 -g -I... -o build/program.o src/program.c clang -arch x86_64 build/program.o -o bin/program -L... </code></pre> <p>The problem is when I execute <code>make</code> or <code>make debug</code>, no <code>program.dSYM</code> subfolder will be made in <code>bin</code> folder. Instead, when I compile without <code>-c</code> argument:</p> <pre><code>clang -arch x86_64 -g -O0 -I... -L... -o bin/program.o src/program.c </code></pre> <p>both executable file and <code>.dSYM</code> are created in <code>bin</code> folder.</p> <ol> <li>How can I add debugging information generation feature to this Makefile while separating compiling and linking process?</li> <li>In which step (compiling/linking) debug information is produced?</li> </ol> <p><strong>UPDATE</strong>: I created a GitHub <a href="https://github.com/hamid914/gdb-lldb-test" rel="nofollow">repo</a> and uploaded related Makefile and source to it. To reproduce the problem, please run these commands in your terminal:</p> <pre><code>git clone https://github.com/hamid914/gdb-lldb-test.git cd gdb-lldb-test make debug </code></pre> <p>The last line, <code>make debug</code> executes these commands:</p> <pre><code>clang -arch x86_64 -c -O0 -std=c11 -g -I include -I include/libs -I /usr/local/include -o build/program.o src/program.c clang -arch x86_64 build/program.o -o bin/program -L /usr/local/lib -lm -g </code></pre> <p>And content of <code>bin</code> folder is:</p> <pre><code>$ ls bin program </code></pre> <p>While if I run <code>clang</code> without <code>-c</code> argument:</p> <pre><code>clang -arch x86_64 -O0 -std=c11 -g -I include -I include/libs -I /usr/local/include -L /usr/local/lib -lm -o bin/program src/program.c </code></pre> <p>Contents of <code>bin</code> folder are:</p> <pre><code>$ ls bin program program.dSYM </code></pre>
<p>You need to add <code>-g</code> to the linker recipe as well in order to generate .dSYM files, the standard way would be to add</p> <pre><code>debug: LDFLAGS += -g </code></pre> <p>but the example you're following defines its own variables for no good reason, it looks like <code>LIB</code> should work however.</p>
Academic-setting clarification of the term "Standard Input" in Java and verifying Input <p>Was instructed, for a university-level assignment, to receive user input through "standard input". Google was a bit scarce as to what precisely this means. </p> <p>While I could (and for the sake of my grade, will) go to my professor for clarification, I figured I would ask Stack Overflow so if anyone in the future has the same question they can find this and do without the research I performed; additionally, I appreciate the history lesson some Stack Overflow contributors provide. </p> <p>Basically, what I found was receiving user input was originally done via standard input methods (hardware). However, and this is where things get complicated, now the process has been abstracted. Instead of requiring hardware, now, through something called redirection/pipelining, we can modify where the input will come from. </p> <p>In addition to clarifying what the above means, I, personally, am interested in a Java-specific response. </p> <p>Simply put, there are three "common" ways of receiving user input in Java SO Source: <a href="http://stackoverflow.com/questions/17637032/bufferedreader-vs-console-vs-scanner">BufferedReader vs Console vs Scanner</a></p> <p>Basically, what I got from the above, is that the differences involve optimization for what you intend to do with the input and how the input is stored/treated, in terms of whether it is received as the ASCII Integer or whatever. </p> <p>My question is are all three of the above methods considered <strong>standard input</strong>? Is there a way of obtaining user input NOT through <strong>standard input</strong>? By user input I mean something the user inputs manually upon program execution, not transferring data from a file or anything like that. </p> <p>Furthermore, when receiving input in the above way, is it worth checking for null?</p> <p>Example:</p> <pre><code> Scanner a = new Scanner(System.in); String testInput = a.nextLine(); if (testInput == null) </code></pre> <p>How can something input by the user ever point to nothing in memory (i.e. null?) is this ever possible? </p>
<blockquote> <p>Was instructed, for a university-level assignment, to receive user input through "standard input". Google was a bit scarce as to what precisely this means.</p> </blockquote> <p>This would generally mean the input to the program you are writing will come from a file or from input the user types at the command line. If you are not familiar with terminal, this might be a good introduction for this aspect: <a href="https://help.ubuntu.com/community/UsingTheTerminal" rel="nofollow">https://help.ubuntu.com/community/UsingTheTerminal</a></p> <blockquote> <p>Basically, what I found was receiving user input was originally done via standard input methods (hardware). However, and this is where things get complicated, now the process has been abstracted. Instead of requiring hardware, now, through something called redirection/pipelining, we can modify where the input will come from.</p> </blockquote> <p>This information you provide here sounds like it comes from <a href="https://en.wikipedia.org/wiki/Standard_streams" rel="nofollow">Wikipedia's article on standard streams</a>. Please reread it, because it does answer your background questions quite well, in particular, reread the headings Background, Application, Standard Input, and Timeline. </p> <p>To clarify the part about pipelining/redirection a bit, try executing this command from terminal in a directory that contains some known file. Then, try to understand what it does either with Google or using <a href="http://www.linfo.org/man.html" rel="nofollow"><em>man</em></a> (its essentially 'pipelining' the result from a directory listing to grep as input to do a search).</p> <pre><code>ls | grep &lt;file&gt; </code></pre> <p>Or try this command and open the resulting file:</p> <pre><code>ls &gt; listings.txt </code></pre> <p>As for your Java specific questions, why not go to the source itself: <a href="https://docs.oracle.com/javase/tutorial/essential/io/index.html" rel="nofollow">https://docs.oracle.com/javase/tutorial/essential/io/index.html</a></p> <p>Also, I would advise you go beyond this and read a little from unix and c perspective with these links: <a href="http://www.linfo.org/standard_input.html" rel="nofollow">http://www.linfo.org/standard_input.html</a> <a href="http://www.umich.edu/~eecs381/handouts/basicCio.pdf" rel="nofollow">http://www.umich.edu/~eecs381/handouts/basicCio.pdf</a></p> <blockquote> <p>Furthermore, when receiving input in the above way, is it worth checking for null?</p> </blockquote> <p>I haven't used Java in sometime, but I'm guessing you won't need to, because you can't get out of the System.in without at least pressing Enter--which would be enough for input. Why not write some code and check it?</p> <p>For files and network inputs, I would imagine you could have failed transfers and so null is possible here. To handle this type of situation, you can use a try/catch or something like that. See the docs because you can also use <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html" rel="nofollow">try-with-resources</a>.</p>
Copy-Item is not working <p>I have a script that is finding a few files and the copying them. This is part of a psake build script.</p> <p>The command is:</p> <pre><code>Get-ChildItem -Path "$sourceFolder" -Include "*.ispac" -Recurse ` | Select-Object -ExpandProperty FullName ` | Copy-Item -Destination "$caseFolder\" -Force -Verbose </code></pre> <p>When I execute this, I get this for the message:</p> <pre><code>VERBOSE: Performing the operation "Copy File" on target "Item: C:\Source\TestSssisOne.ispac Destination: C:\Destination\TestSssisOne.ispac". </code></pre> <p>That sure looks like the files where copied. But they aren't. No errors. If I copy this command out to ISE and setup the variables, it copies no problem. I tried to just manually copy a single file, with explicit paths. Again, in script it does not copy, but in PS console or ISE it does.</p> <p>I have no idea what could be the problem. I've used Copy-Item in psake scripts. In fact, I copied the above code to a later task and it works! In the task where it isn't working I'm calling msbuild to build a solution.</p> <p>Any insight appreciated!</p>
<p>modify your code like this</p> <pre><code> Get-ChildItem -Path "$sourceFolder" -Include "*.ispac" -Recurse -File | foreach{Copy-Item $_.FullName -Destination (("$caseFolder\") + $_.Name) -Force -Verbose } </code></pre>
Vue Router Error <p>Trying set up Vue Router. Not sure what I am doing wrong. Getting the error </p> <p><code>Failed to mount component: template or render function not defined. (found in root instance)</code></p> <p>Again, I'm coming to Vue from React and while they are pretty similar there are small things that are different and there aren't as many Vue resources out there yet. </p> <p>I'm using the Webpack template and using single file components. One thing I didn't completely understand was this part in the documentation</p> <pre><code>// 1. Define route components. // These can be imported from other files const Foo = { template: '&lt;div&gt;foo&lt;/div&gt;' } const Bar = { template: '&lt;div&gt;bar&lt;/div&gt;' } </code></pre> <p>Is this just he same as me doing <code>import Foo from 'path/to/component/</code> ? </p> <p>Anyway, thanks for any and all help!</p> <p>Here is my <code>main.js</code> file</p> <pre><code>import Vue from 'vue' import App from './App' import QuizBuilder from '../src/components/QuizBuilder.vue' import ResourceInfo from '../src/components/ResourceInfo.vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [ { path: '/info', component: ResourceInfo }, { path: '/quiz-builder', component: QuizBuilder } ] const router = new VueRouter({ routes }) const app = new Vue({ router }).$mount('#app') </code></pre> <p>My <code>index.html</code> looks like this </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"&gt; &lt;title&gt;Digestible&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="app"&gt; &lt;router-view&gt;&lt;/router-view&gt; &lt;/div&gt; &lt;!-- built files will be auto injected --&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>Assuming you have the components properly, you still need a small update.</p> <p>When loading vue router as module system, the application should be initialized with the following way:</p> <pre><code>new Vue({ el: '#app', router, render: h =&gt; h(App) }); </code></pre>
Fragment doesn't fill screen properly <p>I'm instantiating a Fragment inside another Fragment. The inner fragment has its layout defined as <code>match_parent</code> for width and height. And their parent too.</p> <p>This is the code for main Fragment. CustomFragment which is inside is the inner Fragment. Its a regular fragment with a calendar.</p> <pre><code>public class CalendarFragment extends Fragment { ... public void onViewCreated( LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState ){ customFragment = new CustomFragment(); customFragment.setArguments( bundle ); FragmentTransaction transaction = getChildFragmentManager().beginTransaction(); transaction.add( R.id.calendar_container, customFragment ); transaction.commit(); ... } </code></pre> <p>When this fargment comes to life, the inner fragment which contains the calendar adjusts its height based on content of each calendar cell. Screenshot. Notice the empty space:</p> <p><a href="https://i.stack.imgur.com/o3CLR.png" rel="nofollow"><img src="https://i.stack.imgur.com/o3CLR.png" alt="enter image description here"></a> If both fragments have match_parent in its layout why this behavior occurs?</p>
<ol> <li>please make sure, your the container for second fragment (if any) is also <code>match_parent</code></li> <li>try give fragment different background color (ie. android:color/red) to check if fragment actually already full screen, but have transparent background. and your calendar view is only reside on small proportion of fragment area.</li> </ol>
Split column with tidyr with different lenghts <p>I want to separate a column with tidyr to extract the grade level. The Column looks like this:</p> <pre><code>School.Name School A ES SchoolB MS </code></pre> <p>The is no standard way the schools are named, so when I use separate </p> <pre><code>separate(DF, School.Name,c("School.Name","Number","Grade Level") </code></pre> <p>I get this</p> <pre><code>School.Name Number Grade Level School A ES SchoolB MS NA </code></pre> <p>Is there a way to tell tidyr to read from the right rather that from the left</p>
<p>try <code>?separate</code>:</p> <pre><code>separate(DF, School.name, c("School.Name","Number","Grade Level"), fill = "left") </code></pre> <p>Then you got result like :</p> <pre><code> School.Name Number Grade Level 1 school A ES 2 &lt;NA&gt; schoolB MS </code></pre> <p><strong>EDIT:</strong></p> <p>parameter <code>fill</code> controls when separated characters size doesn't match column size, optional <code>warn, right, left.</code></p> <ol> <li>Case 1: separated characters size <code>&lt;</code> column size</li> </ol> <p>e.g.</p> <pre><code>"schoolB MS" to C("A", "B", "C"), fill = "left" : &lt;NA&gt; schoolB MS "schoolB MS" to C("A", "B", "C"), fill = "right" : schoolB MS &lt;NA&gt; </code></pre> <ol start="2"> <li>Case 2: separated characters size <code>&gt;</code> column size</li> </ol> <p>e.g.</p> <pre><code>"schoolB MS" to C("A"), fill = "warn" : schoolB #default drop extra from the right </code></pre>
elif statement not working as expected <p>I'm trying to look through multiple sources to see which one has a specific entry.</p> <p>My input looks like:</p> <pre><code>json_str2 = urllib2.urlopen(URL2).read() u = json.loads(json_str2) #load all five results One = u['flightStatuses'][0] Two = u['flightStatuses'][1] Three = u['flightStatuses'][2] Four = u['flightStatuses'][3] Five = u['flightStatuses'][4] </code></pre> <p>My <code>if</code> statement works correctly and I get the correct result:</p> <pre><code>if One['flightNumber'] == str(FlEnd): fnumber = One['flightId'] print fnumber </code></pre> <p>But when I add the <code>elif:</code> the answer is wrong (nothing) even when the first statement is <code>True</code>.</p> <p>I don't understand why the <code>elif</code> doesn't work?</p> <pre><code># if statement checks each result to define flightId, needed for tracking. if One['flightNumber'] == str(FlEnd): fnumber = One['flightId'] elif Two['flightNumber'] == str(FlEnd): fnumber = Two['flightId'] print fnumber </code></pre>
<p>You should write this as a loop over the five flight statuses instead of using five variables and five conditions.</p> <pre><code>results = json.loads(urllib2.urlopen(URL2).read())['flightStstuses'] for result in results: if result['flightNumber'] == str(FlEnd): fnumber = result['flightId'] break else: fnumber = None print fnumber </code></pre>
1st principal component of 3 points on a line <p>I am a little bit confused on the first principal directions. Say I have three points in a two dimensional euclidean space: (1,1), (2,2), and (3,3) and I want to calculate the first principal component. </p> <p>First I see that the center is (2,2) so I move all points to the origin. Now (2,2) is like (0,0) and (1,1) is (-1,-1) and (3,3) is (1,1). This is the mean shift. Now, I know that the first principal component is transpose((sqrt(2)/2, sqrt(2)/2)) from matlab. But, how is it calculating this? What does this mean?</p> <p>Do you compute the covariance matrix then find the eigenvalues then the eigenvectors. This eigenvector is the direction? Then you normalize?</p> <p>So we have our points after the mean shift at (-1,-1), (0,0), and (1,1). We now compute the covariance matrix</p> <p>c(x,x) c(x,y)</p> <p>c(y,x) c(y,y) </p> <p>which is [0 1; 0 1] we then look at the largest eigenvalue 1 and compute the eigenvector which is [1;1]. Then we normalize so divide by sqrt(1^2 + 1^2)? </p>
<p>The steps you write is correct but you misunderstand some concepts. "Mean shift" part has no problem but you got it wrong about covariance matrix. Since the original data is in 2D, then the covariance matrix should between these two dimensions including all six values, that is (-1,0,1) in x axis and (-1,0,1) in y axis. So [0 1; 0 1] is not a correct answer.</p> <p>Suppose we already have the covariance matrix, we can use svd function in matlab to get the eigenvectors and eigenvalues. Eigenvector with the largest eigenvalue is not the direction but a new basis to represent the data. So if you multiply this eigenvector with original data, you can get a new representation of the data in a new coordinate system.</p> <p>I write a code in matlab to make my description easy to understand.</p> <pre><code>clear; % Original data x = [1,1;2,2;3,3]; x = x'; x = x - repmat(mean(x, 2), 1, size(x, 2)); figure('name','original data') plot(x(1,:),x(2,:),'*') axis([-5 5 -5 5]) % PCA rotate data sigma = x * x' / size(x, 2); [U, S, V] = svd(sigma); xRot = U' * x; figure('name','PCA data rotation') plot(xRot(1,:),xRot(2,:),'*') axis([-5 5 -5 5]) </code></pre>
Mysql query on Javascript <p>I'm trying to use Javascript, PHP and MySql all together and get some results. I've done something about it but it does not work as I expected. Hope there is someone to help me.</p> <p>Basically I've created a category table, which includes catID, catName, catDesc, and catPar.</p> <p>In this case I'm creating some main categories and sub-categories as well. Main categories don't have catPar values but if the category is the sub one, it gets main category ID in it as parent category. (Sub categories might have another sub as well)</p> <p>I've been created a query to bring main categories as a select list and bring sub categories with another query and javascript but it does not work as I expected (It's not creating another select list, just overwriting) and for the final part, I could not find any solution.</p> <p>When I do query and if there is a subcategory everything is ok but if there is no more subcategory select list is disappearing and I cannot select the final category.</p> <p>I'd like to be able to put the values (if does not contain another sub-category) in stable select options, which I named it <code>final</code> then start again from the main categories.</p> <p>Then, I will send them to database as multiple.</p> <p>Addition: I've tried to put some specific characters for the categories just before than their name, if they have a sub category but I could not do it.</p> <p>This is my <code>index.php</code></p> <pre><code>&lt;script&gt; function subs(str) { if (str == "") { return; } else { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (this.readyState == 4 &amp;&amp; this.status == 200) { document.getElementById("result").innerHTML = this.responseText; } }; xmlhttp.open("GET","select_sub.php?q="+str,true); xmlhttp.send(); } } &lt;/script&gt; &lt;?php $con = mysqli_connect('localhost','root','','test'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } ?&gt; &lt;form method="post" enctype="multipart/form-data"&gt; &lt;fieldset&gt; &lt;legend&gt;Add New Category&lt;/legend&gt; &lt;label for="category_name"&gt;Category Name&lt;/label&gt; &lt;input class="input250" type="text" name="category_name" value="" &gt; &lt;label for="category_description"&gt;Category Description&lt;/label&gt; &lt;input class="input350" type="text" name="category_description" value="" &gt; &lt;?php $select_mains="SELECT * FROM categoriestable WHERE catPar IS NULL"; $bring_mains = mysqli_query($con,$select_mains); if(mysqli_num_rows($bring_mains)&gt;0){ ?&gt; &lt;label for="category_main"&gt;Main Category&lt;/label&gt; &lt;select name="main_category" onchange="subs(this.value)"&gt; &lt;option value="0"&gt;Select a category&lt;/option&gt; &lt;?php while($main_categories = mysqli_fetch_array($bring_mains)) { echo "&lt;option value='".$main_categories['catID']."'&gt;".$main_categories['catName']."&lt;/option&gt;"; } ?&gt; &lt;/select&gt; &lt;?php } else {} ?&gt; &lt;div id="result"&gt;&lt;/div&gt; &lt;select multiple="true" name="final" id="final"&gt; &lt;option name="sub_category" id="cat" value="0" &gt;Test&lt;/option&gt; &lt;/select&gt; &lt;input type="submit" value="Add category"&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>and this is my <code>select_sub.php</code></p> <pre><code>&lt;?php $q = intval($_GET['q']); $con = mysqli_connect('localhost','root','','test'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } $selected_main_category="SELECT * FROM categoriestable WHERE catPar = '".$q."'"; ?&gt; &lt;?php $has_sub_cat = mysqli_query($con,$selected_main_category); if(mysqli_num_rows($has_sub_cat)&gt;0){ ?&gt; &lt;select id="sub_category" name="sub_category" onchange="subs(this.value)"&gt; &lt;option name="sub_category" id="cat" value="0"&gt;Select a sub category&lt;/option&gt; &lt;?php while($add_to_list = mysqli_fetch_array($has_sub_cat)) { echo "&lt;option value='".$add_to_list['catID']."'&gt;".$add_to_list['catName']."&lt;/option&gt;"; } ?&gt; &lt;/select&gt; &lt;?php } else { ?&gt; &lt;?php } ?&gt; </code></pre> <p>You can see the sample structure of database table below; <a href="https://i.stack.imgur.com/HJtfH.jpg" rel="nofollow">Sample database table</a></p> <p>Thank you very much from now.</p>
<p>The problem is that the ajax call returns nothing when the subcategory has no other subcategories, try sending an empty select list, for example:</p> <pre><code> &lt;?php }else { ?&gt; &lt;select id="sub_category" name="sub_category"&gt; &lt;option name="sub_category" id="cat" value="0"&gt;No subcategory&lt;/option&gt; &lt;/select&gt; &lt;?php } ?&gt; </code></pre> <p><strong>Edit</strong></p> <p>If you want to add the selected elements to the multiselect add a class to the selects with the categories and use a javascript function like the following </p> <pre><code>function addtoFinal(){ var elements=document.getElementsByClassName("clazz"); var opts=""; for(var i=0;i&lt;elements.length;i++){ opts+="&lt;option&gt;"+elements[i].value+"&lt;/option&gt;" } document.getElementById("final").innerHTML=opts; } </code></pre>
Bash loop over files in hdfs directory <p>I need to loop over all csv files in a Hadoop file system. I can list all of the files in a HDFS directory with</p> <pre><code>&gt; hadoop fs -ls /path/to/directory Found 2 items drwxr-xr-x - hadoop hadoop 2 2016-10-12 16:20 /path/to/directory/tmp -rwxr-xr-x 3 hadoop hadoop 4691945927 2016-10-12 19:37 /path/to/directory/myfile.csv </code></pre> <p>and can loop over all files in a standard directory with </p> <pre><code>for filename in /path/to/another/directory/*.csv; do echo $filename; done </code></pre> <p>but <strong>how can I combine the two?</strong> I've tried</p> <pre><code>for filename in `hadoop fs -ls /path/to/directory | grep csv`; do echo $filename; done </code></pre> <p>but that gives me some nonsense like </p> <pre><code>Found 2 items drwxr-xr-x hadoop hadoop 2 2016-10-12 .... </code></pre>
<p>This should work</p> <pre><code>for filename in `hadoop fs -ls /path/to/directory | awk '{print $NF}' | grep .csv$ | tr '\n' ' '` do echo $filename; done </code></pre>
self executing function assigned to a variable <p>I have found an example to run a server using Express but I don't understand 'why' it works.</p> <p>The code is the following:</p> <pre><code>var server = app.listen(3000, function() { console.log('Listening on port 3000'); }); </code></pre> <p>The result of this var assignment is a process listening at port 3000, but I am assigning something not executing.</p> <p>What am I missing?</p> <p>Cheers, Giovanni</p>
<p>In Javascript <code>app.listen()</code> is a method call that executes the <code>listen()</code> method on the <code>app</code> object. The return value from that method call is then assigned to your <code>server</code> variable.</p> <p>So, putting it all together with your code:</p> <pre><code>var server = app.listen(3000, function() { console.log('Listening on port 3000'); }); </code></pre> <p>The sequence of events is this:</p> <ol> <li>Declare a new variable named <code>server</code> in the current scope.</li> <li>Call the <code>listen()</code> method on the <code>app</code> object with <code>app.listen(...)</code>.</li> <li>Pass that method two arguments, <code>3000</code> as the port number and a callback function that will be called when the <code>.listen()</code> method finishes.</li> <li>Whatever value the <code>app.listen()</code> method returns is then assigned to the <code>server</code> variable.</li> </ol> <blockquote> <p>The result of this var assignment is a process listening at port 3000, but I am assigning something not executing.</p> </blockquote> <p>Actually, you're doing both. You're calling the <code>app.listen()</code> method and then assigning the return result to the <code>server</code> variable. </p> <p>The phrase <code>self executing</code> doesn't really apply here. The parens after <code>app.listen()</code> make this a function call which will execute the <code>.listen()</code> method on the <code>app</code> object.</p>
Get rid of duplicate items in ComboBox from a BLOB database <p>I am getting duplicate items in a combobox that displays saved BLOBs in my database.</p> <pre><code>Private Sub refreshBLOBList() Dim getBLOBListCommand As New SqlCommand( _ "SELECT DISTINCT FileName FROM DocumentStorage", dbConnection) Dim reader As SqlDataReader getBLOBListCommand.Connection.Open() reader = getBLOBListCommand.ExecuteReader While reader.Read BLOBList.Items.Add(reader(0)) End While reader.Close() getBLOBListCommand.Connection.Close() BLOBList.SelectedIndex = 0 End Sub </code></pre> <p>In this block I refresh the combobox, but DISTINCT doesn't get rid of the dupes in the combobox. The weird thing is, when I query it and put it in a datagridview I get the dataset I want.</p> <p>Any suggestions?</p>
<p>I needed to call BLOBlist.items.clear() before I added items otherwise I will add the distinct ones again.</p>
Adding Position: fixed; ruins the header <p>When I add:</p> <pre><code>* { margin: 0; padding: 0; position: fixed; } </code></pre> <p>the whole banner messes up and ends with a piece of the code. I've been experimenting on popular websites, and when this one came along I've been having a lot of trouble, but here's the code: <a href="http://paste.ofcode.org/tDEanvxUuk7NAv9ttE3avV" rel="nofollow">http://paste.ofcode.org/tDEanvxUuk7NAv9ttE3avV</a></p> <p>How do I make it so the <code>position: fixed;</code> doesn't ruin it?</p>
<p>Wooahh you've added position fixed onto every single element of the page with this line:</p> <pre><code>* { margin: 0; padding: 0; position: fixed; } </code></pre> <p>You should only add position fixed to the element you want to be fixed. If its the top nav then something like this.</p> <pre><code>nav#top { position: fixed; } </code></pre>
RESTFul Web Service with Ajax <p>I am new to web services and I am trying to use RESTFul webservices. I am trying to pass parameter to RESTFul web server in Java from ajax. Here is what I did </p> <p>index.html </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Insert title here&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="add"&gt; Add : &lt;input type="text" name="name" id="name"&gt; &lt;input type="submit" id="submitAdd"&gt; &lt;/div&gt; &lt;/body&gt; &lt;script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function ()) { $("#submitAdd").click(function() { var data = { name : $("#name").val() }; $.ajax({ type: "GET", url: "http://localhost:8080/Example/Rest/controller/return", data: data, dataType : "json", success : function(rdata) { } }); }) }) &lt;/script&gt; &lt;/html&gt; </code></pre> <p>Controller.java</p> <pre><code>package com.controller; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; @Path("/controller") public class Controller { @GET @Path("/return") @Consumes("application/json") public void add(String msg) { System.out.println("name "+ msg); } } </code></pre> <p>Web.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"&gt; &lt;display-name&gt;StockMonitor&lt;/display-name&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;welcome-file&gt;index.htm&lt;/welcome-file&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;welcome-file&gt;default.html&lt;/welcome-file&gt; &lt;welcome-file&gt;default.htm&lt;/welcome-file&gt; &lt;welcome-file&gt;default.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;servlet&gt; &lt;servlet-name&gt;Example&lt;/servlet-name&gt; &lt;servlet-class&gt;com.sun.jersey.server.impl.container.servlet.ServletAdaptor&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;com.sun.jersey.config.property.packages&lt;/param-name&gt; &lt;param-value&gt;com.controller&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;Example&lt;/servlet-name&gt; &lt;url-pattern&gt;/Rest/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt; </code></pre> <p>Here is the file structure</p> <pre><code> Example src -&gt;com.controller -&gt;Controller.java WebContent -&gt;META_INF -&gt;WEB-INF -&gt;index.html </code></pre> <p>The jars that I am using are - </p> <p>all jars in <code>Jersey JAX-RS 2.0 RI bundle</code> from <a href="https://jersey.java.net/download.html" rel="nofollow"><a href="https://jersey.java.net/download.html" rel="nofollow">https://jersey.java.net/download.html</a></a></p> <p>When I enter this in the browser <a href="http://localhost:8080/Example/Rest/controller/return" rel="nofollow">http://localhost:8080/Example/Rest/controller/return</a> I get <code>HTTP Status 404 Error</code>. I am unable to fix it . Can anyone please tell me whats the mistake ?</p>
<p>You are getting 404 because <code>/Rest</code> is no where registered in any paths</p> <ol> <li>Your context path is <code>/Example</code></li> <li>Then you controller is mapped to <code>/controller</code></li> </ol> <p>So You don't have a mapping to resolve <code>/Rest</code> since your controller is is bound to <code>/controller</code>URI path </p> <p>Either remove the <code>/Rest</code> for your URL and update the servlet mapping in web.xml</p> <pre><code>&lt;servlet-mapping&gt; &lt;servlet-name&gt;Example&lt;/servlet-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p><strong>OR</strong></p> <p>Add the <code>/Rest</code> to your controller path mapping</p> <pre><code>@Path("/Rest/controller") public class Controller { </code></pre>
missing rows when exporting query in Ms Access to MS Excel - VBA <p>I have a query in Ms Access that runs with 227,288 rows.<br> I made a command button which can export the query into excel. I've searched and found this code </p> <pre><code>Private Sub Export_Click() Dim rst As DAO.Recordset Dim excelApp As Object Dim sht As Object Dim fldHeadings As DAO.Field Set rst = CurrentDb.OpenRecordset("acct file", dbOpenDynaset) Set excelApp = CreateObject("Excel.Application") On Error Resume Next Set Wbk = excelApp.Workbooks.Open(book1) If Err.Number &lt;&gt; 0 Or Len(book1) = 0 Then Set Wbk = excelApp.Workbooks.Add Set sht = Wbk.Worksheets("CSC Landed") If Len(sheet1) &gt; 0 Then sht.Name = Left("acct file", 34) End If End If Set sht = Wbk.Worksheets.Add If Len(sheet1) &gt; 0 Then sht.Name = Left("acct file", 34) End If On Error GoTo 0 excelApp.Visible = True On Error GoTo Errorhandler For Each fldHeadings In rst.Fields excelApp.ActiveCell = fldHeadings.Name excelApp.ActiveCell.Offset(0, 1).Select Next rst.MoveFirst sht.Range("A2").CopyFromRecordset rst sht.Range("1:1").Select excelApp.Selection.Font.Bold = True With excelApp.Selection .HorizontalAlignment = -4108 .VerticalAlignment = -4108 .WrapText = False With .Font .Name = "Arial" .Size = 10 End With End With excelApp.ActiveSheet.Cells.EntireColumn.AutoFit With excelApp.ActiveWindow .FreezePanes = False .ScrollRow = 1 .ScrollColumn = 1 End With sht.Rows("2:2").Select excelApp.ActiveWindow.FreezePanes = True With sht .Tab.Color = RGB(255, 0, 0) .Range("A1").Select End With rst.Close Set rst = Nothing Exit Sub Errorhandler: DoCmd.SetWarnings True MsgBox Err.Description, vbExclamation, Err.Number Exit Sub End Sub </code></pre> <p>however, when export is done it only exports 496 rows. I've search and tried different attempts, still the rows I'm getting is only 496.<br> I'm also looking into preferences in vb </p> <p>I'm very new in access. I've done several research but still I couldn't do it.<br> Thanks in advance</p> <p><a href="https://i.stack.imgur.com/AbPmg.png" rel="nofollow">enter image description here</a></p>
<p>Assuming that you're running the Export_Click code from within Microsoft Access, you can use the following code to invoke the "Output To" action of the DoCmd object:</p> <pre><code>Private Sub Export_Click() DoCmd.OutputTo acOutputQuery, "acct file", acFormatXLSX, , True End Sub </code></pre>
Why are file descriptors 1 and 2 ready for reading on manual input but not so on input redirection? <p>This question is a follow-up of '<a href="http://stackoverflow.com/q/39989647/1175080">Why does select() say that stdout and stderr are ready for reading and stdin is ready for writing?</a>' which got closed as a duplicate of '<a href="http://stackoverflow.com/q/7383803/1175080">Writing to stdin and reading from stdout (UNIX/LINUX/C Programming)</a>'.</p> <p>While that question explains why we can read from file descriptors meant for stdout and stderr, the current question is different. This question is concerned about why stdout and stderr are ready for reading in a program while entering input manually from terminal but not so while redirecting standard input to the program.</p> <p>Here is the code to reproduce the behavior. The following program attempts to check if stdin, stdout and stderr is ready for reading.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;sys/select.h&gt; int main(void) { struct timeval tv; fd_set fds; int fd; tv.tv_sec = 10; tv.tv_usec = 0; FD_ZERO(&amp;fds); FD_SET(0, &amp;fds); FD_SET(1, &amp;fds); FD_SET(2, &amp;fds); select(3, &amp;fds, NULL, NULL, &amp;tv); for (fd = 0; fd &lt; 3; fd++) { if (FD_ISSET(fd, &amp;fds)) { printf("fd %d ready\n", fd); } } printf("tv: %ld seconds %ld microseconds\n", tv.tv_sec, tv.tv_usec); return 0; } </code></pre> <p>If I wait for about 2 seconds and enter some data in standard input, the <code>select()</code> call returns and this is the output.</p> <pre><code>$ gcc readselect.c &amp;&amp; ./a.out hi fd 0 ready fd 1 ready fd 2 ready tv: 8 seconds 222132 microseconds </code></pre> <p>However, if I redirect standard input to my program, then the program shows that only stdin is ready for reading.</p> <pre><code>$ gcc readselect.c &amp;&amp; (sleep 2; echo hi) | ./a.out fd 0 ready tv: 7 seconds 994713 microseconds </code></pre> <p>Why does the behavior change now? Why does the program no longer say that stdout and stderr are also ready for reading like it did in the earlier example?</p>
<p>When you don't redirect them, file descriptors 0, 1 and 2 are all your terminal. And you can read from or write to any of them - try it! (Strictly speaking, the file descriptor is not the terminal, it just refers to the terminal)</p> <p>When you type stuff in your terminal, your terminal is ready for reading, so all FDs 0, 1 and 2 are ready for reading because they are all the same terminal that you typed stuff in.</p> <p>When you redirect input (file descriptor 0), FD 0 instantly becomes ready for reading even if you don't type stuff, because it's not waiting for you to type stuff. So your program sees that FD 0 is ready, reads FD 0, then exits. FD 1 and 2 <strong>would</strong> become ready if you typed stuff while the program was running, but you never got a chance to do that because your program exited straight away.</p>
No suitable HttpMessageConverter found error while executing rest service that takes multipart parameters <p>I am using Spring Integration in my project. I am trying to execute a rest service which takes multipart/formdata input parameters. I am using int-http:outbound-gateway to execute rest service. The following is the code:</p> <pre><code>&lt;int:channel id="PQcreateAttachment-Rest-Channel" /&gt; &lt;int:chain input-channel="PQcreateAttachment-Rest-Channel" output-channel="PQcreateAttachment-StoredProcedure-Router" &gt; &lt;int:header-filter header-names="accept-encoding"/&gt; &lt;int:service-activator ref="httpOutboundGatewayHandler" method="buildMultipartHttpOutboundGatewayRequest" /&gt; &lt;int-http:outbound-gateway url-expression="headers.restResourceUrl" http-method-expression="headers.httpMethod" extract-request-payload="true" &gt; &lt;/int-http:outbound-gateway&gt; &lt;int:service-activator ref="msgHandler" method="buildMessageFromExtSysResponse" /&gt; &lt;/int:chain&gt; </code></pre> <p>But I am getting the following error when I execute the above code.</p> <pre><code>Caused by: org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.integration.message.GenericMessage] and content type [application/x-java-serialized-object] at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:665) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:481) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:460) at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:409) at org.springframework.integration.http.outbound.HttpRequestExecutingMessageHandler.handleRequestMessage(HttpRequestExecutingMessageHandler.java:372) ... 121 more </code></pre> <p>Here is the java code that prepares my multipart request:</p> <pre><code>public Message&lt;?&gt; buildMultipartHttpOutboundGatewayRequest(Message&lt;?&gt; inMessage) throws Exception{ logger.debug(" ************** buildMultipartHttpOutboundGatewayRequest Start *************************"); String inMsgPayload = (String)inMessage.getPayload(); SOAXml soaXml = parseSOAXml(inMsgPayload); String restURL = null; String contentType = null; String acceptHdr = null; String userId = null; String password = null; String businessAreaName = null; String typeName = null; String attachmentLocation = null; String httpMethod = null; Message&lt;?&gt; outMessage = null; MessageHeaders inMsgHdrs = null; MessageBuilder&lt;?&gt; msgBuild = null; String authorization = null; //TODO: File location needs to be changed to standard one String fileLocation = "C:\\source.xml"; //if we reach here means, it is AWD system restURL = getAwdSOAService(soaXml); Document document = XmlParserUtil.convertString2Document(inMsgPayload); userId = XmlParserUtil.getNodeValue(document,"//userId"); password = XmlParserUtil.getNodeValue(document,"//PQcreateAttachment/password"); businessAreaName = XmlParserUtil.getNodeValue(document,"//businessAreaName"); typeName = XmlParserUtil.getNodeValue(document,"//typeName"); httpMethod = XmlParserUtil.getNodeValue(document,"//METHOD"); attachmentLocation = XmlParserUtil.getNodeValue(document,"//attachmentLocation"); //Construct source xml //Creating document Document sourceDocument = DocumentHelper.createDocument(); Element sourceInstance = sourceDocument.addElement("createSourceInstance"); sourceInstance.addAttribute("xmlns", "http://www.dsttechnologies.com/awd/rest/v1"); Element orderItem=sourceInstance.addElement("businessAreaName"); orderItem.setText("SAMPLEBA"); Element orderItemDesc=sourceInstance.addElement("typeName"); orderItemDesc.setText("SAMPLEST"); // create source xml file XmlParserUtil.createXMLFileUsingDOM4J(sourceDocument, fileLocation); authorization = getBasicAuthorization(userId,password); Resource source = new ClassPathResource(fileLocation); Resource attachment = new ClassPathResource(attachmentLocation); Map&lt;String, Object&gt; multipartMap = new HashMap&lt;String, Object&gt;(); multipartMap.put("source", source); multipartMap.put("attachment", attachment); logger.info("Created multipart request: " + multipartMap); inMessage = buildMessageForMultipart(multipartMap); // contentType = csProps.getHttpAwdContentTypeValue(); acceptHdr = csProps.getHttpAwdAcceptTypeValue() ; // authorization = getBasicAuthorization(soaXml.getUserid(),decriptPassword(soaXml.getPassword())); inMsgHdrs = inMessage.getHeaders(); msgBuild = MessageBuilder.withPayload(inMessage).copyHeaders(inMsgHdrs); msgBuild.removeHeader("Content-Encoding"); msgBuild.removeHeader("accept-encoding"); msgBuild.setHeader(csProps.getHttpUrlHdr(), restURL); msgBuild.setHeader(csProps.getHttpMethodHdr(), httpMethod); msgBuild.setHeader(csProps.getHttpAuthorizatonHdr(),authorization ); // msgBuild.setHeader(csProps.getHttpContentTypeHdr(), contentType); // msgBuild.setHeader(csProps.getHttpAcceptTypeHdr(),acceptHdr); outMessage = msgBuild.build(); logger.debug(" ************** buildHttpOutboundGatewayRequest End*************************"); logger.debug(outMessage); logger.debug(" ************************************************************************"); return outMessage; } </code></pre> <p>Any ideas on what's wrong here?</p>
<p>Your problem is because you wrap one message to another. </p> <p>What your <code>buildMessageForMultipart(multipartMap);</code> does? </p> <p>I'm sure the simple map as payload and those header would be enough. </p> <p>Not sure what is the point to wrap one message to another.</p>
tvOS: Anyway to display a subtitle outside of the AVPlayer? <p>So the scenario is that there is a view where the user can enable/disable subtitles in an app I'm helping to develop. </p> <p>On that view there is a sample text saying "This is what captions look like", and at the moment it's just a basic, unstyled <code>UILabel</code>. Ideally I would like it to be styled in a similar manner to how the user has customized their captions in the System Settings.</p> <p>Is this possible in any way? I've envisioned two possible method:</p> <ol> <li><p>Create an AVPlayer instance and a .vtt file with the text, load it into the view and pause the player. I'm not sure this is possible with a sample video (and it would somehow have to be transparent as there is an image behind the sample sub text).</p></li> <li><p>Somehow get all the styling (font, size, background color, etc) the user has set for their subtitle and create an attributed string to match that</p></li> </ol> <p>Method 2 seems like the most feasible way, but I don't know if we have access to those settings in code.</p>
<p>So I figured it out! It basically makes use a combination of the <a href="https://developer.apple.com/reference/mediaaccessibility/1658096-media_accessibility_function" rel="nofollow">Media Accessibility API</a>, which allows you to get the values the user has chosen for their captions/subtitle settings, Attributed Strings, and a subclass <code>UILabel</code> (although this could <em>maybe</em> be substituted with a <code>UITextView</code> as that will allow you to set it's <code>UIEdgeInsets</code> natively)</p> <p>So, first, the subclass is to allow the <code>UILabel</code> to be inset. This is because captions can have a background color AND a text highlight color and without the inset, the text highlight is all you see. So the function the subclass is simple:</p> <pre><code>class InsetUILabel: UILabel { override func drawTextInRect(rect: CGRect) { let inset: CGFloat = 15 let insets: UIEdgeInsets = UIEdgeInsets(top: inset, left: inset/2, bottom: inset, right: inset/2) super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets)) } } </code></pre> <p>And for generating the actual label. This uses a label called <code>textSample</code>, but you can obviously make it a little more general.</p> <pre><code>import MediaAccessibility func styleLabel(sampleText: String) { let domain = MACaptionAppearanceDomain.User // Background styling let backgroundColor = UIColor(CGColor: MACaptionAppearanceCopyWindowColor(domain, nil).takeRetainedValue()) let backgroundOpacity = MACaptionAppearanceGetWindowOpacity(domain, nil) textSample.layer.backgroundColor = backgroundColor.colorWithAlphaComponent(backgroundOpacity).CGColor textSample.layer.cornerRadius = MACaptionAppearanceGetWindowRoundedCornerRadius(domain, nil) // Text styling var textAttributes = [String:AnyObject]() let fontDescriptor = MACaptionAppearanceCopyFontDescriptorForStyle(domain, nil, MACaptionAppearanceFontStyle.Default).takeRetainedValue() let fontName = CTFontDescriptorCopyAttribute(fontDescriptor, "NSFontNameAttribute") as! String let fontColor = UIColor(CGColor: MACaptionAppearanceCopyForegroundColor(domain, nil).takeRetainedValue()) let fontOpacity = MACaptionAppearanceGetForegroundOpacity(domain, nil) let textEdgeStyle = MACaptionAppearanceGetTextEdgeStyle(domain, nil) let textHighlightColor = UIColor(CGColor: MACaptionAppearanceCopyBackgroundColor(domain, nil).takeRetainedValue()) let textHighlightOpacity = MACaptionAppearanceGetBackgroundOpacity(domain, nil) let textEdgeShadow = NSShadow() textEdgeShadow.shadowColor = UIColor.blackColor() let shortShadowOffset: CGFloat = 1.5 let shadowOffset: CGFloat = 3.5 switch(textEdgeStyle) { case .None: textEdgeShadow.shadowColor = UIColor.clearColor() case .DropShadow: textEdgeShadow.shadowOffset = CGSize(width: -shortShadowOffset, height: shortShadowOffset) textEdgeShadow.shadowBlurRadius = 6 case .Raised: textEdgeShadow.shadowOffset = CGSize(width: 0, height: shadowOffset) textEdgeShadow.shadowBlurRadius = 5 case .Depressed: textEdgeShadow.shadowOffset = CGSize(width: 0, height: -shadowOffset) textEdgeShadow.shadowBlurRadius = 5 case .Uniform: textEdgeShadow.shadowColor = UIColor.clearColor() textAttributes[NSStrokeColorAttributeName] = UIColor.blackColor() textAttributes[NSStrokeWidthAttributeName] = -2.0 default: break } textAttributes[NSFontAttributeName] = UIFont(name: fontName, size: (textSample.font?.pointSize)!) textAttributes[NSForegroundColorAttributeName] = fontColor.colorWithAlphaComponent(fontOpacity) textAttributes[NSShadowAttributeName] = textEdgeShadow textAttributes[NSBackgroundColorAttributeName] = textHighlightColor.colorWithAlphaComponent(textHighlightOpacity) textSample.attributedText = NSAttributedString(string: sampleText, attributes: textAttributes) } </code></pre> <p>Now the text highlight section makes use of shadows, with values I think look pretty good, but you might want to tweak them a tiny bit. Hope this helps!</p>
How would you render this simple UI using Ract js? <p>I am new to React and I want to render the UI shown in the picture. </p> <p>Description: The UI consists of two main components the sidenav and the display container. The side nav shows the title and the number of questions/answers pairs in for that given tab. When the user clicks on a tab of the side nav, the display container outputs the selected tab as a title with the questions/answers pairs, see api.</p> <p>EX: the user clicks tab2 on the side nav, the display container will show Tab2 </p> <p>Question C Answer to Question C</p> <p>Question D Answer to Question D</p> <p>Question E Answer to Question E</p> <p>And the side nav tab 2 will display 3, since there are 3 question/answer pairs. </p> <p>[IMG]<a href="http://imgur.com/fR4DVoP[/IMG]" rel="nofollow">http://imgur.com/fR4DVoP[/IMG]</a> <a href="http://imgur.com/fR4DVoP" rel="nofollow">http://imgur.com/fR4DVoP</a></p> <p>The data will be fetched from an api in the json format [ { 'Tab1' : [ { 'question':'QuestionA', 'answer':'Answer to Question A' }, { 'question':'QuestionB', 'answer':'Answer to Question B' } ], 'Tab2' : [ { 'question':'QuestionC', 'answer':'Answer to Question C' }, { 'question':'QuestionD', 'answer':'Answer to Question D' }, { 'question': 'QuestionE', 'answer': 'Answer to Question E' } ] //... tab3, tab4, an so on... }</p>
<p>Had you read reac-router tutorial ? if not here's the <a href="https://github.com/reactjs/react-router-tutorial/tree/master/lessons/01-setting-up" rel="nofollow">link</a>.</p> <p>Please read it careful, after that, you will have a good understanding how to acomplish your requirement using react router Links in the easy way.</p> <p>Or checkout this repo <a href="https://github.com/juavidn/starterkit" rel="nofollow">Starter Kit</a> as starting point </p>
Using Hour and Minutes in Comparison <p>I have a table that has date and hours and i am looking to get in my <code>output &gt; &gt;</code> all with a particular date and hour and minutes of that day. </p> <p>A particular person on the table can have a <code>date_added</code> of <code>10/12/2016 9:38:04 PM</code> </p> <p>I want to pull all who have a date added of <code>10/12/2016</code> after <code>9:25:00PM</code>. I have tried different things but nothing worked, see below </p> <p><code>s.date_added &gt;= '2016-12-10 9:25:04 PM' s.date_added &gt;= '12/10/2016 09:00:00 AM' convert(s.date_added) &gt;= '10/12/2016 9:25:04 PM'.</code> </p> <p>I am using sql. I just want a code that will give me all those on a table that have a specific date added on the date added column. I am not trying to format, just get an output</p>
<p>set date to variable datetime before</p> <pre><code> declare @dateParam datetime set @dateParam ='2016-12-10 9:25:04 PM' s.date_added &gt;= @dateParam s.date_added &gt;= @dateParam </code></pre> <p>example comparison with just hour</p> <pre><code> if datepart(hh, @dateParam) &gt;= datepart(hh, s.date_added) print 'True' else print 'False' </code></pre>
How to sequentially execute resolve for parent's route and then for children routes? <p>Here is my simplified routes for angular2 project:</p> <pre><code>export const ROUTES: Routes = [ { path: "user/:user_id", component: UserAuthComponent, resolve: { _auth: UserAuthResolver }, children: [ { path: "", component: UserComponent, resolve: { user: UserResolver } }, // .... many more routes that require authentication cookie ] } ] </code></pre> <p>where <code>UserAuthResolver</code> makes <code>GET</code> request to server to set authentication cookie (which is required for <code>UserResolver</code> as well as all children routes resolver (not shown here) to succeed).</p> <p>But it seems that angular2 doesn't sequentially execute the <code>resolve</code> in parent route and <code>resolve</code> in <code>children</code> routes but instead, it races all the 'relevant' <code>resolve</code>. Therefore, very often, the above code will alert authentication errors.</p> <p>Is there a way to work around this?</p> <p>FYI, I cannot put <code>UserAuthResolver</code>, say, inside <code>UserComponent</code> because then, it means duplicating the 'authentication' code all over the places where it is required.</p> <hr> <p>Edit: This thing is apprently called, <code>nested resolve</code>. In short, how do I deal with nested resolve in angular2? In Angular1, it seemed <a href="http://stackoverflow.com/questions/25333092/ui-router-sequential-resolve-of-parent-and-child-states">possible</a>.</p>
<p>Apparently, this was a <a href="https://github.com/angular/angular/issues/12148" rel="nofollow">known bug</a> and is <a href="https://github.com/angular/angular/issues/12032" rel="nofollow">fixed</a> in new <strong>2.1.0</strong> release. </p> <p>I've confirmed that this release indeed solves the issue.</p>
Placing Labels programmatically over an ImageView <p>I'm making an app to solve sudokus, so in the app I'm using an Imageview that displays an empty 9x9 grid which I've placed within a relative layout. I'm trying to create the interface programmatically, so what I want to know is how can I places labels on top of the Imageview so that they match the locations of the squares of the grid. I know that the labels can be on top of Imageview, but just not how to get them into place. Does Xamarin provide a way to accomplish this as all I've found is how to use alignment methods with the relative layout.</p> <p>Here's code my so far:</p> <pre><code>public class GridActivity : Activity { // Global Variables Button startButton; Button nextButton; RelativeLayout.LayoutParams startButtonParamsPortrait; RelativeLayout.LayoutParams startButtonParamsLandscape; RelativeLayout.LayoutParams nextButtonParamsPortrait; RelativeLayout.LayoutParams nextButtonParamsLandscape; protected override void OnCreate(Bundle savedInstanceState) { // Don't want the action bar to show, find it unnecessary, so gonna hide it. ActionBar.Hide(); base.OnCreate(savedInstanceState); // Create your application here // get the initial orientation var surfaceOrientation = WindowManager.DefaultDisplay.Rotation; RelativeLayout layoutBase = new RelativeLayout(this); layoutBase.LayoutParameters = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); layoutBase.SetPadding(100, 100, 100, 100); // Adding a Imageview to display the sudoku grid ImageView grid = new ImageView(this); grid.LayoutParameters = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); grid.Visibility = ViewStates.Visible; grid.SetBackgroundResource(Resource.Drawable.SudokuGrid); grid.Id = 1; layoutBase.AddView(grid); // Adding a button that will be used to step through the "AI"'s solution nextButton = new Button(this) { Text = "Next" }; nextButton.Id = 2; // Adding a button that will be used to start the "AI" to solve the puzzle startButton = new Button(this) { Text = "Start" }; startButton.Id = 3; // Layout Parameters for Portrait mode // nextButton nextButtonParamsPortrait = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); nextButtonParamsPortrait.AddRule(LayoutRules.AlignParentBottom); nextButtonParamsPortrait.AddRule(LayoutRules.AlignParentRight); // startButton startButtonParamsPortrait = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); startButtonParamsPortrait.AddRule(LayoutRules.AlignParentBottom); startButtonParamsPortrait.AddRule(LayoutRules.LeftOf, nextButton.Id); // Layout Parameters for Landscape mode // startButton startButtonParamsLandscape = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); startButtonParamsLandscape.AddRule(LayoutRules.AlignParentRight); // nextButton nextButtonParamsLandscape = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); nextButtonParamsLandscape.AddRule(LayoutRules.AlignParentRight); nextButtonParamsLandscape.AddRule(LayoutRules.Below, startButton.Id); // Add labels in the location of the squares // Depending on the initial orientation, the buttons will placed at different locations if (surfaceOrientation == SurfaceOrientation.Rotation0 || surfaceOrientation == SurfaceOrientation.Rotation180) { // The screen is in Portrait mode startButton.LayoutParameters = startButtonParamsPortrait; nextButton.LayoutParameters = nextButtonParamsPortrait; } else { // The screen is in Landscape mode startButton.LayoutParameters = startButtonParamsLandscape; nextButton.LayoutParameters = nextButtonParamsLandscape; } // Add the buttons to the layout layoutBase.AddView(startButton); layoutBase.AddView(nextButton); // Display the layout to the screen SetContentView(layoutBase); } public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig) { base.OnConfigurationChanged(newConfig); if (newConfig.Orientation == Android.Content.Res.Orientation.Portrait) { startButton.LayoutParameters = startButtonParamsPortrait; nextButton.LayoutParameters = nextButtonParamsPortrait; } else if (newConfig.Orientation == Android.Content.Res.Orientation.Landscape) { startButton.LayoutParameters = startButtonParamsLandscape; nextButton.LayoutParameters = nextButtonParamsLandscape; } } </code></pre>
<p>You can use Absolute layout to position label over other children (your grid) of the layout (has to be older child).</p>
php convert user input time to hh:mm:ss <p>I have an input field for time of day which is handled by a php script.</p> <p>I want the user to be able to enter things like:</p> <pre><code>6PM 6:30 520 1520 3p </code></pre> <p>and get out a valid time for mysql:</p> <pre><code>06:00:00 06:30:00 05:20:00 15:20:00 15:00:00 </code></pre> <p>how can I do this?</p> <p>edit: What I've tried so far:</p> <pre><code>$t = date('H:i:s', strtotime($input)); </code></pre> <p>and</p> <pre><code>$t = new DateTime($input); echo $t-&gt;format('H:i:s'); </code></pre> <p>either one fails when the input isn't exactly as php expects it.</p>
<p>jQuery Timepicker is a plugin to help users easily input time entries (<a href="http://www.jqueryscript.net/tags.php?/Time%20Picker/" rel="nofollow">http://www.jqueryscript.net/tags.php?/Time%20Picker/</a>)</p>
ActiveRecord mapping to table name with schema name as prefix <p>Has anyone experienced this issue on mapping table in ActiveRecord when table name need a schema name as a prefix (oracle)? </p> <ol> <li><p>Gemfile</p> <pre><code>gem 'activerecord', '4.2.4' gem 'activerecord-oracle_enhanced-adapter', '1.6.7' .... </code></pre></li> <li><p>db_helper.rb</p> <pre><code>class Student &lt; ActiveRecord::Base self.abstract_class = true self.table_name_prefix = 'OPT_ABC.' self.table_name = 'STUDENT' def self.list_student puts Student.take(1) #testing end end </code></pre></li> <li><p>The actual table name looks like: </p> <pre><code>SELECT * FROM OPT_ABC.STUDENT; </code></pre></li> <li><p>I am able to connect to the database instance, but when the code gets line:</p> <pre><code>puts Student.take(1) # SELECT * FROM STUDENT LIMIT 1 </code></pre> <p>I get the following error: </p> <pre><code>ActiveRecord::StatementInvalid: table or view does not exist: SELECT "STUDENT".* FROM "STUDENT" </code></pre></li> </ol> <p>I am looking for solution on how to handle 'OPT_ABC." table prefix. Please share your solution.</p>
<p>It looks like the problem is that you're trying to use both <code>self.table_name_prefix=</code> and <code>self.table_name=</code> together when you should be using one OR the other.</p> <p>First let's consider how both <code>self.table_name_prefix=</code> and <code>self.table_name=</code> work.</p> <hr> <h3>self.table_name_prefix=</h3> <p>According to the <a href="http://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-table_name" rel="nofollow">documentation</a>, <code>self.table_name_prefix=</code> works by prepending the passed in value to the table name that ActiveRecord automatically generates based off of the name of the class.</p> <p>So, if the class name is <code>Student</code> and you do <code>self.table_name_prefix = 'OPT_ABC.'</code>, your table name will be <code>OPT_ABC.STUDENTS</code>. Note that the generated table name is plural (and ends in an <code>s</code>).</p> <h3>self.table_name=</h3> <p>According to the <a href="http://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-table_name-3D" rel="nofollow">documentation</a>, <code>self.table_name=</code> sets the table name explicitly. This means that it completely overrides the table name to the value that you pass in.</p> <p>So, if you do <code>self.table_name = 'OPT_ABC.STUDENT'</code> your table name will be <code>OPT_ABC.STUDENT</code>.</p> <hr> <p>So, given that, to set the table name to <code>OPT_ABC.STUDENT</code>, you should be able to simply pass the value into <code>self.table_name</code> like this:</p> <pre><code>class Student &lt; ActiveRecord::Base self.abstract_class = true self.table_name = 'OPT_ABC.STUDENT' def self.list_student puts Student.take(1) #testing end end </code></pre>
C lang sizeof(char[]) get static size <p>I want to get char array size but I cant do that</p> <p>let see</p> <pre><code>#define MAX 64 char value[MAX] value = "hi" //or something initialization sizeof("hi") //result = 3 sizeof(value) // result = 64 </code></pre> <p>I want to get <code>sizeof("hi") == sizeof(value)</code> How cant I do?</p>
<p>In the snippet that you've included, you're actually setting the size of <code>value</code> to 64. As a result <code>sizeof(value)</code> will return 64 * <code>sizeof(char)</code>. This is correct, regardless of what you're putting into the array <code>value</code>.</p> <p>Perhaps what you're trying to do is to get the array to be automatically sized at compile time? e.g.</p> <pre><code>char value[] = "hi"; int value_size = sizeof(value); // value_size will now equal 3, as the array contains { 'h', 'i', '\0' } </code></pre>
Is JavaScript Proxy supposed to intercept direct changes to underlying object like Object.Observe? <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe" rel="nofollow">MDN for Object.Observe</a> says that Observe is now obsolete and we should use "more general Proxy object instead".</p> <p>But Observe allowed to intercept changes on existing object. If Proxy does not allow then Proxy API is not "more general" than Observable API.</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy" rel="nofollow">MDN for Proxy</a> and <a href="http://stackoverflow.com/questions/35610242/detecting-changes-in-a-javascript-array-using-the-proxy-object">this question</a> give examples of intercepting changes to proxy object, but never talk about changes to underlying object.</p> <p>Is Proxy supposed to intercept changes to underlying object in current or future ECMA standard ?</p> <p>Example:</p> <pre><code>let o = {}; let p = new Proxy(o, { set: (target, prop, val)=&gt; console.log(target, prop, val) }); p.p1 = 'v1'; // this will log o, "p1", "v1" o.p2 = 'v2'; // is this supposed to log o, "p2", "v2" in ECMA standard ? </code></pre>
<blockquote> <p><code>o.p2 = 'v2'; // is this supposed to log o, "p2", "v2" in ECMA standard ?</code></p> </blockquote> <p>No, using that particular pattern.</p> <p>Set the value at the <code>Proxy</code> object, and value will be set at <code>target</code> object.</p> <p>Though you can also define <code>getter</code> at original object.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = { get getProp() { return "obj getter: " + (this["x"] || void 0); } }; var proxy = new Proxy(obj, { set: function(obj, prop, newval) { var oldval = obj[prop]; console.log("set", oldval, obj, prop, newval); obj[prop] = newval; }, get: function(obj, prop) { console.log("get", obj, prop); } }); proxy.x = 1; console.log(obj.x); console.log(obj.getProp);</code></pre> </div> </div> </p>