Id
int64
34.6M
60.5M
Title
stringlengths
15
150
Body
stringlengths
33
36.7k
Tags
stringlengths
3
112
CreationDate
stringdate
2016-01-01 00:21:59
2020-02-29 17:55:56
Y
stringclasses
3 values
55,766,176
How to fix null object that appears all the time on my phone and sometimes on my emulator
got a probleme with Android studio. I'm trying to do a pretty simple app but on my phone (Galaxy S8) it always gives me the same error. And i use two computer it does the same at home and at school. When i use the emulator, i have the problem also on the emulator at home that is not the same from school but not in School. So on the emulator at school, the one that works i had the same error as all the other place but juste once and ive tried it a lot of time. But later in the program i have the same kind of error that appears but in some other function. So far i havent been able to go past that. The error is saying that im trying to do something on a null object (a layout or a text view). The error that happens always on my phone is as soon as i try to use a constraint layer it wont work. The other one that happens late in the program on the emulator seems really random. Its a game of card the 98 card game. And at some time when i try to drop a card on one of the pile it give me the null object error on the same textView. I have really tried but cant see any pattern on this one. ``` public Boolean checkEndOfGame(LinearLayout cartes, LinearLayout piles){ if(nbCartes == 0){ return true; } for (int i=0; i< piles.getChildCount(); i++){ LinearLayout sorte = (LinearLayout)piles.getChildAt(i); for(int j=0; j< sorte.getChildCount(); j++){ if(sorte.getChildAt(j) instanceof ConstraintLayout){ ConstraintLayout pile = (ConstraintLayout)sorte.getChildAt(j); TextView textePile = (TextView) pile.getChildAt(0); Integer noPile = new Integer(textePile.getText().toString()); for(int k=0; k< cartes.getChildCount(); k++){ LinearLayout rangee = (LinearLayout)cartes.getChildAt(i); for(int l=0; l< rangee.getChildCount(); l++){ ConstraintLayout carte = (ConstraintLayout)rangee.getChildAt(l); TextView texteCarte = (TextView) carte.getChildAt(0); Integer noCarte = new Integer(texteCarte.getText().toString()); if(i>0){ //UP if(noCarte>noPile){ return false; } }else{ //DOWN if(noCarte<noPile){ return false; } } } } } } } return true; } ``` So this is the function that gives me the random error always on that last TextView. I give it carte and piles that are layout that contains each two other linearlayout. And in those there constraintLayout and in each constraintLayout theres a textView wich i can drag and drop.
<android>
2019-04-19 18:25:57
LQ_EDIT
55,766,677
Function if in javascript ever return true
I have the function below: $("#botao").on("click", function(){ s = $("#municipio").val(); alert(s); if (s == 1){ $("#imagem").attr("src","https://gatolovers.com.br/uf/popup1.png"); $("#mensagem").html('Uhul! Nós atendemos sua região. Temos uma unidade de atendimento pertinho de você. Ligue agora mesmo e faça um orçamento.'); }else{ $("#imagem").attr("src","https://gatolovers.com.br/uf/popup0.png"); $("#mensagem").html('Ops! Ainda não estamos na sua cidade. Mas muito em breve levaremos a melhor empresa de Redes de Proteção para sua região, consulte nosso plano de expansão.'); } }); Independs of `s` be 0 or 1, the function ever return the first block.
<javascript>
2019-04-19 19:08:30
LQ_EDIT
55,769,120
How do I display a div over a div then disappear after 10 seconds?
<p>I have a SWF file that I play on my website. But before this SWF plays, I want to play another SWF file before it. It's about 10 seconds. So I have a two DIVs: one containing the SWF file that I want to play before, and the other div to contain the SWF I want to present. I believe Jquery can be used to solve my problem. Can anyone help? I tried searching the internet but found no solution. Any help would be gladly appreciated! Thanks!</p>
<jquery>
2019-04-20 00:10:58
LQ_CLOSE
55,771,807
C# replace integer if integer has other numbers from both ends
I want to replace an integer if it is a part of another integer from both ends. Say for example an integer +35343+3566. I want to replace +35 with 0 only if it is surrounded with numbers from both sides. So desired outcome would be +35343066. Normally I'd use line.Replace("+35", "0") and perhaps 'if-else' to meet a condition int a = +35343+3566; string b = a.ToString(); string c = b.Replace("+35", "0"); I would want c = +35343066 and not c = 0343066
<c#><replace>
2019-04-20 08:43:22
LQ_EDIT
55,772,201
How to put a multi-row statement string into a variable?
<p>I want to a store a long string (specifically a SQL query) into a variable, which I'd like to have written on more row for a better readability.</p> <p>I'm using Jupyter notebook on Python 3.5 (Anaconda) if that's important.</p> <p>I've tried:</p> <pre><code># SQL query query = " SELECT Sued ,ApplicationNumber_Primary --,ApprovedLoanAmount, ApprovedLoanDuration, ApprovedMonthlyPayment, ,RequiredLoanDuration, RequiredMonthlyPaymentAmount, RequiredPaidAmount, RequiredCoefficientK1 ,ClientFreeSources, ClientTotalIncome, ClientNetIncome, ClientTotalExpenditures ,ClientAgeToApplicationDate, ClientFamilyStatusID, ClientEmploymentDuration, CreditExposure ,CalendarQuarter, MonthOfYear, WeekOfYear, DayOfMonth, DayOfWeek, RegionID, DistrictID, ZIPcodeID FROM dbo.vRisk GO " </code></pre> <p>...which does not store the string into the variable, as I'd like.</p> <p>Help would be appreciated.</p>
<python><python-3.x>
2019-04-20 09:39:42
LQ_CLOSE
55,774,688
How to make this jquery code work on 3.2.1 jquery
First of all i'll told you i 'm very little knowledge about java script i can under stand an function (can download free resource and applied or modified to my work) so i used this function to make my one page website by set all div to display-non and when click on each button will set that div display-block everything work fine until i have add music player that the creator use higher jquery library (i used to 1.5.2 > 3.2.1) every thing work great like before but wheni click on button to play the music i can't get back or go to other menu inspector said u ncaught TypeError: document.getElementById is not a function but if i won't click on play button everything is mormal :( function openPage(pageName) { var i; var x = document.getElementsByClassName("page"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } document.getElementById(pageName).style.display = "block"; }
<javascript><jquery><css>
2019-04-20 14:54:58
LQ_EDIT
55,776,057
What AWS instance setting can prevent to perform ssh to this instance?
I supposed to add the ssh key and then ssh to the AWS instance using a jumphost in 2 operations So adding the key ssh-add ~/.ssh/<key-file>.pem Then ssh to jumphost ssh -A ec2-user@jumphost And then from jumphost to instance ssh -A ec2-user@<private IP> This works for one instance but does not work for another instance - cannot ssh to this instance from a jumphost. What instance setting can prevent me to do ssh?
<amazon-web-services><ssh>
2019-04-20 17:34:47
LQ_EDIT
55,777,321
format text in javascript
how to Write a parser/method in javascript which would parse below digraph "com.a:test:jar:1.0" { "com.a:test:jar:1.0" -> "org.apache.httpcomponents:httpclient:jar:4.5.5:compile"; "com.a:test:jar:1.0" -> "com.google.code.gson:gson:jar:2.8.2:compile"; "com.a:test:jar:1.0" -> "info.picocli:picocli:jar:2.3.0:compile"; "com.a:test:jar:1.0" -> "log4j:log4j:jar:1.2.17:compile"; "com.a:test:jar:1.0" -> "org.xerial:sqlite-jdbc:jar:3.21.0:compile"; "org.apache.httpcomponents:httpclient:jar:4.5.5:compile" -> "org.apache.httpcomponents:httpcore:jar:4.4.9:compile" ; "org.apache.httpcomponents:httpclient:jar:4.5.5:compile" -> "commons-logging:commons-logging:jar:1.2:compile" ; "org.apache.httpcomponents:httpclient:jar:4.5.5:compile" -> "commons-codec:commons-codec:jar:1.10:compile" ; } into digraph "com.a:test:jar:1.0" { "com.a:test:jar:1.0" -> "org.apache.httpcomponents:httpclient:jar:4.5.5:compile"; "com.a:test:jar:1.0" -> "com.google.code.gson:gson:jar:2.8.2:compile"; "com.a:test:jar:1.0" -> "info.picocli:picocli:jar:2.3.0:compile"; "com.a:test:jar:1.0" -> "log4j:log4j:jar:1.2.17:compile"; "com.a:test:jar:1.0" -> "org.xerial:sqlite-jdbc:jar:3.21.0:compile"; } i.e anything appearing next to diagraph "com.a:test:jar:1.0" if it appears before (LHS) `->` have it else omit it. Note: there can be multiple blocks of digraph.
<javascript><node.js><typescript>
2019-04-20 20:08:46
LQ_EDIT
55,777,723
How to record a call in Android pie?
<p>Basically I've done call recording but it's not working up to Oreo. I read an article in Wich google stop call recording in up to Oreo anyone have any idea how to record call in Android pie? Code comments will be appreciated. Thanks </p>
<java><android>
2019-04-20 21:05:14
LQ_CLOSE
55,779,400
How to split string into arrays based on html tag
<p>I have a string having HTML tags and I would like to explode into arrays as like below</p> <p>The tags I am considering to explode are : <code>p, h1, h2, h3, h4, h5, &lt;ul&gt;, &lt;ol&gt;</code></p> <p>Example: </p> <pre><code>$data ="&lt;p&gt; Paragraph 1 &lt;/p&gt; &lt;h2&gt;h2 tag 1 &lt;/h2&gt; &lt;p&gt; Paragraph 2.&lt;/p&gt; &lt;p&gt;Paragraph 3 &lt;/p&gt; &lt;ol&gt; &lt;li&gt;pizza&lt;/li&gt; &lt;li&gt;burgers&lt;/li&gt; &lt;li&gt;salad&lt;/li&gt; &lt;/ol&gt; &lt;ul&gt; &lt;li&gt; &lt;ul&gt; &lt;li&gt; One &lt;/li&gt; &lt;li&gt;Twp &lt;/li&gt; &lt;li&gt;Three&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;p&gt; Paragraph 5 &lt;/p&gt; &lt;p&gt;Paragraph 6:&lt;/p&gt; &lt;h4&gt; h4 tag&lt;/h4&gt; &lt;h1&gt; h4 tag&lt;/h1&gt; &lt;h4&gt; h4 tag&lt;/h4&gt;" </code></pre> <p>I need the following output:</p> <pre><code>$array_tags= [ 0 =&gt; &lt;p&gt; Paragraph 1 &lt;/p&gt;, 1 =&gt; &lt;h2&gt;h2 tag 1 &lt;/h2&gt;, 2 =&gt; &lt;p&gt; Paragraph 2 &lt;/p&gt;, 3 =&gt; &lt;p&gt; Paragraph 3 &lt;/p&gt;, 4 =&gt; &lt;ol&gt; &lt;li&gt;pizza&lt;/li&gt; &lt;li&gt;burgers&lt;/li&gt; &lt;li&gt;salad&lt;/li&gt; &lt;/ol&gt;, 5 =&gt; &lt;p&gt; Paragraph 4 &lt;/p&gt;, 6 =&gt; &lt;ul&gt; &lt;li&gt; &lt;ul&gt; &lt;li&gt; One &lt;/li&gt; &lt;li&gt;Twp &lt;/li&gt; &lt;li&gt;Three&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt;, 7 =&gt; &lt;p&gt; Paragraph 5 &lt;/p&gt;, 8 =&gt; &lt;p&gt; Paragraph 6 &lt;/p&gt;, 9 =&gt; &lt;h4&gt; h4 tag&lt;/h4&gt;, 10 =&gt; &lt;h1&gt; h1 tag&lt;/h1&gt;, ]; </code></pre> <p>Could someone please help here? Thanks in advance!</p>
<php><preg-replace>
2019-04-21 02:32:27
LQ_CLOSE
55,779,600
Why are these two algorithms for finding the n-th Fabonacci number so inefficient?
When calculating the 64th Fabonacci number, the first algorithm takes several hours, and the second one takes less than a second. Why is the efficiency of the second algorithm so much higher than that of the first one? They look very similar. Please tell me why, thx :) def fib_divide_recursion(n): if n <= 2: return n-1 else: return fib_divide_recursion(n-1) + fib_divide_recursion(n-2) def fib_linear_recursion(n, prev={}): if n <= 2: return n-1 try: return prev[n] except KeyError: prev[n] = fib_linear_recursion(n - 1, prev) + fib_linear_recursion(n - 2, prev) return prev[n]
<python><algorithm><fibonacci>
2019-04-21 03:24:10
LQ_EDIT
55,780,179
How evaluate a string?
<p>So basically what i have been struggling with is to evaluate sentence in EF Core.</p> <p>For example if i have: </p> <pre><code>string condition = "65 &lt; 100 AND 65 &gt; 50" </code></pre> <p>How can evaluate that?</p>
<c#><asp.net-core><entity-framework-core>
2019-04-21 05:35:30
LQ_CLOSE
55,782,265
Can someone please explain this Python code?
<p>Whilst I know what this piece of code does i have no clue how it achieves it. Can someone please explain it in the dumbest way?</p> <pre><code>vec = [[1,2,3], [4,5,6], [7,8,9]] [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre> <p>The first for part of the code returns this:</p> <pre><code>[num for elem in vec] [0, 0, 0] </code></pre> <p>Are they indexes for each nested lists first entry?</p> <p>Thanks!</p>
<python><list><list-comprehension>
2019-04-21 11:23:23
LQ_CLOSE
55,782,999
How to deploy Java stadnalone application on JBOSS along with other web applications
I am writing a Java program which will keep on listening to JMS/ActiveM queue for any messages. When there is a message posted on the queue, this program will pick up the message and process it. this program has a main method. Now I want to deploy this program in JBOSS/wildfly. already there are some web application deployed on JBOSS. I want to deploy this program also on JBOSS to avoid manual start ups. Whenever the JBOSS server starts, this program also should run and listen to queue. If main method cannot be used, Need some advise on alternative solution to this requirement.
<java><jboss><jms>
2019-04-21 13:07:55
LQ_EDIT
55,783,324
Data in not displayed on checkbox in c#.net sqlserver
i am tring diplay the values from database. textbox values displayed successfully but checkbox values is not diplayed and it shown the error. i attached the error on screenshot image below [enter image description here][1] sql = "select * from repair where repairid = '" + repairid + "'"; SqlCommand cmd = new SqlCommand(sql, con); SqlDataReader dread; con.Open(); dread = cmd.ExecuteReader(); while (dread.Read()) { checkBox7.CheckState = dread[6].ToString(); } [1]: https://i.stack.imgur.com/fIf3h.jpg [1]: https://i.stack.imgur.com/97BXW.jpg
<c#><sql-server>
2019-04-21 13:51:29
LQ_EDIT
55,784,108
how to handle with GeoLocation columns in dataset
I am a beginner in machine learning, I am doing predicting adduction probability drug. I have some problem with GeoLocation column and also I don't know how to handle with GeoLocation, please help how to do. my column like this : train['GeoLocation'].head(8) 0 (29.760427, -95.369803) 1 (29.760427, -95.369803) 2 (39.493240390000494, -117.07184056399967) 3 (40.79373015200048, -77.86070029399963) 4 (37.77493, -122.419416) 5 (39.952584, -75.165222) 6 (32.715738, -117.161084) 7 (39.360700171000474, -111.58713063499971) Name: GeoLocation, dtype: object
<python><pandas><machine-learning><geolocation>
2019-04-21 15:31:05
LQ_EDIT
55,785,359
How can I get IOBluetoothDevice's battery level, using Swift and AppKit (Xcode for MacOS)
<p>I am using <strong>Xcode</strong> to develop a <strong>MacOS app</strong>, based on <strong>Cocoa</strong> &amp; <strong>AppKit</strong>, written in <strong>Swift</strong>.</p> <p>I am using <a href="https://developer.apple.com/documentation/iobluetooth/iobluetoothdevice" rel="noreferrer">IOBluetoothDevice</a> objects throughout my app, and I want to be able to display the devices' battery levels, if accessible.</p> <p>I expect that devices which battery levels are visible on the OS's Bluetooth settings (see image below), to be also accessible programmatically (e.g., AirPods, Magic Keyboard, etc.). However, I could not find this anywhere.</p> <p>I have also thought about executing a terminal command and found <a href="https://apple.stackexchange.com/questions/215256/check-the-battery-level-of-connected-bluetooth-headphones-from-the-command-line">this thread</a>, but it did also not work.</p> <p>Thanks</p> <p><a href="https://i.stack.imgur.com/TzlCd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TzlCd.png" alt="Bluetooth device battery level available to the OS"></a></p>
<swift><macos><cocoa><appkit>
2019-04-21 18:06:25
HQ
55,787,035
Is there an API to detect which theme the OS is using - dark or light (or other)?
<h2>Background</h2> <p>On recent Android versions, ever since Android 8.1, the OS got more and more support for themes. More specifically dark theme.</p> <h2>The problem</h2> <p>Even though there is a lot of talk about dark mode in the point-of-view for users, there is almost nothing that's written for developers.</p> <h2>What I've found</h2> <p>Starting from Android 8.1, Google provided some sort of dark theme . If the user chooses to have a dark wallpaper, some UI components of the OS would turn black (article <a href="https://www.theandroidsoul.com/dark-theme-android-8-1-oreo/" rel="noreferrer"><strong>here</strong></a>). </p> <p>In addition, if you developed a live wallpaper app, you could tell the OS which colors it has (3 types of colors), which affected the OS colors too (at least on Vanilla based ROMs and on Google devices). That's why I even made an app that lets you have any wallpaper while still be able to choose the colors (<a href="https://play.google.com/store/apps/details?id=com.lb.lwp_plus" rel="noreferrer"><strong>here</strong></a>). This is done by calling <a href="https://developer.android.com/reference/android/service/wallpaper/WallpaperService.Engine.html#notifyColorsChanged()" rel="noreferrer"><strong>notifyColorsChanged</strong></a> and then provide them using <a href="https://developer.android.com/reference/android/service/wallpaper/WallpaperService.Engine.html#onComputeColors()" rel="noreferrer"><strong>onComputeColors</strong></a></p> <p>Starting from Android 9.0, it is now possible to choose which theme to have: light, dark or automatic (based on wallpaper) :</p> <p><a href="https://i.stack.imgur.com/CKZdV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CKZdV.png" alt="enter image description here"></a></p> <p>And now on the near Android Q , it seems it went further, yet it's still unclear to what extent. Somehow a launcher called "Smart Launcher" has ridden on it, offering to use the theme right on itself (article <a href="https://www.androidcentral.com/smart-launcher-5-adds-android-q-dark-theme-support" rel="noreferrer"><strong>here</strong></a>). So, if you enable dark mode (manually, as written <a href="https://www.xda-developers.com/android-q-toggle-dark-theme/" rel="noreferrer"><strong>here</strong></a>) , you get the app's settings screen as such:</p> <p><a href="https://i.stack.imgur.com/W43vo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/W43vo.png" alt="enter image description here"></a></p> <p>The only thing I've found so far is the above articles, and that I'm following this kind of topic.</p> <p>I also know how to request the OS to change color using the live wallpaper, but this seems to be changing on Android Q, at least according to what I've seen when trying it (I think it's more based on time-of-day, but not sure).</p> <h2>The questions</h2> <ol> <li><p>Is there an API to get which colors the OS is set to use ? </p></li> <li><p>Is there any kind of API to get the theme of the OS ? From which version?</p></li> <li><p>Is the new API somehow related to night mode too? How do those work together?</p></li> <li><p>Is there a nice API for apps to handle the chosen theme? Meaning that if the OS is in certain theme, so will the current app?</p></li> </ol>
<android><themes><android-9.0-pie><android-8.1-oreo><android-10.0>
2019-04-21 21:44:11
HQ
55,787,701
React efficiently update object in array with useState hook
<p>I have a React component that renders a moderately large list of inputs (100+ items). It renders okay on my computer, but there's noticeable input lag on my phone. The React DevTools shows that the entire parent object is rerendering on every keypress.</p> <p>Is there a more efficient way to approach this?</p> <p><a href="https://codepen.io/anon/pen/YMvoyy?editors=0011" rel="noreferrer">https://codepen.io/anon/pen/YMvoyy?editors=0011</a></p> <pre><code>function MyInput({obj, onChange}) { return ( &lt;div&gt; &lt;label&gt; {obj.label} &lt;input type="text" value={obj.value} onChange={onChange} /&gt; &lt;/label&gt; &lt;/div&gt; ); } // Passed in from a parent component const startingObjects = new Array(100).fill(null).map((_, i) =&gt; ({label: i, value: 'value'})); function App() { const [objs, setObjects] = React.useState(startingObjects); function handleChange(obj) { return (event) =&gt; setObjects(objs.map((o) =&gt; { if (o === obj) return {...obj, value: event.target.value} return o; })); } return ( &lt;div&gt; {objs.map((obj) =&gt; &lt;MyInput obj={obj} onChange={handleChange(obj)} /&gt;)} &lt;/div&gt; ); } const rootElement = document.getElementById("root"); ReactDOM.render(&lt;App /&gt;, rootElement); </code></pre>
<reactjs><react-hooks>
2019-04-21 23:45:13
HQ
55,788,554
Can a Perl program know the line number where __DATA__ begins?
<p>Is there a way to get the line number (and maybe filename) where a <strong>__DATA__</strong> token was coded? Or some other way to know the actual line number in the original source file where a line of data read from the <em>DATA</em> filehandle came from?</p> <p>Note that <code>$.</code> counts from 1 when reading from the <code>DATA</code> filehandle. So if the line number of the <code>__DATA__</code> token were added to <code>$.</code> it would be what I'm looking for.</p> <p>For example:</p> <pre><code>#!/usr/bin/perl while (&lt;DATA&gt;) { my $n = $. + WHAT??; die "Invalid data at line $n\n" if /bad/; } __DATA__ something good something bad </code></pre> <p>I want this to say "Invalid data at line 9", not "line 2" (which is what you get if <code>$.</code> is used by itself).</p>
<perl>
2019-04-22 02:42:00
HQ
55,789,409
How to unset "ENV" in dockerfile?
<p>For some certain reasons, I have to set "http_proxy" and "https_proxy" <code>ENV</code> in my dockerfile. I would like to now unset them because there are also some building process can't be done through the proxy.</p> <pre><code># dockerfile # ... some process ENV http_proxy=http://... ENV https_proxy=http://... # ... some process that needs the proxy to finish UNSET ENV http_proxy # how to I unset the proxy ENV here? UNSET ENV https_proxy # ... some process that can't use the proxy </code></pre>
<docker><dockerfile>
2019-04-22 05:10:42
HQ
55,789,448
Is there any way to get the live chat replay log/history for YouTube streaming video?
<p>Recently I'm doing research for online chat message patterns. I chose YouTube and Twitch.tv for chat message sources.</p> <p>So I found chat loggers for real-time livestream, but I also need log/history for already broadcasted livestream which allows live chat replay. (like <a href="https://www.youtube.com/watch?v=1JfohG5a8y8" rel="noreferrer">https://www.youtube.com/watch?v=1JfohG5a8y8</a> )</p> <p>There are tool for Twitch.tv (<a href="https://github.com/jdpurcell/RechatTool" rel="noreferrer">RechatTool from jdpurcell</a>), but I couldn't find any similar one of them for YouTube.</p> <p>So I checked <a href="https://developers.google.com/youtube/v3/live/docs/liveChatMessages/list" rel="noreferrer"> YouTube API for livestream messages</a>, but I couldn't find any instructions or tips for live chat replay. Is there any possible solutions for this?</p>
<youtube-api><chat><live-streaming><livechat>
2019-04-22 05:15:49
HQ
55,792,227
Download latest nuget during run-time
During runtime, I want to download the latest dll from nuget library using .net core and load it into the container.
<c#><.net-core><dependencies><nuget><runtime>
2019-04-22 09:31:48
LQ_EDIT
55,792,721
how to find the probability of each class respect to test data?
Here I am using naive bayse classifier, how to find the probability of each class respect to each test data set? #Import Library of Gaussian Naive Bayes model from sklearn.naive_bayes import GaussianNB import numpy as np #assigning predictor and target variables x= np.array([[-3,7],[1,5], [1,2], [-2,0], [2,3], [-4,0], [-1,1], [1,1], [-2,2], [2,7], [-4,1], [-2,7]]) y = np.array([3, 3, 3, 3, 4, 3, 3, 4, 3, 4, 4, 4]) #Create a Gaussian Classifier model = GaussianNB() # Train the model using the training sets model.fit(x, y) #Predict Output predicted= model.predict([[1,2],[3,4]]) print(predicted)
<python><scikit-learn>
2019-04-22 10:12:29
LQ_EDIT
55,793,095
Could not find method leftShift() for arguments after updating studio 3.4
<p>After updating studio <code>3.4</code> and Gradle version to <code>5.1.1</code> I got the error on my task as <strong>Could not find method leftShift()</strong></p> <p><strong>My task:</strong></p> <pre><code>task incrementBetaVersion &lt;&lt; { println("Incrementing Beta Version Number...") incrementVersionNumber('BetaVersionNumber') println("Incrementing Beta Version Number...") incrementVersionName('BetaVersionName') } </code></pre> <p>I got the error for the left shift operator <code>&lt;&lt;</code> in the line.</p> <p>How to resolve this error?</p>
<android><gradle><groovy><android-gradle-plugin><build.gradle>
2019-04-22 10:43:44
HQ
55,793,734
Full Screen Notification
<p>I want to make App Like Uber But I Don't know how to make full screen notification,When Driver receiver new Request a new Screen Pop up that will show timer ,accept , reject button. even when driver app is in background , I am newbiew here is a video link what i want to do <a href="https://drive.google.com/file/d/1dhqSDexUKYY---ARHjWcg3bM0tYWRmLo/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1dhqSDexUKYY---ARHjWcg3bM0tYWRmLo/view?usp=sharing</a></p> <p>Sorry for English</p> <p>I have tried to use heads up notification with full screen but it didn't work well ; I have tried to make background service to but i am not good in it so that also did not go well; I am working on Oreo ;</p>
<android><firebase><android-studio>
2019-04-22 11:33:46
LQ_CLOSE
55,794,287
My simple c++ calculator is not working as it should be
<p>This is a suppposed to be simple calculator which can plus, minus, mulyiply or divide two numbers that are input into the console (int a, b). The problem is probably with my if / else statemnts. Even though I input "Minus" , "Multiply" or "Divide" into the console, the operator (std::string operator) is always set to "plus", thus adding the two numbers even though that was not my desired operator.</p> <p>Ive tried removing the [int plus();] function alltogether to see the result, then the default and fixed operator changed to minus.</p> <pre><code>#include &lt;iostream&gt; // the problem is probably at [void core();] std::string operation; int a; int b; class common { public: void print() { std::cout &lt;&lt; "a: "; std::cin &gt;&gt; a; std::cout &lt;&lt; "b: "; std::cin &gt;&gt; b; } }; int plus() { common plus1; plus1.print(); int ans = a + b; std::cout &lt;&lt; "ANS: " &lt;&lt; ans &lt;&lt; "\n"; return a + b; } int minus() { common minus1; minus1.print(); int ans = a - b; std::cout &lt;&lt; "ANS: " &lt;&lt; ans &lt;&lt; "\n"; return a - b; } int multiply() { common multiply1; multiply1.print(); int ans = a * b; std::cout &lt;&lt; "ANS: " &lt;&lt; ans &lt;&lt; "\n"; return a * b; } int divide() { common divide1; divide1.print(); int ans = a / b; std::cout &lt;&lt; "ANS: " &lt;&lt; ans &lt;&lt; "\n"; return a / b; } void core() { std::cout &lt;&lt; "\nplus / minus / multiply / divide\n" &lt;&lt; "operation: "; std::cin &gt;&gt; operation; if (operation == "plus" or "Plus") { plus(); } else if (operation == "minus" or "Minus") { minus(); } else if (operation == "multiply" or "Multiply") { multiply(); } else if (operation == "divide" or "Divide") { divide(); } else { std::cout &lt;&lt; "Invalid Operation!\n"; } } int main() { for (int i = 0; i &lt; 99; i++) { core(); } } </code></pre> <p>When i set [std::string operation] as "multiply" through [std::cin >> operation], i expected the [multiply();] function to be called but instead, [plus();] function is called no matter what operator i set.</p>
<c++><if-statement>
2019-04-22 12:17:27
LQ_CLOSE
55,795,237
Javascript insert element at nth index in array, insertion elements from another array
<p>I have 2 Javascript arrays:</p> <pre><code>['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] ['a', 'b', 'c'] </code></pre> <p>I need to insert elements of second array into the first array every 4th or nth index of the first array, resulting in:</p> <pre><code>['a', '1', '2', '3', '4', 'b', '5', '6', '7', '8', 'c', '9', '10', '11', '12'] </code></pre> <p>n needs to be a parameter, so I can move n to the 5th location, or 3rd location when needed.</p> <p>Any solutions appreciated. ES6 ones would be great! Thank you in advance.</p>
<javascript><arrays>
2019-04-22 13:34:31
LQ_CLOSE
55,795,253
Can someone explain why the range in the random.randint(0, len(messages) - 1) has a minus 1 at the end? The list has 9 values
import random messages = ['It is certain', 'It is decidedly so', 'Yes definitely', 'Reply hazy try again', 'Ask again later', 'Concentrate and ask again', 'My reply is no', 'Outlook not so good', 'Very doubtful'] select_number = random.randint(0, len(messages) - 1) list_select = messages[select_number] print(list_select)
<python><python-3.x><random>
2019-04-22 13:35:38
LQ_EDIT
55,795,436
Initialization functionality unavailable for this session, in google Ads
<p>I'm getting this error of google Ads, suddently. I can't find anything here with this error. </p> <p>Notice that ads are displaying correctly</p> <pre><code>Google Mobile Ads SDK initialization functionality unavailable for this session. Ad requests can be made at any time. </code></pre>
<android><ads>
2019-04-22 13:48:22
HQ
55,795,625
Fody is only supported on MSBuild 16 and above. Current version: 15
<p>Visual Studio 2017 let me know there was an upgrade to Fody version 5 this morning. I accepted and did a NuGet package update of both Fody and PropertyChanged.Fody.</p> <p>Now, my project/solution will no longer build.</p> <p>The error is:</p> <p>"Fody is only supported on MSBuild 16 and above. Current version: 15."</p> <p>I tried uninstalling, shutting down VS, and reinstalling to no avail.</p>
<c#><fody><visual-studio-2017-build-tools><fody-propertychanged>
2019-04-22 14:02:50
HQ
55,797,442
Why is grid span not being excepted for "blank1" in IE 11
css grid issue: Third grid item "blank1" should row span and cover both row 1 and row 2 of column 3. But it is not working in IE 11. It is only covering the first row. Here is a link to the file online. Look at in in firefox and it will show what it is suppose to look like. IE 11 need fixing. https://www.survival-manual.com/test/test-ie.php .wrapper { display: -ms-grid; display: grid; -ms-grid-columns: 300px 300px 300px; grid-template-columns: 300px 300px 300px; -ms-grid-rows: 200px 200px 200px 200px; grid-template-rows: 200px 200px 200px 200px; background-color: #fff; } .wrapper > *:nth-child(1) { -ms-grid-row: 1; -ms-grid-column: 1; } .wrapper > *:nth-child(2) { -ms-grid-row: 1; -ms-grid-column: 2; } .wrapper > *:nth-child(3) { -ms-grid-row: 1; -ms-grid-column: 3; } .wrapper > *:nth-child(4) { -ms-grid-row: 2; -ms-grid-column: 1; } .wrapper > *:nth-child(5) { -ms-grid-row: 2; -ms-grid-column: 2; } .wrapper > *:nth-child(6) { -ms-grid-row: 2; -ms-grid-column: 3; } .wrapper > *:nth-child(7) { -ms-grid-row: 3; -ms-grid-column: 1; } .wrapper > *:nth-child(8) { -ms-grid-row: 3; -ms-grid-column: 2; } .wrapper > *:nth-child(9) { -ms-grid-row: 3; -ms-grid-column: 3; } .wrapper > *:nth-child(10) { -ms-grid-row: 4; -ms-grid-column: 1; } .wrapper > *:nth-child(11) { -ms-grid-row: 4; -ms-grid-column: 2; } .wrapper > *:nth-child(12) { -ms-grid-row: 4; -ms-grid-column: 3; } .box { background-color: #444; color: #fff; border-radius: 5px; padding: 20px; font-size: 150%; } .print { -ms-grid-column: 1; grid-column-start: 1; -ms-grid-column-span: 1; grid-column-end: 2; -ms-grid-row: 1; grid-row-start: 1; -ms-grid-row-span: 1; grid-row-end: 2; background-color:white; } .ad { -ms-grid-column: 2; grid-column-start: 2; -ms-grid-column-span: 1; grid-column-end: 3; -ms-grid-row: 1; grid-row-start: 1; -ms-grid-row-span: 1; grid-row-end: 2; background-color:234; } .blank1 { -ms-grid-column: 3; grid-column-start: 3; -ms-grid-column-span: 1; grid-column-end: 4; -ms-grid-row: 1; grid-row-start: 1; -ms-grid-row-span: 2; grid-row-end: 3; background-color:678; } .search { -ms-grid-column: 1; grid-column-start: 1; -ms-grid-column-span: 1; grid-column-end: 2; -ms-grid-row: 2; grid-row-start: 2; -ms-grid-row-span: 1; grid-row-end: 3; background-color:white; } .logo { -ms-grid-column: 2; grid-column-start: 2; -ms-grid-column-span: 1; grid-column-end: 3; -ms-grid-row: 2; grid-row-start: 2; -ms-grid-row-span: 1; grid-row-end: 3; background-color:678; } .menu { -ms-grid-column: 1; grid-column-start: 1; -ms-grid-column-span: 1; grid-column-end: 2; -ms-grid-row: 3; grid-row-start: 3; -ms-grid-row-span: 1; grid-row-end: 4; background-color:789; } .content { -ms-grid-column: 2; grid-column-start: 2; -ms-grid-column-span: 1; grid-column-end: 3; -ms-grid-row: 3; grid-row-start: 3; -ms-grid-row-span: 1; grid-row-end: 4; background-color:567; } .rightside { -ms-grid-column: 3; grid-column-start: 3; -ms-grid-column-span: 1; grid-column-end: 4; -ms-grid-row: 3; grid-row-start: 3; -ms-grid-row-span: 2; grid-row-end: 5; background-color:orange; } .blank2 { -ms-grid-column: 1; grid-column-start: 1; -ms-grid-column-span: 1; grid-column-end: 2; -ms-grid-row: 4; grid-row-start: 4; -ms-grid-row-span: 1; grid-row-end: 5; background-color:red; } .footer { -ms-grid-column: 2; grid-column-start: 2; -ms-grid-column-span: 1; grid-column-end: 3; -ms-grid-row: 4; grid-row-start: 4; -ms-grid-row-span: 1; grid-row-end: 5; background-color:289; } </style>
<html><css><internet-explorer><css-grid>
2019-04-22 16:13:57
LQ_EDIT
55,802,304
How to fill array with random numbers limited to 0-20
<p>I am having trouble placing the random generator in the array, how can I get #20 random numbers from 0-9 in the array? Then you count the occurrences of those numbers.</p> <p>import java.util.Random;</p> <p>public class CountDigits {</p> <pre><code>public static void main(String[] args) { Random digit = new Random(); int Random[] = new int [20]; int Digits[] = {0,1,2,3,4,5,6,7,8,9}; int Count [] = new int [10]; for ( int i = 0; i &lt; Digits.length; i++) { for( int j = 0; j &lt; Random.length; j++) { if ( Digits [i] == Random [j] ) Count[i]++; } } for ( int i = 0; i &lt; Count.length; i++) { if ( Count[i] == 1) System.out.printf(" %d occurs 1 time " , Digits[i] ); else System.out.printf("%d occurs %d times" , Digits[i], Count[i]); } </code></pre> <p>result so far:: 0 occurs 20 times1 occurs 0 times2 occurs 0 times3 occurs 0 times4 occurs 0 times5 occurs 0 times6 occurs 0 times7 occurs 0 times8 occurs 0 times9 occurs 0 times</p>
<java><arrays><random>
2019-04-22 23:23:28
LQ_CLOSE
55,805,496
AG Grid tooltip takes long time to render
<p>I was following <a href="https://www.ag-grid.com/javascript-grid-tooltip-component/" rel="noreferrer">this example</a> and found out that the table takes quite some time to render the tooltip. It doesn't seem to have any delay whatsoever, and I have tried both defaultBrowserTooltip as well as the custom one but both of them are slow. Any given tips on this?</p> <p>P/S: I'm using React</p> <p>Some way that I have tried:</p> <pre><code>tooltipField: 'myTooltipField' tooltip: (value: string): string =&gt; value </code></pre>
<reactjs><tooltip><ag-grid><ag-grid-react>
2019-04-23 06:30:59
HQ
55,805,708
backgound: linear-gradient() not working on mobile
I made a simple page on code pen but background: linear-gradinet not working on mobile. It is showing color in computer but not in mobile here is my code link : - `https://codepen.io/jjarus/full/OGwJqv`
<html><css>
2019-04-23 06:46:20
LQ_EDIT
55,808,079
Turning on Bluetooth programatically Swift
I am trying to turn on bluetooth automatically using my app. The usual way would be for user to go to settings and turn on. But i need to to be turned on from the app. And i have went through lots of documentations and they are referring to private APIs but all are very old.I do not mind that it's not going to be approved at App Store. Is there anything online which uses Swift?
<ios><swift><core-bluetooth>
2019-04-23 09:23:41
LQ_EDIT
55,808,776
panic: runtime error: invalid memory address or nil pointer dereference only on the GAE
I am working on the golang app using gin framework. Basically it just fetch the data from firestore as json. Localy it works perfectly but when I deploy it to the GAE (gcloud app deploy) there is no error during deployment but when access the page it does not work and in the logs provide an error: "panic: runtime error: invalid memory address or nil pointer dereference" Can you please help me to resolve this frustrating problem. Thank you in advance Here is my go page: package listcollections import ( "fmt" "log" "net/http" "cloud.google.com/go/firestore" "github.com/gin-gonic/gin" "google.golang.org/api/iterator" "google.golang.org/appengine" ) func main() { } //GetListCollections function func GetListCollections(c *gin.Context) { var coll []string ctx := appengine.NewContext(c.Request) projectID := "XXX" client, err := firestore.NewClient(ctx, projectID) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer client.Close() iter := client.Collection("collection").Documents(ctx) for { doc, err := iter.Next() if err == iterator.Done { break } if err != nil { fmt.Println("ERROR") } coll = append(coll, doc.Data()["Title"].(string)) } c.JSON(http.StatusOK, gin.H{ "collections": coll, }) }
<go><google-app-engine><go-gin>
2019-04-23 10:04:47
LQ_EDIT
55,810,229
How to stuff any number of values in 8-10 bytes of data for n number of 16 bit values?
<p>I am working on algorithm where i can have any number of 16 bit values(For instance i have 1000 16 bit values , and all are sensor data, so no particular series or repetition). I want to stuff all of this data into an 8 or a 10 byte array(each and every value of the 1000 16 bits numbers should be inside the 10 byte array) . The information should be such that i can also easily decode to read each and every value from the 1000 values. I have thought of using sin function by dividing the values by 100 so every data point would always be in 8 bits(0-1 sin value range) , but that only covers up small range of data and not huge number of values. Pardon me if i am asking for too much. I am just curious if its possible or not.</p>
<c><algorithm><logic><bitstuffing>
2019-04-23 11:31:02
LQ_CLOSE
55,811,114
Async validation with Formik, Yup and React
<p>I want to make async validation with formik and validationschema with yup but i can't find the example or demo.</p>
<reactjs><formik><yup>
2019-04-23 12:20:13
HQ
55,811,381
VBA: Single line if statement with multiple actions
<p>I really should be able to google this, but I can't find what I wanna know about.</p> <p>I want to check if a file exists. If not, a MessageBox should pop up and VBA should exit the sub.</p> <pre><code>If Dir("C:\file.txt", vbDirectory) = "" Then MsgBox "File doesn't exist" Exit Sub End If </code></pre> <p>It works, I just wanna know if you can you do this in a single line statement? Does VBA allow this when more than one thing is supposed to happen (like it is the case here)? This code doesn't work (syntax error): </p> <pre><code>If Dir("C:\file.txt", vbDirectory) = "" Then MsgBox "File doesn't exist" And Exit Sub </code></pre>
<excel><vba>
2019-04-23 12:36:19
HQ
55,811,686
In C# is it possible to instantiate a class with a value?
<p>In C# is it possible to instantiate a class with a value? That is to say if a class contains an array, is it possible to create a class that you pass the length of the desired array when the class is instantiated? </p>
<c#><arrays><class><instantiation>
2019-04-23 12:51:39
LQ_CLOSE
55,813,131
How to fix button clicked not updating but others do
<p>I'm making a math game. Every time I click a button a new question should appear with different results to choose from.</p> <p>However every time I click the button which I think is the result it doesn't update the text but the others do.</p> <p>See github: <a href="https://github.com/Combii/BrainTrainerSwift" rel="nofollow noreferrer">https://github.com/Combii/BrainTrainerSwift</a></p> <p><a href="https://i.stack.imgur.com/XjnqB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XjnqB.png" alt="enter image description here"></a></p>
<swift>
2019-04-23 14:06:45
LQ_CLOSE
55,813,744
How to locate the data column instead of character position in Perl and Bash?
I have research data shown below FRAM_# 20000000 5000000(fs) CN= 1 PRMRYTGT 16652 O 16654 H 1.036 8140 CA 2.586 7319 AL 1.963 Where, there are O,H,CA,and AL atoms. The first atom is target atom oxygen, and the rest of them are neighbors which bond with the target oxygen. Except for the first atom (oxygen), the integer number before each atom is the atom ID, and the float number after it is the bond length with the first atom O(ID=16652). $line="FRAM_# 20000000 5000000(fs) CN= 1 PRMRYTGT 16652 O 16654 H 1.036 8140 CA 2.586 7319 AL 1.963"; @values=split(/\s+/,$line); I can use loop to search the position of H in the array @values. However, is there any other way (not loop), like regex or BASH scripts, to get the position of H in the array? I highly appreciate it if you could provide me extra suggestion and help. NOTE: I have data lines more than 1 million, thus, I have to consider the code efficiency. H is my target atom in this example. In the data lines, the amount of H may be various.
<regex><bash><perl>
2019-04-23 14:43:01
LQ_EDIT
55,814,635
MySQL PHP - Returned column and split it into 2 arrays
<p>I'm using PHP and MySQL to pull some rows from a table. One column is called "item_notes" and this column has a dynamic number of comma-delimited values in it. If I printed 1 row, the column would look something like this: </p> <pre><code>item_1, new_item_1, ** note_1, ** note_2, item_2, ** note_3, old_item_1, new_item2 </code></pre> <p>Is there a way I can split this into 2 arrays using PHP, where 1 array is has only values that start with a ** and the ones that don't go into the other array?</p>
<php><mysql>
2019-04-23 15:29:13
LQ_CLOSE
55,814,781
Can anyone provide some VBA code to loop through several regions of a worksheet?
I'm looking for some VBA that will allow me to loop through several different REGIONS on a worksheet. Not individual cells, necessarily, but to jump from "currentregion" to the next "currentregion". And once the region is located, it should be selected and copied. I've tried setting a StartCell (via Cells.Find(What:="*") and then using that cell to select the corresponding 'currentregion'. The issue is how to move to the next 'currentregion', until all 'currentregions' on the worksheet have been copied/pasted. My results are inconsistent so far, where sometimes all the necessary regions are copied/pasted, but other times some of the regions are ignored (same exact worksheet, same exact data).
<excel><vba>
2019-04-23 15:37:02
LQ_EDIT
55,815,807
Test if all elements of a Foldable are the same
<p>I built a function that verifies that all elements of a foldable structure are equal.</p> <p>Compared to a similar function on the lists, it seems to me that the more general function is disproportionately complex, but I have not been able to simplify it.</p> <p>Do you have any suggestions?</p> <pre><code>import Data.Monoid import Data.Sequence as SQ import Data.Matrix as MT allElementsEqualL :: Eq a =&gt; [a] -&gt; Bool allElementsEqualL [] = True allElementsEqualL (x:ns) = all (== x) ns -- allElementsEqualL [1,1,1] -&gt; True allElementsEqualF :: (Foldable t, Eq a) =&gt; t a -&gt; Bool allElementsEqualF xs = case (getFirst . foldMap (First . Just) $ xs) of Nothing -&gt; True Just x -&gt; all (== x) xs -- allElementsEqualF [1,1,1] -&gt; True -- allElementsEqualF $ SQ.fromList [1,1,1] -&gt; True -- allElementsEqualF $ MT.fromLists [[1,1],[1,1]] -&gt; True </code></pre>
<haskell>
2019-04-23 16:37:05
HQ
55,816,312
A Haskell function that receive a List with different types and returns only a Integer List
I have a function like this : > '[(String, [Int], Int)]' I desire a function that returns a list that just returns a list of '[Int]' Input example : > [("R1",[6,10,14],6),("R2",[8,10,14],8),("R3",[11,15,24],11)] Output example (the bahavior that I want of the output) : > [6,8,10,11,14,15,24] I've been thinking in create a function of input, like this : > function :: [(String, [Int], Int)] > function = [("R1",[6,10,14],6),("R2",[8,10,14],8),("R3",[11,15,24],11)] And another to convert it to what I desire, like this : > convert :: [(String, [Int], Int)] -> [Int] > convert [] = [] > ... How can I develop the function "convert"?
<haskell><types>
2019-04-23 17:14:59
LQ_EDIT
55,816,950
How can I download php file with source?
<p>This is my demo url <a href="http://www.example.com/example.php" rel="nofollow noreferrer">http://www.example.com/example.php</a></p> <p>If we want to download example.php file with source code how can we do it?Is it possible?</p>
<php>
2019-04-23 18:00:24
LQ_CLOSE
55,817,007
Create new instance of class on calling a method c#
I have a Console Application which is injecting all the service through the constructor. I am also creating and initializing a Dictionary in the Constructor of my data access class. I am calling the data access method from my main class but I wanted to create a new instance of data access class and therefore dictionary whenever I will call the method GetData(). public class Startup { private static void Main(string[] args) { ServiceCollection serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(); serviceProvider.GetService<MyService>().Start(); } private static void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection.AddTransient<IMyServiceDataAccess, MyServiceDataAccess>(); serviceCollection.AddTransient<MyService>(); } } MyServiceClass: private readonly IMyServiceDataAccess _dataAccess; public MyService(IMyServiceDataAccess dataAccess) { _dataAccess = dataAccess; } public void Start() { var data = _dataAccess.GetData(); } DataAccess interface public interface IMyServiceDataAccess { List<int> GetData(); } DataAccess class: Dictionary<bool,List<int> dict; public MyServiceDataAccess() { dict = new Dictionary<bool,List<int>>() } public List<int> GetData() { // have to access the above dict and everytime I need new instance // of this dict } This will be multithreaded application so multiple threads can share the dictionary. One way is that create new instance of dictionary in get data method everytime it is called. Any help?
<c#><.net><dependency-injection>
2019-04-23 18:04:05
LQ_EDIT
55,817,481
Calculating percentile counts in python
<p>I have a large array ex <code>[1,4,5,9,1,4,6,....]</code></p> <p>I wanna calculate how many elements in total fall below each percentile. Ex: </p> <pre><code>4 numbers in 10percentile 7 numbers in 20 percentile 10 numbers in 30 percentile and so on till 100. ``` Is there a simple way to do this </code></pre>
<python><arrays><numpy>
2019-04-23 18:38:26
LQ_CLOSE
55,818,077
How to fix "Equations for ‘lefgNLista’ have different numbers of arguments"
I'm trying to learn list in Haskell but I have a error that me and my friends don't understand I've been trying with the definition of the arguments, but to be honest I don't understand too much of haskell yet. lefgNLista:: [Int]->[Int]->Int lefgNLista []=[] lefgNLista (fre1:fre2) fre3 = if fre1 == fre3 then 1+lefgNLista else fre1 : lefgNLista fre2 Also try with this but another error pop up lefgNLista []=[]=0 I expect the function count the amount of N numbers in the list, e.g. lefgNLista [1,3,5,7,8,8,2,3,8] 8 result 3
<haskell>
2019-04-23 19:21:39
LQ_EDIT
55,818,766
Display the currency with fractions
<p>I use this code to display amount using the built in currency Pipe:</p> <pre><code>&lt;td&gt;{{transaction.amount | currency: transaction.currency}}&lt;/td&gt; </code></pre> <p>Is there a way just to display the currency with fractions (.00) with the 3 characters for currency type? I don't need <code>$10,080.00</code> I need <code>10,080.00 USD</code> or <code>10080 JPY</code></p> <p>Is there a wya to get this visual result?</p>
<angular><typescript>
2019-04-23 20:14:17
LQ_CLOSE
55,823,296
ReactJS - prevState in the new useState React hook?
<p>I really like the new <a href="https://reactjs.org/docs/hooks-state.html" rel="noreferrer">React hooks</a> and I'm using them frequently for a project I'm working on. I'm coming across a situation where I want to use the <em>prevState</em> in the <code>useState</code> hook, but I'm not really certain on how to do this.</p> <p>I've tried something like this, but it fails to compile.</p> <pre><code>const [ someState, setSomeState ] = useState( new Map() ) setSomeState( prevState.someState.set( key, value ) ) </code></pre> <p>(by the way, this is to map an array of checkboxes to keep track of the ones that are check marked)</p> <p>I'm trying to follow this example <a href="https://medium.com/@wlodarczyk_j/handling-multiple-checkboxes-in-react-js-337863fd284e" rel="noreferrer">here</a>, but without using the <code>setState</code> function.</p> <p>Thanks for the help!</p>
<reactjs>
2019-04-24 06:00:53
HQ
55,823,655
database connection issue with PHP
Issue Is with the database connection for a open source Project(php). Everything works fine apart from the database connection required for login.Following is the error that can be seen after login. Warning: require_once(../mysqli_connect.php): failed to open stream: No such file or directory in /Applications/XAMPP/xamppfiles/htdocs/airline-ticket-reservation-system-master/login_handler.php on line 44 Fatal error: require_once(): Failed opening required '../mysqli_connect.php' (include_path='.:/Applications/XAMPP/xamppfiles/lib/php') in /Applications/XAMPP/xamppfiles/htdocs/airline-ticket-reservation-system-master/login_handler.php on line 44 mysqli_connect.php ````````````````````` <?php DEFINE('DB_USER','Harry'); DEFINE('DB_PASSWORD','passpasshello'); DEFINE('DB_HOST','localhost'); DEFINE('DB_NAME','airline_reservation'); $dbc=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) OR dies('Could not connect to MySQL:' . mysqli_connect_error()); ?>[enter image description here][1] [1]: https://i.stack.imgur.com/PK1gA.jpg
<php>
2019-04-24 06:29:05
LQ_EDIT
55,823,744
How to fix: cx_Oracle.DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library - Python
<p>I am establishing a connection to oracle 11g which is in a remote server using cx_oracle 7 with python 3.6.7. my OS in Ubuntu 18.04</p> <p>I have installed oracle instant client library with libclntsh.so but I am not getting the expected output.</p> <p>here is the code which i am using to connect to the oracle db</p> <pre><code>connection = cx_Oracle.connect("username/password@host/port") print (connection.version) connection.close() </code></pre> <p>when the script runs i expect to get the connection version instead i am getting the following error message</p> <blockquote> <p>File "script.py", line 13, in connection = cx_Oracle.connect("username/password@host/port") cx_Oracle.DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library: "libclntsh.so: cannot open shared object file: No such file or directory". See <a href="https://oracle.github.io/odpi/doc/installation.html#linux" rel="noreferrer">https://oracle.github.io/odpi/doc/installation.html#linux</a> for help</p> </blockquote>
<python-3.x><ubuntu-18.04><cx-oracle>
2019-04-24 06:36:01
HQ
55,824,159
get data from datalist to another page using session showing error input string is not in correct format
if(Session["proid"].ToString()!=null && Session["name"].ToString()!=null && Session["desc"].ToString()!=null && Session["price"].ToString()!=null) { int id = Convert.ToInt32(Session["proid"].ToString()); string proname = Session["name"].ToString(); string prodesc = Session["desc"].ToString(); string proprice=Session["price"].ToString(); }
<c#><asp.net>
2019-04-24 07:05:20
LQ_EDIT
55,824,445
How to sum the elements of an array list that stores objects
<p>I have a array list called Employees that stores Employee objects. Each employee has last name, first name, hour,pay pate, gross, tax, and net. I am trying to calculate the sum of each Employee's hour,pay pate, gross, tax, and net. Is there a way to extract specific element of an object from an array list?</p> <p>I have tried to calculate the sum through user's input, however, it does not seem to work. </p> <pre><code>//Employee class public Employee getinfo(Employee info ) { info.LastName(); info.FirstName(); info.fullname(); info.hours();//ask user to input hour toth += info.gethours(); info.payrate();//ask user to input payrate totpr+= info.getpayrate(); info.calcGross(); totg+= info.getgross(); info.calcTaxes(); tott+= info.gettax(); info.calcNet(); totn+= info.getnet(); return info; } //Employees class Employee max=new Employee(); public void add() { for (int i=0;i&lt;max.maxemps();i++) { Employee emp= new Employee(); emp.getinfo(emp); list.add(emp); } } </code></pre> <pre><code>//Actual results qwe, ewq 6.00 7.00 42.00 6.30 35.70 ttt, yyy 8.00 9.00 72.00 10.80 61.20 Total 0.00 0.00 0.00 0.00 0.00 Average 0.00 0.00 0.00 0.00 0.00 //Expecting Total Total 14.00 16.00 114.00 17.1 96.9 Average 7.00 8.00 57.00 8.505 48.45 </code></pre>
<java><arraylist>
2019-04-24 07:21:36
LQ_CLOSE
55,824,588
Array or Json to String
<p>change the string to array is</p> <pre class="lang-php prettyprint-override"><code>$string = '[{"name":"jack","address":"who knows"},{"name":"jill","address":"who knows too"}]'; $array = json_decode($array,true); </code></pre> <p>but what if it's reversed change array to string</p> <pre class="lang-php prettyprint-override"><code>$array = [{"name":"jack","address":"who knows"},{"name":"jill","address":"who knows too"}]; $string = $array; // $string is $string like on first example </code></pre>
<php><arrays><json>
2019-04-24 07:31:42
LQ_CLOSE
55,824,625
How to fix 'Object arrays cannot be loaded when allow_pickle=False' in the sketch_rnn algorithm
<p>I was running the sketch_rnn.ipynb on my jupyter notebook, upon loading the environment to load the trained dataset, it returned an error 'Object arrays cannot be loaded when allow_pickle=False'</p> <p>This is the code already used by google developers in developing the sketch_rnn algorithm that was even run in the google colab. In the past i have ran it myself on the google colab it worked but seems not to be working on my own jupyter notebook</p> <pre><code>from magenta.models.sketch_rnn.sketch_rnn_train import * from magenta.models.sketch_rnn.model import * from magenta.models.sketch_rnn.utils import * from magenta.models.sketch_rnn.rnn import * model_params.batch_size = 1 eval_model_params = sketch_rnn_model.copy_hparams(model_params) eval_model_params.use_input_dropout = 0 eval_model_params.use_recurrent_dropout = 0 eval_model_params.use_output_dropout = 0 eval_model_params.is_training = 0 sample_model_params = sketch_rnn_model.copy_hparams(eval_model_params) sample_model_params.max_seq_len = 1 return [model_params, eval_model_params, sample_model_params] [train_set, valid_set, test_set, hps_model, eval_hps_model, sample_hps_model] = load_env_compatible(data_dir, model_dir) </code></pre> <p>i expected the output to be </p> <pre><code>INFO:tensorflow:Downloading http://github.com/hardmaru/sketch-rnn- datasets/raw/master/aaron_sheep/aaron_sheep.npz INFO:tensorflow:Loaded 7400/300/300 from aaron_sheep.npz INFO:tensorflow:Dataset combined: 8000 (7400/300/300), avg len 125 INFO:tensorflow:model_params.max_seq_len 250. total images &lt;= max_seq_len is 7400 total images &lt;= max_seq_len is 300 total images &lt;= max_seq_len is 300 INFO:tensorflow:normalizing_scale_factor 18.5198. </code></pre> <p>But it gave me</p> <pre><code>ValueError: Object arrays cannot be loaded when allow_pickle=False </code></pre>
<python><machine-learning>
2019-04-24 07:34:15
HQ
55,826,221
Install icu4c version 63 with Homebrew
<p>I was trying to start <code>psql</code> but got</p> <pre><code>psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"? </code></pre> <p>When I used <code>postgres -D /usr/local/var/postgres</code>, got the following error:</p> <pre><code>dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.63.dylib Referenced from: /usr/local/bin/postgres Reason: image not found [1] 2559 abort postgres -D /usr/local/var/postgres </code></pre> <p>A quick search on <code>libicui18n.63.dylib</code> showed me I need <code>icu4c</code> lib with version 63. However <code>brew list icu4c</code> says I have the version 64.2. </p> <p>I tried both <code>brew install icu4c 63</code> &amp; <code>brew install icu4c@63</code> but no luck.</p> <p>Can anyone help, please? Thanks in advance.</p>
<postgresql><homebrew><icu4c>
2019-04-24 09:00:49
HQ
55,826,592
Capturing a lambda in another lambda can violate const qualifiers
<p>Consider the following code:</p> <pre><code>int x = 3; auto f1 = [x]() mutable { return x++; }; auto f2 = [f1]() { return f1(); }; </code></pre> <p>This will not compile, because <code>f1()</code> is not const, and <code>f2</code> is not declared as mutable. Does this mean that if I have a library function that accepts an arbitrary function argument and captures it in a lambda, I always need to make that lambda mutable, because I don't know what users can pass in? Notably, wrapping <code>f1</code> in <code>std::function</code> seems to resolve this problem (how?).</p>
<c++><lambda>
2019-04-24 09:20:31
HQ
55,827,688
Creating a markdown table with key bindings in Spacemacs
What is the best way to create a markdown table with key bindings in Spacemacs (evil mode)? The table should show single keystrokes (letters, numbers, punctuation) with and without modifiers, the function bound to them, and the first line of the function description. To clarify, this question is not about markdown or layout, but about how to automate this for a large number of key bindings.
<emacs><markdown><spacemacs>
2019-04-24 10:17:34
LQ_EDIT
55,828,637
how fix textcleaner script
hellow dear i try fix textcleaner script from Fred's ImageMagick Scripts http://www.fmwconcepts.com/imagemagick/textcleaner/index.php but i have following error > File "./textcleaner", line 200 > { > ^ >IndentationError: unexpected indent usage1() { echo >&2 "" echo >&2 "$PROGNAME:" "$@" sed >&2 -e '1,/^####/d; /^###/g; /^#/!q; s/^#//; s/^ //; 4,$p' "$PROGDIR/$PROGNAME" } usage2() { echo >&2 "" echo >&2 "$PROGNAME:" "$@" sed >&2 -e '1,/^####/d; /^######/g; /^#/!q; s/^#*//; s/^ //; 4,$p' "$PROGDIR/$PROGNAME" }
<bash>
2019-04-24 11:08:10
LQ_EDIT
55,829,453
Add parameter on jquery
<pre><code>$(function(){ $(document).on("click", '#btn', function() { $(document).ready(function(){ var sub=document.getElementById("tables").rows.length; for(var i=0;i&lt;sub;i++){ var doc=document.getElementById("checkbox"+i); if(doc.checked!=false){ $("#tables&gt;tr[id='i']").remove(); } } }); }); }); </code></pre> <p>help to add with parameter how to add variable tr[id='i']</p>
<javascript><jquery>
2019-04-24 11:54:06
LQ_CLOSE
55,829,756
Please explain DEFER's behaivour in golang
<p>As I know, defer is usually used to close or free resources. And using <code>defer FUNC ()</code> inside the block (function) of the code ensures that <code>FUNC ()</code> will call in case of any return from this block(function) or panic in this block (function).</p> <p>So - how to explain <code>defer</code> behavior in this code: (<a href="https://play.golang.org/p/FPA0wrRyw1f" rel="nofollow noreferrer">Example</a>):</p> <pre><code>package main import ( "fmt" "errors" ) func test() error { err := errors.New("some error") return err } func main() { if err := test(); err!=nil { fmt.Println("ERROR EXIT") return } defer fmt.Println("DEFER EXIT") fmt.Println("NORMAL EXIT") } </code></pre> <p>I expected to see this:</p> <pre><code>ERROR EXIT DEFER EXIT </code></pre> <p>But got it:</p> <pre><code>ERROR EXIT </code></pre> <p>Where am I wrong?</p>
<go><deferred-execution>
2019-04-24 12:11:24
LQ_CLOSE
55,829,787
Output problem - with itertools.groupby in pyton
I got this homework question, after taking a course on udemy I still cannot figure out how to get the right output like the Solution. furthermore: and how can i make it more efficace how can i do it without use explicit loops, but use list/dictionary comprehensions instead. this is what i do: def group_permutation_values(permutations_list): dic = {} f = lambda x: x[1] for key, group in itertools.groupby(sorted(permutations_list, key=f), f): dic[key] = list(group) return dic pass results = [((1, 2, 3), -4), ((1, 3, 2), -4), ((2, 1, 3), -2), ((2, 3, 1), -2), ((3, 1, 2), 0), ((3, 2, 1), 0)] print(group_permutation_values(results)) this is what i got : {-4: [((1, 2, 3), -4), ((1, 3, 2), -4)], -2: [((2, 1, 3), -2), ((2, 3, 1), -2)], 0: [((3, 1, 2), 0), ((3, 2, 1), 0)]} and the expect output: {-4: [(1, 2, 3), (1, 3, 2)], -2: [(2, 1, 3), (2, 3, 1)], 0: [(3, 1, 2), (3, 2, 1)]}
<python><group-by><itertools>
2019-04-24 12:13:39
LQ_EDIT
55,829,964
How is the best combination for Laravel VueJs?
<p>actually i just learn about Vue.js and i have some knowledge using Laravel. I want to combine both of them, im searching for tutorials on internet and i found 2 kind of combination.</p> <p>the first one is they separate Laravel and Vue, and the second one they combine both of them in Laravel Directory. Which one is the best for use guys? and can you guys tell me what is the benefits of each other? thank you so much.</p>
<javascript><php><laravel><web><vue.js>
2019-04-24 12:22:57
LQ_CLOSE
55,830,621
Abort evaluating Haskell expression if memory limit reached
<p>I'm using QuickCheck to test automatically-generated properties (similar to <a href="https://hackage.haskell.org/package/quickspec" rel="noreferrer">QuickSpec</a>) but one common problem I'm running into is exhausting the memory, either due to naive recursive generators or very large function outputs (e.g. one failure was caused by an exponential function for Peano numerals, which generated huge nested structures).</p> <p>I'm wondering if there's a way to abandon evaluation if a (resident) memory limit is reached. It seems <a href="https://stackoverflow.com/questions/20752083/haskell-time-limit-on-evaluation">we can do this for timeouts</a>, but memory seems to be trickier. This way, if we use too much memory, that test can be discarded (as if a <code>==&gt;</code> precondition had failed).</p> <p>I can see how to measure the whole program's memory usage, by looking at the source of the <code>weigh</code> package. This would be workable, but it would be much nicer (and robust) to measure it for one particular expression (perhaps by getting the memory used by one thread, or something?).</p> <p>For my purposes it would be enough to fully-normalise the expression, since I don't need to worry about recursive structures (I can apply this to the test results, which are effectively booleans).</p>
<haskell><memory><timeout><quickcheck>
2019-04-24 12:58:47
HQ
55,831,728
What is StatReloader while running Django?
<p>I've just created new Python 3.7 virtualenv with Django 2.2</p> <p>And each <code>runserver</code> it prints:</p> <blockquote> <p>Watching for file changes with StatReloader</p> </blockquote> <p>I could not find any info in Django's docs etc.</p> <p>Is it related specially to Django somehow? Does it go with Django? What it does? Why is it printed in red in PyCharm? Should I be careful about something? Could it be disabled?</p> <p>Big thx</p>
<django>
2019-04-24 13:51:12
HQ
55,832,170
Find All Instances of a String NOT Within HREF Tags?
I'm writing a JavaScript that goes through an html document and finds all instances of a keyword that are NOT links -- not within an HREF tag. For example, let's take the following HTML and I'm looking for the keyword "laptops." <p>I love laptops so much and these are <a href="mylink">some of my <i>favorite laptops</i></a>. Don't you love laptops also?</p> So I need a way to return instances 1 and 3 here, but not number 2, because it is within a link. I'm not sure if the right way to do this is with a Regex (I can't figure out the right one for this) or iterating through the DOM or something. I can use either JQuery or straight JS.
<javascript><jquery>
2019-04-24 14:12:22
LQ_EDIT
55,832,248
google Geometry Library in C#
<p>I have a point (latitude,longitude) ex : 25,-80 and I'm looking for a way in c# to check if this point is in specific polygon.</p> <p>I did some research and I found that containsLocation function contained within the Google Maps Geometry Library does exactly what I need but it is not available for c#. Here is an examples in which this method is utlized in JS:</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>// This example requires the Geometry library. Include the libraries=geometry // parameter when you first load the API. For example: // &lt;script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&amp;libraries=geometry"&gt; function initMap() { var triangleCoords = [ {lat: 25.774, lng: -80.19}, {lat: 18.466, lng: -66.118}, {lat: 32.321, lng: -64.757} ]; var coords = new google.maps.LatLng(25.774, -80.19); var bermudaTriangle = new google.maps.Polygon({paths: triangleCoords}); var result = google.maps.geometry.poly.containsLocation(coords, bermudaTriangle); alert('The location exist in polygon: '+result); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="map"&gt;&lt;/div&gt; &lt;!-- Replace the value of the key parameter with your own API key. --&gt; &lt;script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&amp;libraries=geometry&amp;callback=initMap" async defer&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>I found a c# library for gmaps google maps API for C# but it does not support the function containsLocation Is there a way to do the required above in c#?</p>
<javascript><c#><google-maps><google-poly>
2019-04-24 14:16:06
LQ_CLOSE
55,833,840
Convert Sql to Laravel Query Builder
how to convert this query to Laravel querry builder SELECT request_product_attributes.product_id, products.name, COUNT(request_product_attributes.product_id) as no_of_count from request_product_attributes,products where request_product_attributes.product_id=products.id GROUP BY request_product_attributes.product_id ORDER BY no_of_count DESC LIMIT 0,10
<laravel>
2019-04-24 15:38:05
LQ_EDIT
55,834,359
NoUiSlider - doesn't hide lines
<p>I have NoUiSlider 12.1.0 in my CSS theme (modern admin) and it works fine, but there is some problem with CSS. When I move by handle the slider lines behind them are not hiding / changing color. Do anyone know what can cause the problem, or what class/styles I should check?</p> <p><a href="https://i.stack.imgur.com/VGnSd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VGnSd.png" alt="enter image description here"></a></p>
<javascript><css><nouislider>
2019-04-24 16:09:08
LQ_CLOSE
55,834,669
Java Difference between current date and past date in Years, Months, Days, Hours, Minutes, Seconds
<p>I know this has been asked on here many times previously, but I'm haven't been able to find anything specific to my case. I'm trying to find the difference between the current datetime and a previous datetime, each with the format <code>yyyy-MM-dd HH:mm:ss.s</code>. Based on the answer given <a href="https://stackoverflow.com/questions/5351483/calculate-date-time-difference-in-java">here</a>, I've come up with the following code:</p> <pre><code>SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.s"); String earliestRunTime = "2017-12-16 01:30:08.0"; Date currentDate = new Date(); log.info("Current Date: {}", format.format(currentDate)); try { Date earliestDate = format.parse(earliestRunTime); long diff = currentDate.getTime() - earliestDate.getTime(); long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; long diffDays = diff / (24 * 60 * 60 * 1000) % 30; long diffMonths = diff / (30 * 24 * 60 * 60 * 1000) % 12; long diffYears = diff / (12 * 30 * 24 * 60 * 60 * 1000); return String.format("%s years, %s months, %s days, %s hours, %s minutes, %s seconds", diffYears, diffMonths, diffDays, diffHours, diffMinutes, diffSeconds); } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } </code></pre> <p>When I run the code, the JSON returns the following result:</p> <pre><code>lifetime: "41 years, -1 months, 14 days, 9 hours, 42 minutes, 37 seconds" </code></pre> <p>I have two questions here:</p> <ol> <li>Where am I going wrong in my calculations 41 years and a negative number? </li> <li>Is there a better way for me to do this? My current setup does not consider leap years or a 365 day year, and I need to take these into account.</li> </ol>
<java><date><datetime><difference><date-difference>
2019-04-24 16:27:27
LQ_CLOSE
55,834,845
Unable to install java8 with homebrew
<p>Installing <code>java8</code> with Homebrew seems to no longer be working. After running:</p> <pre><code>brew install caskroom/cask/java8 </code></pre> <p>I get the following error:</p> <pre><code>Error: Cask 'java8' is unavailable: '/usr/local/Homebrew/Library/Taps/caskroom/homebrew-cask/Casks/java8.rb' does not exist. </code></pre> <p>Simply doing:</p> <pre><code>brew cask install java8 </code></pre> <p>Errors out with:</p> <pre><code>Error: Cask 'java8' is unavailable: No Cask with this name exists. </code></pre> <p>This seems like a recent development because I remember installing it this way a few months ago. Any suggestions on how to properly install <code>java8</code> on MacOS nowadays?</p>
<java><macos><java-8><homebrew>
2019-04-24 16:39:07
HQ
55,835,701
Trying to build a web page that can generate an image
<p>I've been having trouble getting started with this project because I'm not sure what I should be searching for. Any help on where/how to start would be greatly appreciated.</p> <p>The idea is, I have an image of a postcard that I want users to be able to upload and add their logo to a designated blank area and then download it. Hopefully all through a single web page.</p> <p>If it can be all be done locally through their browser without actually uploading anything to my web server, even better!</p> <p>So, I'm trying to figure out what I should use to accomplish this.</p> <p>Thank you again in advance for any suggestions and help!</p>
<javascript><php><html><image-processing><web-applications>
2019-04-24 17:38:30
LQ_CLOSE
55,836,399
how has-a-relationship is said to be composition?
<p>I have searched books read through website but cannot get a justified answer. whats is the proper meaning of composition and how we attain has-a-relationship in the program.</p>
<java><composition>
2019-04-24 18:25:38
LQ_CLOSE
55,837,075
My instance is not updating in my while loop
<p>I want to recalculate the hash by changing the nonce by 1. but the instance of self.hash is not changing. </p> <p>I am not that experienced and do not know how to fix these types of issues</p> <pre><code>import hashlib class Block: def __init__(self, timestamp, transaction, previousHash = ''): self.timestamp = timestamp self.transaction = transaction self.nonce = 0 self.previousHash = previousHash self.hash = self.calculateHash() def mineBlock(self): checkIfTrue = str(self.hash).startswith('0') while checkIfTrue != True: self.nonce += 1 self.hash = self.calculateHash() print(self.hash) print("block mined") def calculateHash(self): h = hashlib.sha256((str(self.timestamp) + str(self.transaction) + str(self.previousHash) + str(self.nonce)).encode('utf-8')) return h.hexdigest() </code></pre>
<python>
2019-04-24 19:13:14
LQ_CLOSE
55,838,815
Issue with creating a VIEW inside a Stored Procedure
I needed to Parse a JSON string from a column in a SQL Server 2008 r2 table, so I used 2 Views and 3 tables and several stepped queries. Everything worked. Now after populating several databases I need to allow for Triggers to be placed on a specific table. Since only a Stored Procedure can be called from a Trigger I was converting everything into an SP. All went well except for a CREATE VIEW statement. I've wrapped that into EXEC but I'm still getting a syntax error regarding an unclosed quote. I've tried several different ways of enclosing keywords but nothing worked. Here's a snippet of the code: EXEC ('If object_ID(''vw_BuildLookup01'',''V'') IS NOT NULL DROP VIEW vw_BuildLookup01;') EXEC ('If object_ID(''vw_BuildLookup02'',''V'') IS NOT NULL DROP VIEW vw_BuildLookup02;') EXEC ('CREATE VIEW [dbo].[vw_BuildLookup01] AS SELECT DISTINCT t.tblKey, t.Name AS MetricTypesName, m.tblKey AS MetricKey, m.Name AS MetricName, m.MetricLimitedValues, f.Value FROM OccurrenceMetricFacts f INNER JOIN Metrics m ON f.MetricKey = m.tblKey INNER JOIN MetricTypes t ON m.MetricTypeKey = t.tblKey WHERE m.MetricLimitedValues IS NOT NULL AND t.DeletedDate IS NULL AND f.Value IS NOT NULL ') EXEC ('CREATE VIEW [dbo].[vw_BuildLookup02] AS SELECT v.tblKey, v.MetricTypesName, v.MetricKey, v.MetricName, REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(v.MetricLimitedValues, '"Name":"', ''),'","Value"', ''),'{', ''), '}',''),'[', ''), ']', '') AS MetricLimitedValues, v.Value FROM vw_BuildLookup01 v INNER JOIN MetricTypes t ON t.tblKey = v.tblKey WHERE t.DeletedDate IS NULL ') The syntax error is in the CREATE VIEW [dbo].[vw_BuildLookup02] after the nested REPLACE commands the '"Name":"' has the dreaded red squiggly line underneath. I've read too many articles, rewrote the query too many ways, I need help. Thanks in advance.
<sql-server>
2019-04-24 21:27:28
LQ_EDIT
55,839,512
Lombok @SuperBuilder workaround on IntelliJ
<p>I've a class Product:</p> <pre><code> @Data
 @SuperBuilder public class Product { private String name; private String manufacturer; } </code></pre> <p>and an extended class</p> <pre><code>@Data
 @SuperBuilder public class Frame extends Product{ private String model; } </code></pre> <p>I'm trying to create a Frame object using the builder:</p> <pre><code> return Frame.builder()
 .name("Frame ABC")
 .manufacturer("Manufacturer")
 .model("Model 1")
 .build(); </code></pre> <p>I'm using IntelliJ 2019.1.1 with lombok plugin but unfortunately the compiler marks as error the .name() and .manufacturer() methods. I saw this <a href="https://github.com/mplushnikov/lombok-intellij-plugin/issues/513" rel="noreferrer">https://github.com/mplushnikov/lombok-intellij-plugin/issues/513</a> issue opened and I'm wondering if there is a workaround to make my code to work.</p>
<java><lombok><intellij-lombok-plugin>
2019-04-24 22:41:01
HQ
55,842,077
How i can use horizontal scroll view in fragments?
I'm working with fragments i have a requirement to use horizontal scroll view inside a fragment.I know how to add it in activity but I have no idea how to add horizontal scroll view in fragment?
<android><android-fragments>
2019-04-25 04:58:17
LQ_EDIT
55,842,088
Svelte Hot Reloading Issue
<p>Recently started playing with Svelte using the sveltejs template. Everything is working fine, however when I do any change in the files it doesn't hot reload the changes to the web browser, so I have to manually refresh the page to see the changes. Is there any option in the settings to enable that feature or is it not possible at this point?</p>
<svelte><hot-reload>
2019-04-25 04:59:10
HQ
55,842,241
decode the json file in java
i am trying to decode JSON file in json format using UTF-8, But its printing no value JSONParser jsonParser = new JSONParser(); FileReader file = new FileReader("C:/Users/aab6cob/Desktop/jsonFile/170902_K0_RUCd_ML_F4974.txt.insights-json"); BufferedReader filBufferedReader = new BufferedReader(file); String st; while((st=filBufferedReader.readLine())!=null){ byte[] tempByte = st.getBytes("UTF-8"); String tempString = new String(tempByte); System.out.println(tempString); }
<java><jsondecoder>
2019-04-25 05:15:58
LQ_EDIT
55,844,077
FindBugs IDEA - ClassNotFoundException com.google.wireless.android.sdk.stats.IntellijIndexingStats
<p>FindBugs IDEA v1.0.1 Android Studio 3.4</p> <p>I get this error when running FindBugs. I don't use com.google.wireless.android.sdk anywhere in the app.</p> <pre><code>Error:Internal error: (java.lang.ClassNotFoundException) com.google.wireless.android.sdk.stats.IntellijIndexingStats$Index java.lang.ClassNotFoundException: com.google.wireless.android.sdk.stats.IntellijIndexingStats$Index at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at com.intellij.util.indexing.counters.IndexCounters.&lt;clinit&gt;(IndexCounters.java:34) at com.intellij.util.indexing.impl.MapReduceIndex.&lt;init&gt;(MapReduceIndex.java:86) at org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex$CompilerMapReduceIndex.&lt;init&gt;(CompilerReferenceIndex.java:214) at org.jetbrains.jps.backwardRefs.index.CompilerReferenceIndex.&lt;init&gt;(CompilerReferenceIndex.java:73) at org.jetbrains.jps.backwardRefs.JavaCompilerBackwardReferenceIndex.&lt;init&gt;(JavaCompilerBackwardReferenceIndex.java:12) at org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexWriter.initialize(JavaBackwardReferenceIndexWriter.java:74) at org.jetbrains.jps.backwardRefs.JavaBackwardReferenceIndexBuilder.buildStarted(JavaBackwardReferenceIndexBuilder.java:40) at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild(IncProjectBuilder.java:358) at org.jetbrains.jps.incremental.IncProjectBuilder.build(IncProjectBuilder.java:178) at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:138) at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:302) at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:135) at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler.lambda$channelRead0$0(BuildMain.java:229) at org.jetbrains.jps.service.impl.SharedThreadPoolImpl.lambda$executeOnPooledThread$0(SharedThreadPoolImpl.java:42) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) </code></pre>
<android><findbugs>
2019-04-25 07:34:12
HQ
55,844,680
deadlock detected when trying to start server
<p>I have a simple application where I am using both django and django-rest-framework.</p> <p>Quite often, when I try to start the local server (<code>python manage.py runserver</code>), I get the following exception:</p> <pre><code>Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "/project/venv/lib/python3.7/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/project/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/project/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/project/venv/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/project/venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/project/venv/lib/python3.7/site-packages/django/contrib/admin/checks.py", line 80, in check_dependencies for engine in engines.all(): File "/project/venv/lib/python3.7/site-packages/django/template/utils.py", line 90, in all return [self[alias] for alias in self] File "/project/venv/lib/python3.7/site-packages/django/template/utils.py", line 90, in &lt;listcomp&gt; return [self[alias] for alias in self] File "/project/venv/lib/python3.7/site-packages/django/template/utils.py", line 81, in __getitem__ engine = engine_cls(params) File "/project/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 25, in __init__ options['libraries'] = self.get_templatetag_libraries(libraries) File "/project/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 43, in get_templatetag_libraries libraries = get_installed_libraries() File "/project/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 108, in get_installed_libraries for name in get_package_libraries(pkg): File "/project/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 121, in get_package_libraries module = import_module(entry[1]) File "/project/venv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 1006, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 983, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 967, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 677, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 728, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_removed File "/project/venv/lib/python3.7/site-packages/rest_framework/templatetags/rest_framework.py", line 15, in &lt;module&gt; from rest_framework.renderers import HTMLFormRenderer File "/project/venv/lib/python3.7/site-packages/rest_framework/renderers.py", line 20, in &lt;module&gt; from django.test.client import encode_multipart File "/project/venv/lib/python3.7/site-packages/django/test/client.py", line 23, in &lt;module&gt; from django.test import signals File "&lt;frozen importlib._bootstrap&gt;", line 980, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 149, in __enter__ File "&lt;frozen importlib._bootstrap&gt;", line 94, in acquire _frozen_importlib._DeadlockError: deadlock detected by _ModuleLock('django.test.signals') at 4420467792 Performing system checks... </code></pre> <p>After a couple of retries, the server starts successfully. Therefore, it is not a show-stopper but it is quite annoying.</p> <p>Since I am quite new to Django, I was wondering if there was a way to prevent such an error.</p>
<python><django><django-rest-framework><python-3.7>
2019-04-25 08:11:51
HQ
55,846,125
How to put the name of the file in advance when uploading?
I want to save the uploaded file with "1.jpg" name. If it already exists in the "upload" folder, save with "2.jpg", and if file "2.jpg" already exists in the "upload" folder, Wait until the another script clears one of them. If, after some time (about 120 seconds), none of the two files was erased, it will display an error message. What code should I use?
<php>
2019-04-25 09:35:03
LQ_EDIT
55,847,935
MySQL select statement not working for `*`
<p>Trying to load the data from my SQL tables with the following statement</p> <pre><code>select `*` from `table_name` </code></pre> <p>Unfortunately, it throws an error in the MySQL <strong>5.6.33</strong> version and another side it works fine in the <strong>5.7.25</strong> version.</p> <p>I'm confused where it is the configuration thing or it is due to the version change because I'm not able to find out the clear documentation on the above thing.</p> <p>Also, what is the preferred way to write a select statement? Should I go with <strong>``</strong> or not.</p>
<php><mysql>
2019-04-25 11:11:44
LQ_CLOSE
55,848,101
Memory leak using gridsearchcv
<p><strong>Problem:</strong> My situation appears to be a memory leak when running gridsearchcv. This happens when I run with 1 or 32 concurrent workers (n_jobs=-1). Previously I have run this loads of times with no trouble on ubuntu 16.04, but recently upgraded to 18.04 and did a ram upgrade.</p> <pre><code>import os import pickle from xgboost import XGBClassifier from sklearn.model_selection import GridSearchCV,StratifiedKFold,train_test_split from sklearn.calibration import CalibratedClassifierCV from sklearn.metrics import make_scorer,log_loss from horsebet import performance scorer = make_scorer(log_loss,greater_is_better=True) kfold = StratifiedKFold(n_splits=3) # import and split data input_vectors = pickle.load(open(os.path.join('horsebet','data','x_normalized'),'rb')) output_vector = pickle.load(open(os.path.join('horsebet','data','y'),'rb')).ravel() x_train,x_test,y_train,y_test = train_test_split(input_vectors,output_vector,test_size=0.2) # XGB model = XGBClassifier() param = { 'booster':['gbtree'], 'tree_method':['hist'], 'objective':['binary:logistic'], 'n_estimators':[100,500], 'min_child_weight': [.8,1], 'gamma': [1,3], 'subsample': [0.1,.4,1.0], 'colsample_bytree': [1.0], 'max_depth': [10,20], } jobs = 8 model = GridSearchCV(model,param_grid=param,cv=kfold,scoring=scorer,pre_dispatch=jobs*2,n_jobs=jobs,verbose=5).fit(x_train,y_train) </code></pre> <p><strong>Returns:</strong> UserWarning: A worker stopped while some jobs were given to the executor. This can be caused by a too short worker timeout or by a memory leak. "timeout or by a memory leak.", UserWarning</p> <p><strong>OR</strong></p> <p>TerminatedWorkerError: A worker process managed by the executor was unexpectedly terminated. This could be caused by a segmentation fault while calling the function or by an excessive memory usage causing the Operating System to kill the worker. The exit codes of the workers are {SIGKILL(-9)}</p>
<memory-leaks><scikit-learn><grid-search><gridsearchcv>
2019-04-25 11:21:26
HQ
55,848,548
How to search for a string and print it's related details in c++
I'm trying to compare an inputed string to a returned string while looping through a file and if the inputed string is equal to the returned string from the file it prints the details associated with the file but it keeps giving me the error message invalid use of void expression... > void search_course(string course){ int check=0; student st; > ifstream file; > file.open("student.dat",ios::binary|ios::out); if(!file) { cout<<"No Such file in Database..."; return; } while(!file.eof() > && check==0) { file.read((char *) &st, sizeof(student)); > if(strcmp(st.return_prog(), course) == 0) { st.showid_detail(); > } > } > file.close(); } int main(){ > system("CLS"); string course="physics"; search_course(course); return 0; } The showid_detail() is a function in a class which displays information about a record as follows....id, index, name, course, year, Hall return_prog() is a void function that outputs a course of a student I expected the code to display all those students doing physics, but it kept telling me invalid use of void expression...
<c++>
2019-04-25 11:44:04
LQ_EDIT
55,849,896
Why is my program is outputting '0' when run, even though it is not supposed too?
<p>I am quite new to c++, and was just playing around with if statements, so I made this program:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int getMax(int num1, int num2){ if (num1&gt;num2) { cout &lt;&lt; num1 &lt;&lt;endl; }else{ cout &lt;&lt; num2 &lt;&lt;endl; } return EXIT_SUCCESS; } int main(){ cout&lt;&lt;getMax(7,13)&lt;&lt;endl; return 0; } </code></pre> <p>My getMax function takes two parmeters and is supposed to output the greater of the 2 numbers — in this case 13. But instead of only outputting 13, it also outputs 0. Why is this happening?</p>
<c++><if-statement><output>
2019-04-25 13:00:25
LQ_CLOSE
55,850,782
variable referenced before assignment error in python
<p>In my code I am testing if a user has AWS access keys:</p> <pre><code>for response in paginator.paginate(UserName=user_name): if len(response['AccessKeyMetadata']) and 'AccessKeyId' in response['AccessKeyMetadata'][0].keys(): key1 = response['AccessKeyMetadata'][0]['AccessKeyId'] </code></pre> <p>Later in my code I test if key1 exists:</p> <pre><code>if key1: print("\nAccess Key 1: ", key1) else: print("The user does not have any keys.") </code></pre> <p>If the user has NO keys at all, the function fails with this error:</p> <pre><code> File ".\aws_iam_utils.py", line 1430, in rotate_access_keys if key1: UnboundLocalError: local variable 'key1' referenced before assignment </code></pre> <p>Am I testing if key1 exists correctly? Why am I getting an unbound local error, when it should just print out the statement in the else clause?</p>
<python>
2019-04-25 13:45:32
LQ_CLOSE
55,852,044
Is there any alternate command of ExecuteNonQuery?
<p>I am making project on Hospital Management Information System using c#, and want to insert data to SQL Server from c#, but ExecuteNonQuery Command is not working. Is there any alternate of this command?</p> <pre><code>connection.Open(); command = new SqlCommand(sql, connection); command.CommandType = CommandType.Text; int i = command.ExecuteNonQuery(); command.Dispose(); connection.Close(); </code></pre>
<c#><sql-server>
2019-04-25 14:45:52
LQ_CLOSE
55,853,977
How to get the current namespace of current context using kubectl?
<p>I am trying to get the namespace of the currently used Kubernetes context using <code>kubectl</code>.</p> <p>I know there is a command <code>kubectl config get-contexts</code> but I see that it cannot output in json/yaml. The only script I've come with is this:</p> <pre class="lang-sh prettyprint-override"><code>kubectl config get-contexts --no-headers | grep '*' | grep -Eo '\S+$' </code></pre>
<kubernetes>
2019-04-25 16:37:15
HQ
55,854,087
how to resize a range to a specific column
I have data in a range from B2:P10. If i select a cell (for example c3), what is the vba code to select right to column p (so c3:p3). There is text in column q so i cant select right to the 'end'. i've tried using offset and resize functions but everything i try is relative and doesnt stop at the absolute of column P
<excel><vba><resize><offset>
2019-04-25 16:44:14
LQ_EDIT
55,854,416
Purpose of reference template arguments
<p>You can use a reference to a global object as a template parameter. For example thus:</p> <pre><code>class A {}; template&lt;A&amp; x&gt; void fun() { } A alpha; int main() { fun&lt;alpha&gt;(); } </code></pre> <p>In what situation might a reference template argument be useful?</p>
<c++><templates>
2019-04-25 17:06:31
HQ
55,854,451
What does const myObject = { ...object1, ...object2 } evaluate to in JS?
<p>I inherited some code in a React Native codebase and was just curious as to what this syntax means. Can't seem to find a good answer by googling but I have console logged it seems like: </p> <pre><code> const myObject = object2 ? ojbect2 : object1 </code></pre> <p>Is similar to: </p> <pre><code> const myObject = { ...object1, ...object2} </code></pre>
<javascript><arrays><object><operators>
2019-04-25 17:08:57
LQ_CLOSE
55,854,498
How to convert an integer to byte literal in Rust?
<p>I am trying to convert an integer to byte literal in Rust:</p> <pre><code>for x in 0..10000 { let key = x.to_???; other_function(key); } </code></pre> <p>Could not find it in the docs.</p>
<rust>
2019-04-25 17:12:51
LQ_CLOSE
55,854,519
How to ask user for username or other data with vs code extension API
<p>I want to receive some input from the user, such as <code>username</code> and use it in the code. How to achieve that?</p>
<visual-studio-code><vscode-extensions>
2019-04-25 17:14:01
LQ_CLOSE
55,854,838
Is WPF ideal to create a midi editor windows desktop app?
<p>I'm planning to create a midi editor, like the <a href="https://i.stack.imgur.com/j3Hov.png" rel="nofollow noreferrer">piano roll</a> in DAWs like Reaper, Cubase, Fl Studio.. To get the midi data in, i will use NAudio's library. For the UI, i'm thinking WPF since that's the only framework i have experience with.</p> <p>So my question is: Do i have much better options other than c# and wpf for this task? If so, what would it be and why?</p>
<c#><wpf><desktop-application><midi><naudio>
2019-04-25 17:36:14
LQ_CLOSE
55,855,572
Select button in selemium c#
<p>How can I select the last button in this code? the only thing that changes is the value.</p> <p>button class="btn btn-link btn-star" data-value="26">/button></p> <p>button class="btn btn-link btn-star" data-value="27">/button></p>
<c#><selenium>
2019-04-25 18:29:16
LQ_CLOSE